php设置session值和cookies的学习示例_php实例
第一步:先在本地写一个登陆页面和一个内容页面(登陆了才能进去)吧。代码大致如下:
下面是login.php,用于请求登陆的,通过post传递参数,如果登陆成功就会注册session。
session_start();
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == 'admin' && $password == 'admin') {
$_SESSION['username'] = $username;
echo "进入网站";
} else {
echo "-1";
}
}
?>
下面是content.php,会验证session,用来当网站的内容页,登陆了才能看到正确的内容。
session_start();
if (isset($_SESSION['username'])) {
echo "login ok";
} else {
echo "not login";
}
?>
接下来先讲HttpURLConnection这个类,先使用这个类直接请求content.php页面,理所应当的返回了"-1"。如果先用这个类去请求login.php,并传递正确的参数,就会显示登陆成功,这个时候再去用这个类请求content.php,依然是返回"-1",很显然,HttpURLConnection并没有记录我们登陆的状态,或者说服务器认识刚刚登陆成功的人,但这次请求content.php的人它依然不认识。这就说明了HttpURLConnection的每一次请求都是独立的,都是一次新的请求,或者说每一次请求都是一个新的会话(session)。
然后我就用chrome去开我自己写的那个测试的网页,发现在同一个网站下,同一次会话中,有一个sessionid是不会变的。
就是上面这个东西,如果开着某个页面,无论如何刷新,或者跳转到这个服务器下的其他网站,这个SESSIONID的值都不会改变,但是如果关掉这个服务器下的所有页面,再重新打开这样的一个页面,这个SESSIONID的值就被重新生成了。
于是用HttpURLConnection的情况,第一次登陆login.php是一个SESSIONID,确实登陆成功了,服务器记住的是SESSIONID为A的情况(假设是A好了),但再去请求content.php的时候,SESSIONID就不是A了,服务器就认为你没有登陆,于是就显示了“-1”。问题搞明白了,那么只需要在HttpURLConnection请求的时候,给它加上SESSIONID这个头部就行了。最终代码如下:
public class NetHelper {
/**
* SESSIONID
* */
private String sessionId = "";
/**
* 发送一条请求,将内容以字符串返回
* @param url 请求的地址
* @return 返回的内容
* */
public String request(String url) throws IOException {
URL uUrl = new URL(url);
HttpURLConnection huc = (HttpURLConnection) uUrl.openConnection();
huc.addRequestProperty("Cookie", sessionId); //为什么是“Cookie”,Chrome打开F12自己看看就明白了
huc.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream()));
String data = "";
String line = "";
while ((line = br.readLine()) != null) {
data = data + line;
}
return data;
}
/**
* 发送登陆请求,并将SESSIONID保存起来
* @param url 登陆请求的地址
* @return 返回的内容
* */
public String login(String url) throws IOException {
URL uUrl = new URL(url);
HttpURLConnection huc = (HttpURLConnection) uUrl.openConnection();
//设置请求方式
huc.setRequestMethod("POST");
//设置post参数
StringBuffer params = new StringBuffer();
params.append("username=").append("admin").append("&").append("password=").append("admin");
byte[] bytes = params.toString().getBytes();
huc.getOutputStream().write(bytes);
huc.connect();
//从headers中取出来,并分割,为什么要分割,Chrome打开F12自己看看就明白了
String[] aaa = huc.getHeaderField("Set-Cookie").split(";");
sessionId = aaa[0];
BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream()));
String data = "";
String line = "";
while ((line = br.readLine()) != null) {
data = data + line;
}
return data;
}
}
接下来就是使用HttpClient,代码类似的,我做了相同的实验,结果就直接出来了,HttpClient会自动的管理Session,第二次请求不需要手动去设置Session就可以登录上。
public class NetClient {
private HttpClient client = null;
public NetClient() {
client = new DefaultHttpClient();
}
public String request(String url) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost(url);
HttpResponse res = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
String data = "";
String line = "";
while ((line = br.readLine()) != null) {
data = data + line;
}
return data;
}
public String login(String url) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost(url);
//设置post参数的方式还真是不人性化啊……
ArrayList
pa.add( new BasicNameValuePair( "username", "admin"));
pa.add( new BasicNameValuePair( "password", "admin"));
post.setEntity( new UrlEncodedFormEntity(pa, "UTF-8"));
HttpResponse res = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
String data = "";
String line = "";
while ((line = br.readLine()) != null) {
data = data + line;
}
return data;
}
}
最后总结一下,Session验证的方式是在一次会话中,为每一个客户端都生成了一个SESSIONID,如果是成功登陆的,服务器端就会记录好,登陆成功的SESSIONID,如果登陆失败或者新的SESSIONID,都将无法验证登陆,这就是SESSION验证登陆的基本情况。
而HttpURLConnection和HttpClient这两个类都可以用来网络请求,但稍有不同,HttpuRLConnection每一次请求都是新的会话,如果需要去验证SESSIONID,就必须手动的去设置Header,HttpClient就能智能的管理Session,不需要手动设置,实际上HttpClint就类似于一个程序中的小浏览器。
最大的槽点我觉得就是这两个类设置post参数的方式都很2B一点都不方便……
另外HttpClient不能同时发送两次请求,如果一个请求还没有结束或者关闭,又马上开启另一个请求。就会报警告,截个图吧
所以我综合考虑了下,以后还是尽量都使用HttpURLConnection吧。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.
