PHP会话 - 几个问题

I am using PHP sessions to store tracking data across my pages for my site. The session is started with session_start();

By the way - this is not a login script. I am tracking the first page the user entered on, the date/time and a few other variables.

I store the information in a database, and finally redirect the user to a page using:

header("Location: ".$URLHERE);
exit(); 

A few questions about using sessions:

  1. As I am not explicity closing the session after the redirect, does PHP delete session variables from disk - or do I have to handle this myself?

(I am concerned about datafiles building up on my Apache server)

  1. Are there any security issues with PHP sessions? This isn't a login, but my scripts do rely on session variables to track information about that unqiue visit.

Thanks :)

  1. No, the session garbage collection is managed by the system, based on the session.gc_maxlifetime property of php.ini. As your PHP script is run on a per-request basis, calling session_destroy() would involve the lost of data you got about the user at the end of each request.

  2. No security problem with php sessions, only risk is the cookie being stolen by an attacker, but you can avoid that requiring https.

Note that you can also do this without the session, but using the cookie API.

First, Please perform these

Note: before you start your session it is always best to save your session path to a folder. Also give read/write permission to this folder. Eg.

session_save_path('path to the session folder'/session name); session_start();

  1. session_start should be called before any session is being set or retrieved. Best practice is to set session at the begging point of your page i.e immediately once you open your php tag (

  2. very important point--> cookie must be enabled in your browser

  3. make sure _globals is off, you can check this on the php.ini file and also using phpinfo().

  4. after every header redirect .Please use exit so that the script doesnt continue further and before redirect please dont delete or empty your session.Also redirect to same domain.

  5. $_SESSION[key] --> make sure that this key is not overridden anywhere.

  6. the file extension always has to be .php

I hope it works out for you using above steps.

Here is your answers

1. As I am not explicity closing the session after the redirect, does PHP delete session variables from disk - or do I have to handle this myself?

When session create then on server a file create automatically and if user is no longer active on website then it will delete automatically as default session active time 1440 seconds (24 minutes). Session timeout can be set from php.ini by editing session.gc_maxlifetime = 1440

2. Are there any security issues with PHP sessions? This isn't a login, but my scripts do rely on session variables to track information about that unqiue visit.

No, There is no issues with PHP sessions just you need to take care of XSS