William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP:Declare global variables

Declare global variable

I had a small bug in the PHP codes which prevents webpage from correctly display: global variable must be declared in functions before using it. The following codes doesn’t work:

$config = array(
 'header' => array(...),
);
function foo() {
 if (isset($config) && is_array($config['header'])) {
  //do some stuff.
 }
}
foo();

the foo() will not be executed because $config is unseen and not set in the function. To correct it, add:
global $config;
at the beginning of the function, to declare ‘I have been defined some place else’, like this:

function foo() {
 global $config;
 if (isset($config) && is_array($config['header'])) {
  //do some stuff.
 }
}
foo();

Right now it works.
1 more thing is: The $_COOKIE is not secure enough because it can be seen in different scripts as long as it is set. But $_SESSION is much more safe since it can only be seen in the script it is called.

echo "<pre>"; print_r($_COOKIE); print_r($_SESSION); echo "</pre>";

$_COOKIE will be printed out here, but $_SESSION not. So for security reason, $_SESSION is more considerable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: