• Blogs (9)
    • šŸ“± 236 - 992 - 3846

      šŸ“§ jxjwilliam@gmail.com

    • Version: ā€šŸš€ 1.1.0
  • PHP:Declare global variables

    Blogs20122012-09-29


    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.