Tag Archives: php

Managing Sessions and State with PHP

In PHP, sessions can keep track of authenticated in users. They are an essential building block in today’s websites with big communities and a lot of user activity. Without sessions, everyone would be an anonymous visitor.

Due to the fast evolution of Web programming, the stateless nature of the HTTP protocol brought many problems to certain Web applications that required maintaining their state across several HTTP requests. This demanded a rapid development of several mechanisms aimed at tackling this issue through diverse methods. Then a session management emerged as a direct response to the above mentioned problem, and currently this mechanism is being used by PHP developers worldwide, in cases where a Web application needs to keep track of its “state” during the occurrence of different HTTP requests.

PHP sessions are very simple to use. They hide all the complexities inherent to where and how to store session data, and provide developers with a transparent mechanism for managing information that must persist or keep state even if different HTTP requests are triggered across the same Web application.

Thus, we get to know that session management is used to help web applications maintain their state across several HTTP requests when needed. In this first part of a series, you will learn the basics of the PHP built-in session mechanism, as well as some of its many useful functions.

Let us see how to maintain the state of applications with PHP session:

The first step involved in the use of PHP sessions is naturally indicating to the PHP interpreter that some kind of persistent data must be stored in the course of a session, in such a way that this data will maintain its value across different HTTP requests.

A cryptographic session identifier is created (known as the session ID), which is saved in the client in a cookie (this is the default behavior), or propagated by the URL as part of the query string (also known as URL propagation). Session data is stored on the server in text files (the default directory for storing session data is /tmp), but this behavior can be easily changed to save session data in shared memory or even database tables. The corresponding session ID is associated with saved session data, in this way providing a method for tying a particular user to this data.

Now let us know how session IDs are propagated across different HTTP requests. First off, the PHP session module uses cookies as the default way to propagate session IDs between different pages. Additionally, IDs can be propagated by GET/POST requests, by appending to each URL the name of the session together with the corresponding session ID. The following example shows how to pass a session ID between pages:




<a href="sesionscript.php?<?php echo 'PHPSESSID='.session_id()?

>">Click here</a>

In addition, PHP offers the global constant SID, which can be used to propagate session IDs within the URL, as follows:



<a href="sesionscript.php?<?php echo SID?>">Click here</a>

Finally, it’s possible to propagate session IDs by using the powerful “URL rewrite” feature, which automatically parses relative URLs and includes the session ID as part of the query string. To enable this handy feature, PHP must be configured with the “—enable-trans-id—option and then recompiled. Here’s a simple script that creates (or resumes) a session, and registers some data in the superglobal $_SESSION array:

// register session variables



// display session variables

echo 'My first name is '.$_SESSION['firstname'].' and my last

name is '.$_SESSION['lastname'];

As you can see, the above script is very simple. It first creates a new session or resumes an existing one by the “session_start()” function, and then stores my first and last names respectively as session data. If there is not a previous session, PHP will first generate a pseudo random session ID, then create a session file on the server using that ID, and save the serialized data in this file. In addition, the corresponding session ID will be stored in the client by using a cookie.


This sequence is the default behavior of the session module. However, as you’ll see later on, this process can be entirely changed, in order to utilize either shared memory or database tables for storing session data. Let us continue exploring the PHP session module, by using some other interesting functions. Have a look at the following example, which uses the “session_id()” function:


echo 'Old session ID :'.session_id();

// generate a new session ID


echo 'New session ID: '.session_id();

In this case, after running the above script, these are the values outputted to the browser:

Old session ID :e0c9904e70f283343f5aba1bad09aa69

New session ID: b0169350cd35566c47ba83c6ec1d6f82

As shown above, the “session_id()” function comes in very handy either for retrieving the ID of the current session, or for generating a new session identifier. To increase the overall security of a session, generating a new ID sometimes can be quite useful, in order to avoid possible session ID interceptions from malicious users. In case you need to regenerate the ID of a current session, PHP also provides the “session_regenerate_id()” function, which can be used as follows:





echo 'Old session ID is '.$oldid;

And the corresponding output for this script would be similar to this:

Old session ID is 8245009bcf9e24a738804323e779a3b7

New session ID is 680ee3c504bdecaf270539b254dd97df

In this example, as its name suggests, the “session_regenerate_id()” function is used to generate a new ID for the current session, but the good thing is that session data is always maintained. This function is extremely useful for avoiding some issues related to session ID fixation, and should be utilized in order to increase the security of session handling scripts.

