虚拟机:
sudo apt update && sudo apt install -y php7.2 php-fpm nginx
将 PHP-FPM 的配置文件 /etc/php/7.2/fpm/pool.d/www.conf
中的
listen = /run/php/php7.2-fpm.sock
注释掉,新增
listen = 0.0.0.0:9090
最后重启 php-fpm:
sudo systemctl daemon-reload && sudo systemctl restart php7.2-fpm.service
仅在 192.168.56.112 上执行
新建文件 /etc/nginx/conf.d/php-session-test.conf
,其内容为:
upstream fpm-backend {
server 192.168.56.112:9090;
# server 192.168.56.113:9090;
# ip_hash;
}
server {
listen 8080;
# server_name XXX default_server;
root /var/www/php-session-test;
index index.php index.htm index.html;
location ~ \.php {
include /etc/nginx/fastcgi.conf;
fastcgi_pass fpm-backend;
add_header Upstream-Addr $upstream_addr;
}
location / {
try_files $uri $uri/ = 404;
}
}
然后重启 Nginx:
sudo systemctl daemon-reload && sudo systemctl restart nginx.service
创建目录:
sudo mkdir -p /var/www/php-session-test
新增文件 index.php:
<?php
session_start();
$username = $_SESSION["username"];
if (!isset($username))
{
echo "尚未登陆," . '<a href="/login.php">点此登陆</a>';
}
else {
echo "Hello " . $username . ".";
}
?>
新增文件 login.php:
xxxxxxxxxx
<?php
$login_page_html = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆页面</title>
</head>
<body>
<fieldset>
<legend>请登陆</legend>
<form action="login.php" method="post">
user:
<input type="text" placeholder="请输入用户名" name="username" id="username"><br/>
pwd:
<input type="password" placeholder="请输入密码" name="password" id="password"><br/>
<button id="btn" type="submit">提交</button>
</form>
</fieldset>
</body>
</html>
HTML;
$request_method = $_SERVER['REQUEST_METHOD'];
if ($request_method == 'GET')
{
echo $login_page_html;
}
else
{
$username = $_POST["username"];
$password = $_POST["password"];
# 校验用户名和密码
session_start();
$_SESSION["username"] = $username;
header("location: /");
}
?>