Introduction
What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

  • Nice, but what does that mean? An example:
  • Example #1 An introductory example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Example</title>
        </head>
        <body>

            <?php
                
    echo "Hi, I'm a PHP script!";
            
    ?>

        </body>
    </html>

    Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."

    What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

    The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.

    Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.

    What can PHP do?

    Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

    There are three main areas where PHP scripts are used.

    Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work: the PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.

    Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.

    Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.

    PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, macOS, RISC OS, and probably others. PHP also has support for most of the web servers today. This includes Apache, IIS, and many others. And this includes any web server that can utilize the FastCGI PHP binary, like lighttpd and nginx. PHP works as either a module, or as a CGI processor.

    So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming (OOP), or a mixture of them both.

    With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

    One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple using one of the database specific extensions (e.g., for mysql), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB

    PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects

    PHP has useful text processing features, which includes the Perl compatible regular expressions (PCRE), and many extensions and tools to parse and access XML documents. PHP standardizes all of the XML extensions on the solid base of libxml2, and extends the feature set adding SimpleXML, XMLReader and XMLWriter support.

    And many other interesting extensions exist, which are categorized both alphabetically and by category. And there are additional PECL extensions that may or may not be documented within the PHP manual itself, like » XDebug.

    As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.

    A Simple Tutorial
  • Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information. PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.
  • What do I need?

    In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things.

    Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as » Apache, and of course » PHP. You will most likely want to install a database as well, such as » MySQL.

    You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). If you have problems with installing PHP yourself, we would suggest you ask your questions on our » installation mailing list. If you choose to go on the simpler route, then » locate a pre-configured package for your operating system, which automatically installs all of these with just a few mouse clicks. It is easy to setup a web server with PHP support on any operating system, including MacOSX, Linux and Windows. On Linux, you may find » rpmfind and » PBone helpful for locating RPMs. You may also want to visit » apt-get to find packages for Debian.

    Your first PHP-enabled page

    Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:

    Example #1 Our first PHP script: hello.php

    <html>
     <head>
      <title>PHP Test</title>
     </head>
     <body>
     <?php echo '<p>Hello World</p>'?> 
     </body>
    </html>

    Use your browser to access the file with your web server's URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

    <html>
           <head>
            <title>PHP Test</title>
           </head>
           <body>
           <p>Hello World</p>
           </body>
          </html>
          

    This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

    If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.

    The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.

    Note: A Note on Line Feeds

    Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.

    Note: A Note on Text Editors

    There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

    Note: A Note on Word Processors

    Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

    Note: A Note on Windows Notepad

    If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.

    Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.

    Example #2 Get system information from PHP

    <?php phpinfo(); ?>
    Something Useful

    Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].

    Note:

    $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP » 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. As of PHP 5.4.0 these older variables have been removed. (See also the note on old code <.)

    To display this variable, you can simply do:

    Example #1 Printing a variable (Array element)

    <?php
    echo $_SERVER['HTTP_USER_AGENT'];
    ?>

    A sample output of this script may be:

    Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

    There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.

    $_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.

    You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:

    Example #2 Example using control structures and functions

    <?php
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
        echo 
    'You are using Internet Explorer.<br />';
    }
    ?>

    A sample output of this script may be:

    You are using Internet Explorer.

    Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.

    The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.

    We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:

    Example #3 Mixing both HTML and PHP modes

    <?php
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    ?>
    <h3>strpos() must have returned non-false</h3>
    <p>You are using Internet Explorer</p>
    <?php
    } else {
    ?>
    <h3>strpos() must have returned false</h3>
    <p>You are not using Internet Explorer</p>
    <?php
    }
    ?>

    A sample output of this script may be:

    <h3>strpos() must have returned non-false</h3>
    <p>You are using Internet Explorer</p>

    Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.

    Dealing with Forms

    One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:

    Example #1 A simple HTML form

    <form action="action.php" method="post">
           <p>Your name: <input type="text" name="name" /></p>
           <p>Your age: <input type="text" name="age" /></p>
           <p><input type="submit" /></p>
          </form>

    Example #2 Printing data from our form

    Hi <?php echo htmlspecialchars($_POST['name']); ?>.
    You are <?php echo (int)$_POST['age']; ?> years old.

    A sample output of this script may be:

    Hi Joe. You are 22 years old.

    Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data.

    You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.

    Using old code with new versions of PHP

    Now that PHP has grown to be a popular scripting language, there are a lot of public repositories and libraries containing code you can reuse. The PHP developers have largely tried to preserve backwards compatibility, so a script written for an older version will run (ideally) without changes in a newer version of PHP. In practice, some changes will usually be needed.

    Two of the most important recent changes that affect old code are:

    The old $HTTP_*_VARS arrays are not available as of PHP 5.4.0. The following superglobal arrays were introduced in PHP » 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION.

    External variables are no longer registered in the global scope by default. In other words, as of PHP » 4.2.0 the PHP directive register_globals is off by default in php.ini. The preferred method of accessing these values is via the superglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If it were on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.

    For more details on these changes, see the section on predefined variables and links therein.

    What's next?

    With your new knowledge you should be able to understand most of the manual and also the various example scripts available in the example archives.

    To view various slide presentations that show more of what PHP can do, see the PHP Conference Material Site: » http://talks.php.net/

    Basic syntax
    PHP tags

    When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.

    PHP also allows for short open tag <? (which is discouraged since it is only available if enabled using the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option).

    If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

    <?php
    echo "Hello world";

    // ... more code

    echo "Last statement";

    // the script ends here with no PHP closing tag
    Escaping from HTML

    Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents, for example to create templates.

    <p>This is going to be ignored by PHP and displayed by the browser.</p>
    <?php echo 'While this is going to be parsed.'?>
    <p>This will also be ignored by PHP and displayed by the browser.</p>

    This works as expected, because when the PHP interpreter hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation) until it hits another opening tag unless in the middle of a conditional statement in which case the interpreter will determine the outcome of the conditional before making a decision of what to skip over. See the next example. Using structures with conditions

    Example #1 Advanced escaping using conditions

    <?php if ($expression == true): ?>
      This will show if the expression is true.
    <?php else: ?>
      Otherwise this will show.
    <?php endif; ?>

    n this example PHP will skip the blocks where the condition is not met, even though they are outside of the PHP open/close tags; PHP skips them according to the condition since the PHP interpreter will jump over blocks contained within a condition that is not met.
    For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print.

    In PHP 5, there are up to five different pairs of opening and closing tags available in PHP, depending on how PHP is configured. Two of these, <?php ?> and <script language="php"> </script>, are always available. There is also the short echo tag <?= ?>, which is always available in PHP 5.4.0 and later.

    The other two are short tags and ASP style tags. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.

    Note:

    Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.

    PHP 7 removes support for ASP tags and <script language="php"> tags. As such, we recommend only using <?php ?> and <?= ?> when writing PHP code to maximise compatibility.

    Example #2 PHP Opening and Closing Tags

    1.  <?php echo 'if you want to serve PHP code in XHTML or XML documents,
                    use these tags'
    ?>

    2.  You can use the short echo tag to <?= 'print this string' ?>.
        It's always enabled in PHP 5.4.0 and later, and is equivalent to
        <?php echo 'print this string' ?>.

    3.  <? echo 'this code is within short tags, but will only work '.
                
    'if short_open_tag is enabled'?>

    4.  <script language="php">
            
    echo 'some editors (like FrontPage) don\'t
                  like processing instructions within these tags'
    ;
        
    </script>
        This syntax is removed in PHP 7.0.0.

    5.  <% echo 'You may optionally use ASP-style tags'; %>
        Code within these tags <%= $variable; %> is a shortcut for this code <% echo $variable; %>
        Both of these syntaxes are removed in PHP 7.0.0.

    Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.

    ASP style tags (example five) are only available when they are enabled via the asp_tags php.ini configuration file directive, and have been removed in PHP 7.0.0.

    Note:

    Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.

    Note:

    In PHP 5.2 and earlier, the parser does not allow the <?php opening tag to be the only thing in a file. This is allowed as of PHP 5.3 provided there are one or more whitespace characters after the opening tag.

    Note:

    Starting with PHP 5.4, short echo tag <?= is always recognized and valid, regardless of the short_open_tag setting.

    Instruction separation

    As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

    <?php
        
    echo 'This is a test';
    ?>

    <?php echo 'This is a test' ?>

    <?php echo 'We omitted the last closing tag';

    Note:

    The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

    Comments

    PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:

    <?php
        
    echo 'This is a test'// This is a one-line c++ style comment
        /* This is a multi line comment
           yet another line of comment */
        
    echo 'This is yet another test';
        echo 
    'One Final Test'# This is a one-line shell-style comment
    ?>

    The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.

    <h1>This is an <?php # echo 'simple';?> example</h1>
    <p>The header above will say 'This is an  example'.</p>

    'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.

    <?php
     
    /*
        echo 'This is a test'; /* This comment will cause a problem */
     
    */
    ?>
    Variables
    Basics
  • Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
  • Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
  • Note: For our purposes here, a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).

    Note: $this is a special variable that can't be assigned.

    For information on variable related functions, see the Variable Functions Reference.

    <?php
    $var 
    'Bob';
    $Var 'Joe';
    echo 
    "$var$Var";      // outputs "Bob, Joe"

    $4site 'not yet';     // invalid; starts with a number
    $_4site 'not yet';    // valid; starts with an underscore
    $täyte 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
    ?>

    By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

    PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

    To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

    <?php
    $foo 
    'Bob';              // Assign the value 'Bob' to $foo
    $bar = &$foo;              // Reference $foo via $bar.
    $bar "My name is $bar";  // Alter $bar...
    echo $bar;
    echo 
    $foo;                 // $foo is altered too.
    ?>

    One important thing to note is that only named variables may be assigned by reference.

    <?php
    $foo 
    25;
    $bar = &$foo;      // This is a valid assignment.
    $bar = &(24 7);  // Invalid; references an unnamed expression.

    function test()
    {
       return 
    25;
    }

    $bar = &test();    // Invalid.
    ?>

    It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

    Example #1 Default values of uninitialized variables

    <?php
    // Unset AND unreferenced (no use context) variable; outputs NULL
    var_dump($unset_var);

    // Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
    echo($unset_bool "true\n" "false\n");

    // String usage; outputs 'string(3) "abc"'
    $unset_str .= 'abc';
    var_dump($unset_str);

    // Integer usage; outputs 'int(25)'
    $unset_int += 25// 0 + 25 => 25
    var_dump($unset_int);

    // Float/double usage; outputs 'float(1.25)'
    $unset_float += 1.25;
    var_dump($unset_float);

    // Array usage; outputs array(1) {  [3]=>  string(3) "def" }
    $unset_arr[3] = "def"// array() + array(3 => "def") => array(3 => "def")
    var_dump($unset_arr);

    // Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
    // Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
    $unset_obj->foo 'bar';
    var_dump($unset_obj);
    ?>

    Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

    Predefined Variables

    PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

    From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.

    Note: Variable variables

    Superglobals cannot be used as variable variables inside functions or class methods.

    Note:

    Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.

    If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

    Variable scope

    The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

    <?php
    $a 
    1;
    include 
    'b.inc';
    ?>

    Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

    <?php
    $a 
    1/* global scope */ 

    function test()

        echo 
    $a/* reference to local scope variable */ 


    test();
    ?>

    This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

    The global keyword

    First, an example use of global:

    Example #1 Using global

    <?php
    $a 
    1;
    $b 2;

    function 
    Sum()
    {
        global 
    $a$b;

        
    $b $a $b;


    Sum();
    echo 
    $b;
    ?>

    The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

    A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

    Example #2 Using $GLOBALS instead of global

    <?php
    $a 
    1;
    $b 2;

    function 
    Sum()
    {
        
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];


    Sum();
    echo 
    $b;
    ?>

    The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

    Example #3 Example demonstrating superglobals and scope

    <?php
    function test_global()
    {
        
    // Most predefined variables aren't "super" and require 
        // 'global' to be available to the functions local scope.
        
    global $HTTP_POST_VARS;
        
        echo 
    $HTTP_POST_VARS['name'];
        
        
    // Superglobals are available in any scope and do 
        // not require 'global'. Superglobals are available 
        // as of PHP 4.1.0, and HTTP_POST_VARS is now
        // deemed deprecated.
        
    echo $_POST['name'];
    }
    ?>

    Note:

    Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

    Using static variables

    Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

    Example #4 Example demonstrating need for static variables

    <?php
    function test()
    {
        
    $a 0;
        echo 
    $a;
        
    $a++;
    }
    ?>

    This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

    Example #5 Example use of static variables

    <?php
    function test()
    {
        static 
    $a 0;
        echo 
    $a;
        
    $a++;
    }
    ?>

    Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.

    Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

    Example #6 Static variables with recursive functions

    <?php
    function test()
    {
        static 
    $count 0;

        
    $count++;
        echo 
    $count;
        if (
    $count 10) {
            
    test();
        }
        
    $count--;
    }
    ?>

    Note:

    Static variables may be declared as seen in the examples above. From PHP 5.6 you can assign values to these variables which are the result of expressions, but you can't use any function here, what will cause a parse error.

    Example #7 Declaring static variables

    <?php
    function foo(){
        static 
    $int 0;          // correct 
        
    static $int 1+2;        // correct (as of PHP 5.6)
        
    static $int sqrt(121);  // wrong  (as it is a function)

        
    $int++;
        echo 
    $int;
    }
    ?>

    Note:

    Static declarations are resolved in compile-time.

    References with global and static variables

    The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:

    <?php
    function test_global_ref() {
        global 
    $obj;
        
    $obj = &new stdclass;
    }

    function 
    test_global_noref() {
        global 
    $obj;
        
    $obj = new stdclass;
    }

    test_global_ref();
    var_dump($obj);
    test_global_noref();
    var_dump($obj);
    ?>

    The above example will output:


    NULL
    object(stdClass)(0) {
    }

    A similar behaviour applies to the static statement. References are not stored statically:

    <?php
    function &get_instance_ref() {
        static 
    $obj;

        echo 
    'Static object: ';
        
    var_dump($obj);
        if (!isset(
    $obj)) {
            
    // Assign a reference to the static variable
            
    $obj = &new stdclass;
        }
        
    $obj->property++;
        return 
    $obj;
    }

    function &
    get_instance_noref() {
        static 
    $obj;

        echo 
    'Static object: ';
        
    var_dump($obj);
        if (!isset(
    $obj)) {
            
    // Assign the object to the static variable
            
    $obj = new stdclass;
        }
        
    $obj->property++;
        return 
    $obj;
    }

    $obj1 get_instance_ref();
    $still_obj1 get_instance_ref();
    echo 
    "\n";
    $obj2 get_instance_noref();
    $still_obj2 get_instance_noref();
    ?>

    The above example will output:


    Static object: NULL
    Static object: NULL

    Static object: NULL
    Static object: object(stdClass)(1) {
    ["property"]=>
    int(1)
    }

    This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.

    Variable variables

    Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

    <?php
    $a 
    'hello';
    ?>

    A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

    <?php
    $$a 'world';
    ?>

    At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

    <?php
    echo "$a ${$a}";
    ?>

    produces the exact same output as:

    <?php
    echo "$a $hello";
    ?>

    i.e. they both produce: hello world.

    In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

    Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

    Caution

    Further dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7. The PHP 7.0 migration guide includes further details on the types of expressions that have changed, and how to place curly braces to avoid ambiguity.

    Example #1 Variable property example

    <?php
    class foo {
        var 
    $bar 'I am bar.';
        var 
    $arr = array('I am A.''I am B.''I am C.');
        var 
    $r   'I am r.';
    }

    $foo = new foo();
    $bar 'bar';
    $baz = array('foo''bar''baz''quux');
    echo 
    $foo->$bar "\n";
    echo 
    $foo->{$baz[1]} . "\n";

    $start 'b';
    $end   'ar';
    echo 
    $foo->{$start $end} . "\n";

    $arr 'arr';
    echo 
    $foo->{$arr[1]} . "\n";

    ?>

    The above example will output:


    I am bar.
    I am bar.
    I am bar.
    I am r.
    Warning

    Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

    Variables From External Sources
    HTML Forms (GET and POST)

    When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are few ways to access this information, for example:

    Example #1 A simple HTML form

    <form action="foo.php" method="post">
              Name:  <input type="text" name="username" /><br />
              Email: <input type="text" name="email" /><br />
              <input type="submit" name="submit" value="Submit me!" />
          </form>

    Example #1 A simple HTML form

    <form action="foo.php" method="post">
              Name:  <input type="text" name="username" /><br />
              Email: <input type="text" name="email" /><br />
              <input type="submit" name="submit" value="Submit me!" />
          </form>

    As of PHP 5.4.0, there are only two ways to access data from your HTML forms. Currently available methods are listed below:

    Example #2 Accessing data from a simple POST HTML form

    <?php
    echo $_POST['username'];
    echo 
    $_REQUEST['username'];
    ?>

    There were some other ways of accessing user input in old PHP versions. These are listed below. See changelog at the bottom of the page for more details.

    Example #3 Old methods of accessing user input

    <?php
    // WATCH OUT: these methods ARE NOT supported anymore.
    // Valid ones were described above.

    // Using import_request_variables() - this function has been removed in PHP 5.4.0
       
    import_request_variables('p''p_');
       echo 
    $p_username;

    // These long predefined variables were removed in PHP 5.4.0
       
    echo $HTTP_POST_VARS['username'];

    // Using register_globals. This feature was removed in PHP 5.4.0
       
    echo $username;
    ?>

    Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST.

    Note:

    Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].

    PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

    Example #4 More complex form variables

    <?php
    if ($_POST) {
        echo 
    '<pre>';
        echo 
    htmlspecialchars(print_r($_POSTtrue));
        echo 
    '</pre>';
    }
    ?>
    <form action="" method="post">
        Name:  <input type="text" name="personal[name]" /><br />
        Email: <input type="text" name="personal[email]" /><br />
        Beer: <br />
        <select multiple name="beer[]">
            <option value="warthog">Warthog</option>
            <option value="guinness">Guinness</option>
            <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
        </select><br />
        <input type="submit" value="submit me!" />
    </form>
    IMAGE SUBMIT variable names

    When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

    <input type="image" src="image.gif" name="sub" />

    When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

    HTTP Cookies

    PHP transparently supports HTTP cookies as defined by » RFC 6265. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

    If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

    <?php
      setcookie
    ("MyCookie[foo]"'Testing 1'time()+3600);
      
    setcookie("MyCookie[bar]"'Testing 2'time()+3600);
    ?>

    That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

    Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

    Example #5 A setcookie() example

    <?php
    if (isset($_COOKIE['count'])) {
        
    $count $_COOKIE['count'] + 1;
    } else {
        
    $count 1;
    }
    setcookie('count'$counttime()+3600);
    setcookie("Cart[$count]"$itemtime()+3600);
    ?>
    Dots in incoming variable names

    Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:

    <?php
    $varname
    .ext;  /* invalid variable name */
    ?>

    Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

    For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.

    Determining variable types

    Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.

    HTTP being a text protocol, most, if not all, content that comes in Superglobal arrays, like $_POST and $_GET will remain as strings. PHP will not try to convert values to a specific type. In the example below, $_GET["var1"] will contain the string "null" and $_GET["var2"], the string "123".

    /index.php?var1=null&var2=123
          
    Reference
  • All the documentation in this page is taken from PHP.NET