In many situations, the logic of a particular PHP application requires that a specific session be terminated. In order to end an active session, PHP includes the “session_destroy()” function, which as the name indicates, destroys all the data associated with the current session. This function doesn’t unset any of the global variables tied to the session or the respective cookie. The use of this function is exemplified below:



Calling the “session_destroy()” function doesn’t delete the corresponding session variables or associated cookies. Thus a typical script, excerpted from the PHP manual, which destroys the current session along with all the session variables and the cookie associated to it, is listed below:

// destroy a session and all variables and cookies associated with it.


$_SESSION = array();


setcookie(session_name(),'', time()-48000,'/');



In the above example, all the session variables are unset by the line:


$_SESSION = array();

while the corresponding cookie is deleted by the following code:



setcookie(session_name(),'', time()-48000,'/');


Additionally, all the registered session variables can be freed up with the “session_unset()” function. However, for a complete and secure deletion of the entire session, it’s recommended to use the “session_destroy()” function in conjunction with the superglobal $_SESSION array and the “setCookie()” function, as shown in the example above.

If the session ID is transmitted by cookies, they will be deleted as soon as the browser is closed. Bearing in mind this condition, you should configure (when possible) the “gc_maxlifetime” and “gc_probability” directives of the php.ini file, in order to instruct PHP to trigger its garbage collection mechanism, in accordance with the requirements of the application being developed.

Let us see the example, which displays the name of an active session:


echo session_name(); // displays PHPSESSID

// generate new session name

session_name('NEW_SESSION_NAME'); //displays NEW_SESSION_NAME

echo session_name();

As shown in the above script, the name of a session can be obtained by using the “session_name()” function. This function returns the name of the active session or assigns a new name to it.

After running the previous snippet, the output I get on my browser is the following:



If a new session is started with the same browser or even with a different one, the value returned by the “session_name()” function (without passing any argument to it) will always be “PHPSESSID,” because this is the default session name assigned in the php.ini configuration file.

PHP also exposes a bunch of handy functions, aimed at returning and modifying some configuration parameters assigned as default values in the corresponding php.ini file. The examples begins with the “session_cache_limiter()” function, which returns the current setting of the “session.cache_limiter” directive, included in the php.ini file:

echo session_cache_limiter(); // default value is 'nocache'

// set new cache limiter to 'public'


echo session_cache_limiter();

// set new cache limiter to 'private'


echo session_cache_limiter();

As shown above, the “session_cache_limiter()” function allows you to return or change the settings of the “session.cache_limiter” directive. This parameter controls how server responses will be cached by the browser, and its default value is “nocache.” This means that any client/proxy caching process will be disabled by default in PHP.

On the other hand, if a value of “public” is assigned to this parameter, it will allow proxies and the client to cache content respectively. A value of “private” will disable caching by proxies, but enable caching by the client. As you may have guessed, all the cache directives are handled directly by the appropriate HTTP headers.

Also have a look at another handy PHP session function, in this case “session_cache_expire(),” which returns and eventually modifies the settings of the “session.cache_expire” directive:


echo session_cache_expire();// default value is 180 seconds.

// set new cache expire value

session_cache_expire(20); // set cache value to 20 seconds.

echo session_cache_expire();

The above example shows how to use the pertinent “session_cache_expire()” function. Of course this function should be utilized when cache is enabled, and its default value is 180 seconds. If a new setting is assigned to this directive (the example sets a new value of 20 seconds for caching contents), the current value will be replaced with the new one. If you’re going to modify the “session.cache_expire” setting, keep in mind that the default value of 180 seconds is assigned to it with every new HTTP request, so you should change this directive each time a request is triggered and before calling the “session_start()” function.

Another helpful function that will allow you to modify the value assigned to PHP session storage modules is the “session_module_name()” function. In case you didn’t know about this feature, PHP can be configured to use different storage modules. As you saw before, the default storage module is “files,” but it’s possible to modify this setting, in order to use shared memory, by assigning a value of “mm,” or utilizing user-level callback functions, which are used in conjunction with the “session_set_save_handler()” function. For this last option, the assigned value should be “User.”

Now, here’s an example of how to use this function:

echo session_module_name().'<br />'; // default value is 'files'

// set new module name


echo session_module_name(); // displays ‘user’

After demonstrating a simple implementation of the “session_module_name()” function, we are going to explain the combination of “session_set_cookie_params()/ session_get_cookie_params()” functions. Here are a couple of examples that show how to use them:




In the above script, the “session_get_cookie_params()” function is used to return the settings of the following php.ini directives: “session.cookie_lifetime,” “session.cookie_path,” “session.cookie_domain” and “session.cookie_secure.” And the output I get on my browser is listed below:

Array ( [lifetime] => 0 [path] => / [domain] => [secure] => )

As you can see, the above function returns nicely the values assigned to the php.ini entries that I mentioned before. Its counterpart, the “session_set_cookie_params()” function, should be used in the following way:





And the output would look similar to this:

Array ( [lifetime] => 3600 [path] => /cookiepath/ [domain] =>

mydomain.com [secure] => )

In this case, this function sets new values for the corresponding php.ini settings, which will only be valid during the execution of the script in question. Thus, if you need to keep the new assigned values across different HTTP requests, the function should be called each time a new request is made.


In this article, we have covered the basics of the PHP built-in session mechanism, as well as some of its many useful functions. For more information, keep on logging www.phpfresher.com.

SVN : Quick Overview on SVN


SVN is Subversion and it is a source control system. It is a PHP web based tool to administer an Apache Subversion repository server. It allows PHP scripts to communicate with SVN repositories and working copies without direct command line calls to the svn executable. If you are not currently using some other source control system; you are wise to invest in one. SVN is rather easy to use, compared to some other open source control systems, and has some neat tools on top of the source repository to make things easier for you.

With this tool you can remotely:

  • Create, remove, load and dump repositories
  • Manage user accounts for access to the repositories
  • Manage groups for access to the repositories
  • Invite users by email to create an account on the server

In order to work on SVN, you must meet the following requirements:

  • A PHP-enabled web server
  • A Linux server with Subversion installed
  • PHP function shell_exec() must be allowed


Not all servers or hosting providers allow their users to execute direct shell commands.  Please confirm with your hosting provider that this is enabled and allowed by their terms of service.

SVN Checkout

Here we are going to show how to checkout files from an SVN repository.  If you are using a public repository, you probably will not need to provide a username or password to access the files. However if you are using a private repository, you will be required to provide a username and password. This is the SVN command you will need to use to check out a file:

svn checkout SVNURL PATH

Now let’s go ahead and explain what is going on here.  First off the command we are using in svn checkout to pull the files from the SVN repository. SVNURL should be replaced with the link to the SVN repository (for the example we are going to use “ hello”).

PATH should be replaced with the name of the folder you want the files to be placed in to.  You can use the path depending on the location you are executing this command at, or you could use the full path to the folder. If you are executing the command in /home/user/public_html/ and list the path as “hello”, then it will place the files in /home/user/public_html/hello/. You could also just use the full path (for example, /home/user/public_html/hello) to specify a path anywhere on the server.

As we mentioned, we are going to use the hello repository and put all the repository files in a folder named “hello”.

svn checkout http://hello-php.googlecode.com/svn/trunk/distribution/libs/hello

Now that we have our command, we can go ahead and begin putting this command in to a PHP script.

$cmd="svn checkout http://hello-php.googlecode.com/svn/trunk/distribution/libs/ hello";
$svn = shell_exec($cmd);
echo $svn;

We are now ready to use PHP script to check out the latest version of hello. Obviously, you should replace the hello URL with the URL of the SVN repository you plan on using.  Also you can change the path to whatever you want your folder named.

 Quick Tips for SVN Checkout

If you are using a private repository, you will be forced to authenticate yourself with a username and password.  To authenticate, use the following script below. All you have to do is replace USERNAME with your username, PASSWORD with your password from your SVN account that has at least read-only access.  Also be sure to replace SVNURL with the SVN address and PATH with where you want the files placed.


$cmd = "svn --username USERNAME --password PASSWORD checkout SVNURL PATH";

$svn = shell_exec($cmd);

echo $svn;



If you would like the SVN repository files to be placed within the current folder that the command is being executed within, you use a period in the place of PATH.


$cmd = "svn checkout SVNURL .";

$svn = shell_exec($cmd);

echo $svn;


SVN Update

Now that we have our files checked out, we may need to update the files if they are changed on the repository.  Here we are showing you how to update your files with the latest ones from the SVN repository you used to check out the files.  Here is the shell command we are going to be using:

svn update PATH

So that is the command we are using, it is much more simple than the svn checkout function because all the variables such as the repository URL and username/password (if applicable) are already stored on the server.

The function we are looking at is svn update to pull the latest files from the SVN repository.  PATH should be replaced with the path of the folder where you checked the files out to.  If you placed the files in a folder named “hello” you can just replace PATH with “hello”.  If you are executing the command from a different folder, you should use the full path to the working folder (for example /home/user/public_html/hello).

Now let’s go ahead and pretend we are going to update a folder named “hello”, this will be the command you are going to use.

svn update hello

Now that we know how to structure the command, it is time to show this command being executed through PHP function shell_exec().


$cmd = "svn update hello";

$svn = shell_exec($cmd);

echo $svn;



Quick Tips for SVN Update

If you are using a private SVN repository, when you are updating a working folder, you do not need to re-authenticate again as your credentials are already stored on the server.

If you are updating a working folder and are executing the command from within that folder, you do not need to enter the PATH of the working folder. Below is a simple example of how you can execute the command from within the working folder.


$cmd = "svn update";

$svn = shell_exec($cmd);

echo $svn;



You now know the basics of performing an SVN checkout or update from a remote repository.  Please remember that not all hosting servers allow the PHP function shell_exec() to be executed for server security reasons. It is best to check with your hosting provider before attempting any of these commands.


PHP : Remove trans SID from URL

Remove trans SID from URL for XHTML compliance


When search engine attempts to search your site, usually they won’t remember sent cookies so that php will add a unique PHPSESSID query pair to URIs within your site if cookies are not available and session.use_trans_sid is set. As a result of this, the links to your site at GOOGLE will always have a query string with the session attached to them, and they will look bad search engines that will crawl less of your site and they may even consider your site as mirroring itself when they  got different sessions appended. This looks to search engines as if different pages have exactly the same content, and they will lower your rank or even ban it.
You can find a good stuff here The best advisors  please Check it.

With the release of PHP version 4.2.0 you don’t need to configure PHP with --enable-trans-sid to have transparent session support, this means that a lot more hosts will have it.

Without this feature you can usually choose between sending cookies to the visitor and modifying the URLs, with cookies being the default setting. Cookies do no harm (most of the time) but appending a query string to all URLs is quite different.

If you have forms and have left the default settings for the rewritable tags PHP will also add a hidden input to forms on your site but does that in such a way that your code cannot validate as XHTML 1.0 Strict or XHTML 1.1.


But you want your site being at the top of the search engine. So to disable that feature, you should add the following line:




This is the RUNTIME modifiable string. This allows trans_sid to do its thing.


Of course you call them before calling session_start().

Make your php code portable

Make your php code portable

As a developer, one of the most important things to consider when developing a Web application is portability. “Portable” means that your application is able to run on any PHP web server with minimal fuss. Ensuring portability is an absolute must for programs that are packaged and distributed for public consumption, like WordPress or MediaWiki. But, you should aim for portability in all of your applications.

Why Make it Portable?

It keeps things simple.

Secondly, it makes deploying your application to a new server simple if the need ever arises.

Thirdly, it enables you to easily distribute your package to the world if that is your intention.

Finally, portability makes distributed development easier.  Many applications are developed on Windows but run on Linux.  Portable applications eliminate the headaches involved in trying to get the two environments (development & production) to match.

How to Make Your Application Portable?

        Here we explain how to create the config and how to get your current configuration.

Use Long Tags

The first step to making your PHP applications portable is to use long PHP tags. That is, use ‘<?php’ instead of ‘<?’. This means your previous short write tags:


must now be:

<?php echo $foo; ?>

Note: The last semicolon in any PHP block is optional.

It’s annoying, but it’s sensible. Some people don’t have short tags turned on (they can be annoying if you also want XML declarations in your files) but PHP always supports the long tag versions.

Use E_ALL On Your Server

PHP allows you to set different levels of error reporting in your scripts. You should always use E_ALL when building applications, to show all errors and notices. To enable E_ALL, edit your php.ini file (ask your sysadmin about this), or add the following line at the top of your script:


With E_ALL turned on, you’re likely to get a lot of errors. But take the time to fix them — new PHP installations come with E_ALL on by default. The main errors you’ll come across are:

* Initializing variables

* Hash keys that don’t exist

* Bare strings

Initializing variables is easy. Consider the following piece of code:

if ($HTTP_GET_VARS['password'] == 'foo') {

$admin_ok = 1;


Looks fine, but $admin_ok hasn’t been initialised. If register_globals were turned on, someone could pass a value in for $admin_ok and your script would think they had gotten the password right. It’s very easy to fix:

$admin_ok = 0;

if ($HTTP_GET_VARS['password'] == 'foo') {

$admin_ok = 1;


This then can be cleaned up into a single statement:

$admin_ok = ($HTTP_GET_VARS['password'] == 'foo')?1:0;

With E_ALL turned on, you need to check hash keys exist before using them. Consider this code:

$foo = $HTTP_POST_VARS['foo'];

If ‘foo’ wasn’t passed as a form field, then the key doesn’t exist in the $HTTP_POST_VARS hash. What you need to do is check the key exists before referencing it:

$foo = 0;

if (array_key_exists('foo', $HTTP_POST_VARS)){

$foo = $HTTP_POST_VARS['foo'];


Than can get quite tedious, quite quickly, especially for $HTTP_GET_VARS and HTTP_POST_VARS, so construct a little routine:

function get_http_var($name, $default=''){


if (array_key_exists($name, $HTTP_GET_VARS)){return $HTTP_GET_VARS[$name];}

if (array_key_exists($name, $HTTP_POST_VARS)){return $HTTP_POST_VARS[$name];}

return $default;


Thirdly, this is very simple. Instead of this:


Write this:


But don’t worry about it when it’s in an interpolated string:

$baz = "$foo[bar]";

Don’t Use register_globals .They present a portability issue. Turn off register_globals in your php.ini or put a .htaccess file on your server with the following line in:

php_value register_globals off

If you build your application with register_globals off, using the get_http_var() function above, then it’ll be nice and secure (E_ALL will pick up on any uninitialized variables) and will also run fine on servers with register_globals on. But you should always have it disabled while developing your application.

Don’t Use Auto Slashing

The other evil options that are sometimes enabled are the annoying magic_quotes_gpc and the deadly magic_quotes_runtime. magic_quotes_gpc causes the GET, POST and COOKIE variables to have AddSlashes() run on them before your script runs. magic_quotes_runtime is even more dangerous, doing it during the running of your script. Since it has no effect until after your script is running, you can simply disable it at the top of your script:


ini_set("magic_quotes_runtime", 0);

magic_quotes_gpc is trickier, since it has already affected your variables by the time your script runs. To battle this, you’ll have to detect for it and undo its actions. We can do this by adding a little magic to our get_http_var() function:

function get_http_var($name, $default=''){


if (array_key_exists($name, $HTTP_GET_VARS)){return clean_var($HTTP_GET_VARS[$name]);}

if (array_key_exists($name, $HTTP_POST_VARS)){return clean_var($HTTP_POST_VARS[$name]);}

return $default;


function clean_var($a){

return (ini_get("magic_quotes_gpc") == 1)?recursive_strip($a):$a;


function recursive_strip($a){

if (is_array($a)) {

while (list($key, $val) = each($a)) {

$a[$key] = recursive_strip($val);



$a = StripSlashes($a);


return $a;


We use a recursive strip function since HTTP variables can contain arrays and that you don’t have auto-slashed variables, you MUST always call AddSlashes() on your variables before constructing an SQL statement. A good rule of thumb is to make sure ALL variables have been escaped, even if you’re sure they won’t contain quotes. If you’re using cookies you’ll also want to add a cookie-getting function:

function get_cookie_var($name, $default=''){


if (array_key_exists($name, $HTTP_COOKIE_VARS)){return clean_var($HTTP_COOKIE_VARS[$name]);}

return $default;


That just about wraps up our handy functions, but we’re not quite done with the rules yet.

Write Variables Out With HtmlEntities()

Whenever you output something to the browser, consider its content. If you don’t know exactly what’s in a variable, you should probably be using HtmlEntities() to make sure it won’t break. Consider this code, which is part of a form to edit a database record:

<input type=”text” name=”foo_bar” value=”<?php echo $row[‘foo_bar’]; ?>”><br>

This is fine, UNLESS $row[‘foo_bar’] contains the string “><img src=”/images/woo.gif

To make sure that the variable is displayed as expected, wrap it with HtmlEntities():

<input type="text" name="foo_bar" value="<?php echo htmlentities($row['foo_bar']); ?>"><br>


Similar Sites:
Dev Shed
Mt Dev

array_push() –php array function


The “array_push” function is used insert one or more elements onto the end of array.



In the above syntax “array” specifies the array to which the values in “value1” is to be added, “value2” is optional.


    print_r(array_push($b, Orange, Guava));


    Array ( [c]=> Cherry,[b]=> Strawberry, [0]=> Orange, [1]=> Guava);

In the above example even though the array already has string keys, the added elements will have numerical keys.