Php beginner's tips
Facts - Php
Sunday, 19 August 2007 21:48

Here are some Php beginner's tips:

Single or double quoted strings ?

Not sure whether you should use a single or a double quoted string ? If you don't use special characters such as newlines or variable expansion in your string then use single quotes. Why ? If Php does not need to look for any special characters or variables to expand Php can parse your single quoted string faster.

Modifying an array in a loop

When you use foreach for modifying an array in a loop make sure you use an ampersand (&) for the loop variable:

 
foreach ($yourarray as &$modifyit) {
 $modifyit = $anothervar;
}
 

If you don't use the ampersand the array elements are passed to the foreach loop by value and they won't be modified.

Session parameters from your local webserver.

When I tried to pass session parameters for the first time, using $_SESSION, I could not get it working at all. What I did was opening another url and pass a session id as a html parameter. 

I was developing with a webserver installed locally. I had configured my PC such that the website, e.g. http://localfactsandpeople.com, was mapped to my local webserver. For the webserver this url was the same as http://localhost/localwebsites/localfactsandpeople.

I tried to pass a session id in the url http://localfactsandpeople.com/page.php to a new page using the following url: http://localhost/localwebsites/localfactsandpeople/newpage.php?sessionid=mysession.

I was trying to retrieve the session variable in newpage.php like this:

$mysession = $_GET('sessionid'); 
$passthisvariable = $_SESSION[$mysession]['passthis'];

However it did not work: I could extract the session id but I could not read the session variable in newpage.php.

When I changed the url to http://localfactsandpeople.com/newpage.php?sessionid=mysession I was able to use the session id in newpage.php.

What I learned is that php sessions do not work across different domains.

Last Updated ( Friday, 07 November 2008 22:09 )