PHP Sessions
- صفحه قبلی PHP Cookies
- صفحه بعدی PHP E-mail
PHP session variables are used to store information about user sessions or to change the settings of user sessions. The information stored in session variables is for a single user and can be used by all pages in the application.
PHP Session Variables
When you run an application, you open it, make some changes, and then close it. This is very much like a session. The computer knows who you are. It knows when you start the application and when you stop. But on the internet, there is a problem: the server does not know who you are or what you are doing, which is due to the fact that HTTP addresses cannot maintain state.
By storing user information on the server for later use, PHP session solves this problem (such as user name, purchased items, etc.). However, session information is temporary and will be deleted when the user leaves the website. If you need to store information permanently, you can store the data in a database.
The way Session works is: it creates a unique id (UID) for each visitor and stores variables based on this UID. The UID is stored in a cookie or passed through the URL.
Start PHP Session
You must start the session first before you store user information in the PHP session.
توضیح:The session_start() function must be placed before the <html> tag:
<?php session_start(); ?> <html> <body> </body> </html>
The above code registers the user's session with the server so that you can start saving user information, and also assigns a UID to the user session.
Store Session Variables
The correct method to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php session_start(); // Store session data $_SESSION['views']=1; ?> <html> <body> <?php // Retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html>
خروجی:
Pageviews=1
در مثال زیر، ما یک شمارنده ساده page-view ایجاد کردهایم. تابع isset() بررسی میکند که آیا متغیر "views" تنظیم شده است یا خیر. اگر "views" تنظیم شده باشد، ما شمارنده را جمع میکنیم. اگر "views" وجود ندارد، ما متغیر "views" را ایجاد کرده و آن را برابر با 1 تنظیم میکنیم:
<?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>
پایان سشن
اگر میخواهید برخی از دادههای سشن را حذف کنید، میتوانید از تابع unset() یا session_destroy() استفاده کنید.
تابع unset() برای آزاد کردن متغیرهای سشن مشخص شده استفاده میشود:
<?php unset($_SESSION['views']); ?>
شما همچنین میتوانید از تابع session_destroy() برای پایان دادن به طور کامل سشن استفاده کنید:
<?php session_destroy(); ?>
توضیح:session_destroy() سشن را تنظیم مجدد خواهد کرد، شما تمام دادههای سشن ذخیره شده را از دست خواهید داد.
- صفحه قبلی PHP Cookies
- صفحه بعدی PHP E-mail