Эта статья иллюстрирует использование PHP-файлов cookie , сеанса и реализацию функции автоматического входа пользователя в систему. Поделитесь для вашей справки следующим образом:
Использование файлов cookie
// Generating cookies // Note: The setcookie () function must precede the < HTML > tag. // Setcookie (name, value, expire, path, domain); //name, value, expiration time, valid path, valid domain name // path, optional; if the path is set to "/", cookies will be valid throughout the domain name. If the path is set to "/ test /", cookies will be valid in the test directory and all its subdirectories. The default path value is the current directory in which cookie resides. // domain, optional; in order for cookies to be valid in all subdomains of example.com, you need to set the domain name of cookies to ".example.com". When you set the cookie domain name to www.example.com, cookies are only valid in the WWW subdomain name. Default the current domain name. setcookie("user", "Alex Porter", time()+3600); setcookie("userid", "1000569852", time()+3600); // Acquisition var_dump($_COOKIE); // isset () function to confirm whether cookies have been set: if (isset($_COOKIE["user"])){ echo "Welcome " . $_COOKIE["user"] . "!
"; } else{ echo "Welcome guest!
"; } // When you delete cookies, you should change the expiration date to the past time point. setcookie("user", "", time()-3600);
Использование сеанса
// Session-specific: Useable for all pages in an application; session information is temporary and will be deleted after the user leaves the site. // Virtual host user. Setting up a storage directory requires read and write permissions $savePath = getcwd().'/session_save_dir/'; //echo $savePath; Session_save_path ($savePath); //session_start before opening. Session_id ('phpjianlong'); session_id () is called before the // session_start () function; the name is the same variable session_start(); // Storage and Value $_SESSION['views']=123456789; $_SESSION ['name']='php Jianlong'; $_SESSION['array']=array('a','b','c','d'); echo "Pageviews=". $_SESSION['views']; var_dump($_SESSION); // Judgment of existence if(isset($_SESSION['views'])){ $_SESSION['views']=$_SESSION['views']+1; } else{ $_SESSION ['views']= 1; // No assignment exists } echo "Views=". $_SESSION['views']; // Session deletion unset($_SESSION['name']); var_dump($_SESSION); // Note: session_destroy() will reset session, and you will lose all stored session data. Session_destroy(); // without parameters Session_start(); // To reopen the session is to reinitialize the $_SESSION array; var_dump($_SESSION); // Gets/sets the current session ID. Browsers automatically generate cookies called PHPSESSID echo session_id(); Session_id ('phpjianlong'); session_id () is called before the // session_start () function; the name is the same variable
Разница между сеансом и файлами cookie:
1. Сеанс находится на сервере, файлы cookie хранятся в браузере 2. Сеанс может хранить массивы, значение файла cookie может быть только строкой 3. Сеанс не может установить срок действия, файл cookie может установить срок действия. 4. Сессия оценивает информацию о пользователе на основе файлов cookie и отключает файлы cookie. Сеанс затронут и не может быть использован. Идентификатор сеанса также можно передать вручную через URL-адрес и скрытую форму. Сохраните идентификатор сеанса в виде файлов, баз данных и т.д.
URL-адрес выглядит следующим образом: http://www.openphp.cn/index.php?PHPSESSID = bba5b2a240a77e5b44cfa01d49cf9669
Реализация автоматического входа пользователя в систему
// Method 1: Cookie, save the username and password in Cookie (maybe the string encrypted by md5), and verify it every time you request a page. If the username and password are stored in the database, the database query should be executed once at a time, which will cause redundant burden to the database. Because the information in the client Cookie can be viewed and modified by the user. It is unsafe to abandon this method. // Method 2: session, using cookie to save session ID for a long time. // The Session file is found in the system temporary folder. The general file name is sess_4c83638b3b0dbf65583181c2f89168ec, followed by a 32-bit encoded random string. Open it with an editor and take a look at its contents: // Variable Name | Type: Length: Value; // Set Session's lifetime: session_start(); // Keep for 5 days $lifeTime = 5 * 24 * 3600; setcookie(session_name(), session_id(), time() + $lifeTime, "/"); // Then the browser enters the corresponding address here, and the server obtains the session ID saved by the cookie. According to the content of the session id, the browser automatically logs in.
Больше читателей,интересующихся контентом, связанным с PHP, могут ознакомиться с темами этого сайта: Краткое описание использования файлов cookie в PHP, Полное введение в базовую грамматику PHP, Краткое описание использования операторов PHP, Краткое описание навыков сетевого программирования PHP и Краткое описание использования строк Php.
Я надеюсь, что эта статья будет полезна для разработки PHP – программ для всех.