Home php教程 php手册 PHP脚本的8个技巧(2)

PHP脚本的8个技巧(2)

Jun 13, 2016 am 10:21 AM
php session Skill expectations characteristic usage of Script

会话用法
  
PHP 4.0有一个一直为人所期待的特性,这就是PHP的会话(session)支持。相比之下,PHP 3.0的用户则不得不使用第三方的程序库或完全不能具备这项功能。缺乏会话支持能力是PHP最大的缺陷之一,也是它最受人指摘的地方。不过,随着会话支持从早期测试版本的PHP 4.0开始就成为后者的一部分,这个障碍也荡然无存了。
有了会话支持,你就可以在用户访问网络站点期间维持用户特定的变量而无须象现在这样:设置多个cookie、使用隐蔽表单域或在你可能经常要连结的一个数据库内存储信息等。
在一个页面上启动会话就是告诉PHP引擎:你或是要开始一个会话(如果先前没有)或是继续目前的会话:
session_start();
启动一个会话将通过cookie向用户发送一个标识字符串(比如940f8b05a40d5119c030c9c7745aead9);在服务器端则会创建一个与此相匹配的临时文件,在以上例子中,其名称则是这个样子:sess_940f8b05a40d5119c030c9c7745aead9。该文件包含了注册的会话变量及其赋值。
用户访问计数器可谓使用会话的最常见实例:
启动你的PHP模块,保证PHP代码是文件的第一行:没有空白、没有HTML输出等等。这是因为,当会话函数发出一个文件头的时候,如果你在session_start()函数之前发送了空白或者HTML代码,系统即会报错。

// if a session does not yet exist for this user, start one
session_start();
接下来,注册一个名为count的变量。
session_register(count);
注册变量就等于告诉了PHP:只要会话存在,一个名叫count的变量也就同时存在。目前这个变量还没有赋值。不过,如果你对它进行加1运算的话,该值即可被赋值为1:
$count++;
把以上各行代码一起考虑,实际上你已经启动了一个会话(如果先前没有)、为某个用户分配了会话id、注册了名为count的变量并把$count加1以表示用户首次访问页面:
要显示用户在当前会话下访问页面的次数,你只要打印出$count的值即可:
echo "

Youve been here $count times.

";
整个访问计数器代码如下所示:

session_start();
session_register(count);
$count++;
echo "

Youve been here $count times.

";
?>

 

 

 

 

如果你重载以上脚本,你可以观察到计数值增加了。有意思吧?
你还可以在会话中注册数组。假设你有一个名为$faves的数组:
$faves = array (chocolate,coffee,beer,linux);
你可以象其他单个变量一样注册该数组:
session_register(faves);
索引数组和索引其他单变量没有什么差别,比如$faves这样。如果你的用户想在Web站点的一个页面上展示自己的爱好,那么你完全可以把他喜欢的东西注册为一个名为$faves会话变量,然后你可以在其他页面上把这些值打印出来:

 


session_start();
echo "My user likes:
    ";
    while (list(,$v) = each ($faves)) {
    echo "
  • $v"; }
    echo "
";
?>

 

 

 

 

 

这就是你要得到的:用户爱好的漂亮列表。
会话变量不能被查询字符串所覆盖,这就是说,你不能键入http:///www.yourdomain.com/yourscript.php?count=56 这样的指令为注册会话变量$count分配新值。这一点对安全而言是非常重要的:你只能在服务器端脚本上修改或者删除(未注册的)会话变量。
如果你想完全删除某个会话变量,你可以从系统中取消注册该变量:
session_unregister(count);
彻底删除某个会话,比如按下Logout按钮就是这样的例子,那么你可以写下如下的代码:
session_destroy();
使用会话来存储变量值可以让我们免于编写数据库处理代码的痛苦,这样也就不会过度增加对系统的负载,同时也减少了对专有数据库语法的使用范围,再说,你也不再非得向访问站点的用户发送一大堆cookie了。而现在呢——只需要一个cookie、一个变量就全部搞定了,真是一滴水就映出了全部光辉!实在是不能比这更简单的了。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles