PHP Tutorial

This is a rarely available Online PHP Tutorial. Hope it will be helpful for you.

  • Hello Techies..!!!

Thank You For Visiting this site.

Here YOu Will find most of the technical learning articles.

And if you find some problem in searching a particular topic then please leave some comment so that i can review on that particular topic.

Thank You.

Technolearn Team.

This is a rarely available fast PHP language learning online resource. Hope IT Will be helpful to you.

  • INTRODUCTION & INSTALLATION:
  • What Is PHP?

    PHP stands for PHP: Hypertext Preprocessor, a recursive acronym. It is mainly a Web server side scripting language. But it can also be used for other purposes.

    PHP was originally created by Rasmus Lerdorf in 1995 as a simple Web page generation tool named as PHP/FI (Personal Home Page/Forms Interpreter). Today it becomes the number one of server side scripting languages. Here is a comparison of number of matches on Google for key words: “PHP script”, “Perl script”, and “ASP script”:

    Key words     Number of matches
    PHP script    13,600,000
    Perl script   11,900,000
    ASP script     8,650,000

    Downloading PHP 5.0.4 for Windows

    1. Go to http://www.php.net, and download PHP 5.0.4 binary for Windows. You will get a file called php-5.0.4-Win32.zip of 7488 KB.

    2. Unzip php-5.0.4-Win32.zip to \php directory.

    3. Open a command window, and try the following commands:

    >\php\php -v
    PHP 5.0.4 (cli) (built: Mar 31 2005 02:45:48)
    Copyright (c) 1997-2004 The PHP Group
    Zend Engine v2.0.4-dev, Copyright (c) 1998-2004 Zend Technologies
    
    >\php\php-cgi -v
    PHP 5.0.4 (cgi-fcgi) (built: Mar 31 2005 02:45:43)
    Copyright (c) 1997-2004 The PHP Group
    Zend Engine v2.0.4-dev, Copyright (c) 1998-2004 Zend Technologies

    Cool, both Command Line Interface (CLI) and Common Gateway Interface (CGI) are working!

    My First PHP Script – Hello.php

    Use any text editor, and enter the first PHP script, Hello.php:

    Hello <?php echo "world!"; ?>

    Let’s run it PHP CLI first:

    >\php\php Hello.php
    Hello world!

    Now run it PHP CGI:

    >\php\php-cgi Hello.php
    Content-type: text/html
    X-Powered-By: PHP/5.0.4
    
    Hello world!

    As expected, PHP CGI did generate the HTTP response header for me.

    Installing PHP with IIS as CGI

    1. Add \php to the PATH environment variable. I assume you know how to do this.

    2. Set up PHP configuration file. First rename \php\php.ini-recommended to \php\php.ini. Then edit \php\php.ini to set the following values:

    cgi.force_redirect = 0
    doc_root = "c:\inetpub\wwwroot"
    cgi.redirect_status_env = ENV_VAR_NAME

    3. Create a new environment variable PHPRC with \php. This is needed to access php.ini.

    4. Now we need to change IIS configuration to run PHP scripts as CGI scripts. Run Control Panel, Internet Information Service, Default Web Site, and Properties. On the Directory tab, first set Execute Permissions to “Scripts only”. Then click Configuration to add a new Application Mapping with Executable=\php\php-cgi.exe, Extension=.php, and Script engine checked.

    5. Stop and start Default Web Site.

    6. Copy Hello.php to \inetpub\wwwroot.

    7. Run Internet Explorer (IE) with http://localhost/Hello.php. You should see:

    Hello world!

    Congratulation, you have installed PHP with IIS as CGI correctly!

    Conclusion

    Installation PHP on Windows IIS as CGI seems to be simple.

    Of course, you can also install PHP with IIS as a server module, using php5isapi.dll.

    For additional installation instructions, please read \php\install.txt.

    • PHP Syntax

    This chapter describes:

    • How to begin and end a PHP code block.
    • How a PHP input file will be processed.
    • How to enter comments in a PHP code block.

    PHP Code Blocks

    Like any other scripting language, PHP is used to transform text information from an input to an output by mixing PHP code segments in the input text. Here is how a PHP input file should look like:

    text PHP_code text PHP_code text PHP_code …

    There are 3 basic ways to mark the beginning and ending of a PHP code segments:

    1. HTML “script” tag: <script language=”php”>PHP_code</script>

    2. XML processing instruction: <?php PHP_code ?>

    3. Short XML processing instruction: <? PHP_code ?>

    PHP Processing Behavior

    As I mentioned previously, a PHP input is a sequence text blocks and PHP code blocks. The PHP engine will process the sequence as if it was a single PHP code block by:

    • First converting each text block into a PHP statement of print “text”.
    • Then joining code blocks with the converted print statements to form a single PHP code block.

    PHP’s processing behavior is very similar to Active Server Page (ASP)’s processing behavior.

    Now let’s see an example PHP input file:

    <?php ?> I am tossing a coin now. Guess what the result will be? <?php $coin = rand(0,1); ?> <?php if ($coin==1) { ?> Head <?php } else { ?> Tail <?php } ?>

    If you run this file, you may get:

    I am tossing a coin now. Guess what the result will be? Tail

    Of course, we could rewrite HeadOrTail.php as HeadOrTailModified.php:

    <?php /* HeadOrTailModified.php * Copyright (c) 2002 by Dr. Herong Yang */ ?> I am tossing a coin now. Guess what the result will be? <?php $coin = rand(0,1); if ($coin==1) { print ” Head”; } else { print ” Tail”; } ?>

    PHP Comments and Statement Delimiter

    There are 3 ways to enter comments in a PHP code block:

    • Perl style: Using “#”
    • Java style: Using “//”
    • C style: Using “/*” and “*/”

    PHP uses semicolon “;” as the statement delimiter.

    • DataTypes & Variables

    This chapter describes:

    • What are PHP data types.
    • How to define variables, references, and variable variable names.
    • How to define and use constants.

    Data Types

    PHP supports 8 data types:

    • boolean: It has only two literal values: ‘true’ and ‘false’.
    • integer: It is stored as signed integers with 32 bits. Integer literals have 3 forms: decimal, octal (prefixed with ’0′), and hexadecimal (prefixed with ’0x’).
    • float: It is stored as IEEE double floating point numbers with 64 bits. Float literals have the standard floating point number forms.
    • string: It is a sequence of 8-bit characters. String literals have 3 forms: single quoted, double quoted, and heredoc syntax. These forms are very similar to Perl.
    • array: It stores an ordered map of pairs of keys and values. This is quite different than the array type used in other languages.
    • object: It stores an instance of a class.
    • resource: It represents an external resource like a file, or a database connection.
    • null: It represents a status of a variable in which no value is assigned the variable. Null type has only one literal value: ‘null’.

    Data Literals ….

    PHP supports 8 data types:

    • boolean: It has only two literal values: ‘true’ and ‘false’.
    • integer: It is stored as signed integers with 32 bits. Integer literals have 3 forms: decimal, octal (prefixed with ’0′), and hexadecimal (prefixed with ’0x’).
    • float: It is stored as IEEE double floating point numbers with 64 bits. Float literals have the standard floating point number forms.
    • string: It is a sequence of 8-bit characters. String literals have 3 forms: single quoted, double quoted, and heredoc syntax. These forms are very similar to Perl.
    • array: It stores an ordered map of pairs of keys and values. This is quite different than the array type used in other languages.
    • object: It stores an instance of a class.
    • resource: It represents an external resource like a file, or a database connection.
    • null: It represents a status of a variable in which no value is assigned the variable. Null type has only one literal value: ‘null’.

    Variables

    Like Perl, a PHP variable name must be prefixed with a “$” sign.

    PHP variables do not need declaration. Variable can be assigned with one type of data, then re-assigned with another type of data.

    Reference: PHP supports a reference concept, where a reference of a variable can be expressed with the reference operator ‘&’, and assigned to a new variable. Once assigned with a reference, the new variable and the old variable become aliases to each other. They are sharing the storage location in memory.

    Variable Variable Name: PHP supports a dynamic variable name concept, where a variable name can be expressed as a string expression in the form of ${string_expression}. If the string expression is only a single variable, it can also be written as $$variable.

    To show you some of the variable features, I wrote the following PHP script, VariableTest.php:

    <?php # VariableTest.php
    
       print "\nSimple assignments:\n";
       $a = 777; # Assigning an integer
       print "   a = $a\n";
       $b = 3.14; # Assigning a float
       print "   b = $b\n";
       $c = "Hello"; # Assigning a string
       print "   c = $c\n";
       $d = true;
       print "   d = $d\n";
    #
       print "\nSpecial assignments:\n";
       $a = "Test"; # Re-assigning a string
       print "   a = $a\n";
       $a = null; # Assigning no-value
       print "   a = $a\n";
       $x = &$a; # Assigning a reference
       $x = 888; # Assigning an integer to an alias.
       print "   a = $a\n";
    #
       print "\nVariable variable names:\n";
       ${'a'} = 999; # Variable variable name as a string literal
       print "   a = $a\n";
       $y = 'a';
       ${$y} = 888; # Variable variable name as a string variable
       print "   a = $a\n";
       $$y = 777;
       print "   a = $a\n";
    ?>

    Here is the output:

    Simple assignments:
       a = 777
       b = 3.14
       c = Hello
       d = 1
    
    Special assignments:
       a = Test
       a =
       a = 888
    
    Variable variable names:
       a = 999
       a = 888
       a = 777

    As you can see from the output, the print statement seems to behave differently than other languages:

    • The print statement prints boolean true as 1.
    • The print statement prints null as nothing.

    Constants

    PHP supports constants with the following rules:

    • Constants can be defined with the define(“constant_name”, value) function. Constant names can not be redefined.
    • Constant values can be referred by constant names.
    • Operations & Expressions.

    This chapter describes:

    • What are PHP operations.
    • How expression works in PHP.

    Operations

    PHP supports most types of operations used in other languages:

    • Bitwise Operations: and, or, xor, not, shift left, and shift right.
    • Incrementing/Decrementing Operations: pre-inrement, post-increment, pre-decrement, and post-decrement.
    • Arithmetic Operations: negation, addition, subtraction, multiplication, division, and modulus.
    • Comparison Operations: equal, identical, not equal, not identical, less than, greater than, less than or equal, and greater than or equal to.
    • Logical Operations: and, or, xor, and not.
    • String Operations: concatenation.

    Note that “identical” and “not identical” operations are not commonly used in other languages.

    Expressions

    PHP supports most common rules on building expressions in other languages. It also supports some special rules:

    • The data type of the resulting value of an expression does not match the data type required by the evaluation context, the resulting value will be automatically converted the required data type.
    • Like Perl, 0 and no-value will be converted to false in a boolean context. Other values will be converted to true in a boolean context.
    • Assignment is also an expression. The resulting value of an assignment is the value used in the assignment.

    To show you some of the features, I wrote the following sample PHP script, ExpressTest.php:

    <?php # ExpressionTest.php
    
       print "\nSimple expressions:\n";
       $a = 1 + 2 * 3 / 4; # Expression with arithmetic operations
       print "   a = $a\n";
       $b = 'A' + 1; # Context requires 'A' to be evaluated to a float
       print "   b = $b\n";
       $c = 'A' . 1; # Context requires 1 to be evaluated to a string
       print "   c = $c\n";
       $d = true && 9; # Context requires 9 to be evaluated to true
       print "   d = $d\n";
    #
       print "\nSpecial expressions:\n";
       $a = $b = "Apple"; # Using assignement as an expression
       print "   a = $a\n";
       $x = $a === $b;
       print "   x = $x\n";
    ?>

    Here is the output:

    Simple expressions:
       a = 2.5
       b = 1
       c = A1
       d = 1
    
    Special expressions:
       a = Apple
       x = 1
    • Flow Control Statements

    This chapter describes:

    • What are conditional statements.
    • What are loop statements.

    Conditional Statements

    PHP supports most types of conditional statements used in other languages:

    • “if … elseif … else” statements.
    • “switch … case … default” statements.

    Like other languages, “break” statements can be used in the “case” clauses to break out the “switch” statements.

    Here is my standard test program for flow control statements, LibraryHours.php:

    <?php # LibraryHours.php
    
       $dateInfo = getdate();
       $wDay = $dateInfo["wday"];
       $weekDay = $dateInfo["weekday"];
       $openHours = "open";
    #
       print "\nLibrary Hours with \"if\" statements:\n";
       print "   Today is: $weekDay\n";
       if ($wDay == 0) {
          $openHours = "closed";
       } elseif ($wDay >= 1 && $wDay <= 5) {
          $openHours = "open from 9:00am to 9:00pm";
       } elseif ($wDay == 6 ) {
          $openHours = "open from 9:00am to 5:00pm";
       } else {
          $openHours = "not at here";
       }
       print "   The library is $openHours\n";
    #
       print "\nLibrary Hours with \"switch\" statements:\n";
       print "   Today is: $weekDay\n";
       switch ($weekDay) {
          case "Monday":
          case "Tuesday":
          case "Wednesday":
          case "Thursday":
          case "Friday":
             $openHours = "open from 9:00am to 9:00pm";
             break;
          case "Saturday":
             $openHours = "open from 9:00am to 5:00pm";
             break;
          case "Sunday":
             $openHours = "closed";
             break;
          default:
             $openHours = "not at here";
       }
       print "   The library is $openHours\n";
    ?>

    Output of the program:

    C:\herong\php_20050402\src>php LibraryHours.php
    
    Library Hours with "if" statements:
       Today is: Saturday
       The library is open from 9:00am to 5:00pm
    
    Library Hours with "switch" statements:
       Today is: Saturday
       The library is open from 9:00am to 5:00pm

    Loop Statements

    PHP supports most types of loop statements used in other languages:

    • “while” statements.
    • “for” statements.
    • “foreach” statements.
    • “do … while” statements.

    Here is my standard test program for loop statements, PrimeNumbers.php:

    <?php # PrimeNumbers.php
    
       $upperLimit = 20;
    #
       print "\nCalculating prime numbers with \"for\" statements:\n";
       for ($i=3; $i<$upperLimit; $i++) {
          $isPrime = true;
          for ($j=2; $j<=$i/2; $j++) {
             $isPrime = $i%$j > 0;
             if (!$isPrime) break;
          }
          if ($isPrime) print "   $i is a prime number.\n";
       }
    #
       print "\nCalculating prime numbers with \"while\" statements:\n";
       $i = 3;
       while ($i<$upperLimit) {
          $isPrime = true;
          $j = 2;
          while ($j<$i) {
             $isPrime = $i%$j > 0;
             if (!$isPrime) break;
             $j++;
          }
          if ($isPrime) print "   $i is a prime number.\n";
          $i++;
       }
    ?>

    Output of the program:

    Calculating prime numbers with "for" statements:
       3 is a prime number.
       5 is a prime number.
       7 is a prime number.
       11 is a prime number.
       13 is a prime number.
       17 is a prime number.
       19 is a prime number.
    
    Calculating prime numbers with "while" statements:
       3 is a prime number.
       5 is a prime number.
       7 is a prime number.
       11 is a prime number.
       13 is a prime number.
       17 is a prime number.
       19 is a prime number.
    • Functions

    This chapter describes:

    • How to define functions.
    • How to pass references to and returning a reference from functions.

    User Defined Functions

    PHP supports user defined functions like in other languages, with some special features:

    • By default, arguments are passed by value. But arguments can also be passed as references.
    • Arguments can be assigned with default values.
    • Functions can return values or references.
    • Function names can also be string expressions. This is called variable functions.
    • Functions can be defined inside another code block, or function.

    Passing and Returning References

    The following sample script shows how references can be passed to and returned from a function, FunctionTest.php:

    <?php # FunctionTest.php
    
       print "\nPassing arguments as references:\n";
       $x = "Apple";
       $y = "Orange";
       swap($x,$y);
       print "   x = $x\n";
       print "   y = $y\n";
    #
       print "\nReturning a reference:\n";
       $x = 10;
       $y = &ref($x);
       $x = 20;
       print "   y = $y\n";
    #
    function swap(&$a, &$b) {
       $c = $b;
       $b = $a;
       $a = $c;
    }
    function &ref(&$a) {
       return $a;
    }
    ?>

    Here is the output of the program:

    Passing arguments as references:
       x = Orange
       y = Apple
    
    Returning a reference:
       y = 20

    I am sure you know why we getting this output.

    • Arrays

    What Is an Array in PHP?

    Array: In PHP, an array represents an ordered map of pairs of keys and values. This is different than most of other languages. Basic rules for PHP’s array are:

    1. An array can be constructed by the array constructor, like:

       $myArray = array(k1=>v1, k2=>v2, ..., kn=>vn);

    where k1, k2, …, and kn are keys of integer type or string type. v1, v2, …, and vn are values of any data types.

    2. The value of a given key in an array can be expressed by the array variable followed by the key in square brackets, like:

       print $myArray[kn];

    3. The value of a given key in an array can be modified by an assignment statement, like:

       $myArray[kn] = new_value.

    4. A new pair of key and value can be added to an array by an assignment statement, like:

       $myArray[kx] = vx

    5. If a string key represents an integer, it will be used as an integer key. So $myArray['7'] is the same as $myArray[7].

    6. If the key is missing in an array assignment or an array constructor, an integer key of 0, or the highest integer key plus 1, will be provided.

    7. An empty string is also a valid string key, like:

       $myArray[''] = vy;

    8. A pair of key and value can be removed by using the unset() function, like:

       unset($myArray[kn]);

    9. Pairs of keys and values are ordered in an array like a queue. New pairs are always added at the end of the array.

       unset($myArray[kn]);

    Here is a simple script to show you some of these rules:

    <?php # ArrayTest.php
    
       print "\nLibrary hours:\n";
       $libraryHours = array(
          'Monday - Friday'=>'09:00 - 21:00',
          'Saturday'=>'09:00 - 17:00',
          'Sunday'=>'closed');
       print_r($libraryHours);
    #
       print "\nPrime numbers:\n";
       $primeNumbers = array(3, 5, 7, 11);
       $primeNumbers[] = 13;
       print_r($primeNumbers);
    #
       print "\nFruits:\n";
       $fruits[] = 'Apple';
       $fruits[] = 'Orange';
       $fruits[''] = 'Peach';
       $fruits[''] = 'Banana';
       $fruits['G'] = 'Grape';
       $fruits['7'] = 'Pear';
       $fruits[] = 'Fig';
       print_r($fruits);
    #
       print "\nFruits array modified:\n";
       unset($fruits[1]);
       $fruits[1] = 'Orange';
       print_r($fruits);
    ?>

    Here is the output:

    Library hours: Array ( [Monday - Friday] => 09:00 – 21:00 [Saturday] => 09:00 – 17:00 [Sunday] => closed ) Prime numbers: Array ( [0] => 3 [1] => 5 [2] => 7 [3] => 11 [4] => 13 ) Fruits: Array ( [0] => Apple [1] => Orange [] => Banana [G] => Grape [7] => Pear [8] => Fig ) Fruits array modified: Array ( [0] => Apple [] => Banana [G] => Grape [7] => Pear [8] => Fig [1] => Orange )

    The behavior of the $fruits array is very interesting. Review it carefully.

    Array Related Built-in Functions

    PHP offers a number of interesting built-in functions to work with arrays:

    • array_combine() – Combines two arrays into a new array with the first array as keys and the second as values.
    • array_count_values() – Counts the frequencies of values in an array and returns them as an array.
    • array_key_exists() – Searches for a key in an array.
    • array_keys() – Returns an array with all keys of an array.
    • array_search() – Searches for a value in an array.
    • array_values() – Returns an array with all values of an array.
    • ksort() – Sorts an array by keys.
    • sort() – Sorts an array by values.

    PHP also offers special loop statements to iterate over arrays:

    foreach($myArray as $value) {} foreach($myArray as $key=>$value) {}

    Here is a simple script with a “foreach” statement:

    <?php # ArrayLoop.php # Copyright (c) 2003 by Dr. Herong Yang # print “\nLibrary hours:\n”; $libraryHours = array( ‘Monday – Friday’=>’09:00 – 21:00′, ‘Saturday’=>’09:00 – 17:00′, ‘Sunday’=>’closed’); foreach($libraryHours as $day=>$hours) { print ” $day: $hours\n”; } ?>

    Here is the output:

    Library hours: Monday – Friday: 09:00 – 21:00 Saturday: 09:00 – 17:00 Sunday: closed

    Conclusion

    • PHP’s array is easy to use. But mixing integer indexed array with associate map is kind of confusing.

    .

    • Sending Emails Using PHP

    This chapter describes:

    • How to check the mail server on your local Windows system.
    • How to send an email through PHP.

    Using Local Windows System as a Mail Server

    If you are running your Web server on a local system and not connected to the Internet, you need to set up your local system as a mail server to test the email function in PHP.

    If you are running a Linux/Unix system, setting up a mail server is easy. Just run sendmail as daemon.

    If you are running a Windows system, setting up a mail server is a little bit harder. But most of the time, your local Windows system is probably already running a mail server. Here is how you can check this:

    1. Go to Control Panel / Services, and make sure Simple Mail Transfer Protocol is running.

    2. Open a command window, and run the following command:

    >telnet localhost 25 
    
    220 localhost Microsoft ESMTP MAIL Service, Version: 6.0.2600.1106...
    help
    214-This server supports the following commands:
    214 HELO EHLO STARTTLS RCPT DATA RSET MAIL QUIT HELP AUTH BDAT VRFY
    quit
    221 2.0.0 localhost Service closing transmission channel

    If you got similar outputs as above, your mail server is running ok.

    Sending an Email with PHP

    First you need to verify \php\php.ini to make sure the following settings:

    SMTP = localhost
    smtp_port = 25

    Now run the following PHP script, MailTest.php:

    <?php # MailTest.php
    
    mail("nobody","Testing","This is a test.","From: herong@localhost");
    ?>

    Then go check to see the email is delivered or not in a command window:

    >dir \inetpub\mailroot\drop
    
    ... d9765b3001c54a1200000001.eml
    
    >type \inetpub\mailroot\drop\d9765b3001c54a1200000001.eml
    
    x-sender: herong@localhost
    x-receiver: nobody@localhost
    Received: from localhost ([127.0.0.1]) by localhost with Microsoft...
    Subject: Testing
    To: nobody
    From: herong@localhost
    Return-Path: herong@localhost
    ......
    
    This is a test.

    If you can follow me to here, you have successfully configured your local system to send emails with PHP.

    • HTTP Request Variables In PHP

    This chapter describes:

    • What are the predefined variables that store information from the HTTP request.
    • A sample script to test request variables.
    • How to promote request variables to stand alone variables.

    Predefined Variables Related to HTTP Request

    When PHP is used on a Web server to handle a HTTP request, it converts information submitted in the HTTP request as predefined variables:

    • $_GET – Associate array of variables submitted with GET method.
    • $_POST – Associate array of variables submitted with POST method.
    • $_COOKIE – Associate array of variables submitted as cookies.
    • $_REQUEST – Associate array of variables from $_GET, $_POST, and $_COOKIE.
    • $_SERVER – Associate array of all information from the server and the HTTP request.

    Variables in those arrays can also be promoted (registered) as stand alone global variables using one of the following two ways:

    • Change “register_globals = on” in php.ini to register HTTP request variables on the entire server.
    • Call import_request_variables() to register HTTP request variables in one script only.

    Here is my standard test program for HTTP request variables:

    <?php # HttpRequestDetails.php
    
       print "<pre>\n";
       print "\nContents of \$_GET:\n";
       foreach ($_GET as $k => $v) {
          print "   $k = $v\n";
       }
    #
       print "\nContents of \$_POST:\n";
       foreach ($_POST as $k => $v) {
          print "   $k = $v\n";
       }
    #
       print "\nContents of \$_COOKIE:\n";
       foreach ($_COOKIE as $k => $v) {
          print "   $k = $v\n";
       }
    #
       print "\nContents of \$_REQUEST:\n";
       foreach ($_REQUEST as $k => $v) {
          print "   $k = $v\n";
       }
    #
       print "\nContents of \$_SERVER:\n";
       foreach ($_SERVER as $k => $v) {
          print "   $k = $v\n";
       }
       print "</pre>\n";
    ?>

    Run HttpRequestDetails.php at the command line, you will get:

    <pre>
    
    Contents of $_GET:
    
    Contents of $_POST:
    
    Contents of $_COOKIE:
    
    Contents of $_REQUEST:
    
    Contents of $_SERVER:
       CLIENTNAME = Console
       ComSpec = C:\WINDOWS\system32\cmd.exe
       HOMEDRIVE = C:
       PHPRC = c:\local\php
       PROCESSOR_ARCHITECTURE = x86
       SESSIONNAME = Console
       SystemDrive = C:
       SystemRoot = C:\WINDOWS
       PHP_SELF = HttpRequestDetails.php
       SCRIPT_NAME = HttpRequestDetails.php
       SCRIPT_FILENAME = HttpRequestDetails.php
       PATH_TRANSLATED = HttpRequestDetails.php
       DOCUMENT_ROOT =
       argv = Array
       argc = 1
       ......
    </pre>

    Not very interesting, right? $_GET, $_POST, $_COOKIE, and $_REQUEST are all empty.

    Testing Request Variables – HttpRequestDetails.php

    Now, let’s run HttpRequestDetails.php on the local Web server. First copy HttpRequestDetails.php to \inetpub\wwwroot, then run Internet Explorer (IE) with http://localhost/HttpRequestDetails.php. You should get:

    Contents of $_GET:
    
    Contents of $_POST:
    
    Contents of $_COOKIE:
    
    Contents of $_REQUEST:
    
    Contents of $_SERVER:
       CONTENT_LENGTH = 0
       GATEWAY_INTERFACE = CGI/1.1
       HTTP_ACCEPT = */*
       HTTP_ACCEPT_LANGUAGE = en-us
       HTTP_CONNECTION = Keep-Alive
       HTTP_HOST = localhost
       HTTP_ACCEPT_ENCODING = gzip, deflate
       HTTPS = off
       INSTANCE_ID = 1
       LOCAL_ADDR = 127.0.0.1
       NUMBER_OF_PROCESSORS = 1
       OS = Windows_NT
       ProgramFiles = C:\Program Files
       REMOTE_ADDR = 127.0.0.1
       REMOTE_HOST = 127.0.0.1
       REQUEST_METHOD = GET
       SCRIPT_NAME = /HttpRequestDetails.php
       SERVER_NAME = localhost
       SERVER_PORT = 80
       SERVER_PORT_SECURE = 0
       SERVER_PROTOCOL = HTTP/1.1
       SystemDrive = C:
       ORIG_PATH_INFO = /HttpRequestDetails.php
       ORIG_SCRIPT_NAME = /HttpRequestDetails.php
       DOCUMENT_ROOT = c:/inetpub/wwwroot
       SCRIPT_FILENAME = c:\inetpub\wwwroot\HttpRequestDetails.php
       PHP_SELF = /HttpRequestDetails.php
       ......

    $_GET is still empty, because nothing is submitted in the HTTP request. Now try this URL: http://localhost/HttpRequestDetails.php?lang=PHP&search. You should get:

    Contents of $_GET:
       lang = PHP
       search = 
    
    Contents of $_POST:
    
    Contents of $_COOKIE:
    
    Contents of $_REQUEST:
       lang = PHP
       search = 
    
    Contents of $_SERVER:
       ......
       QUERY_STRING = lang=PHP&search
       ......

    Registering HTTP Request Variables as Global Variables

    As I mentioned in the first section, there are two ways to promote variables stored in the request as stand alone global variables:

    To promote request variables for the entire server, edit \php\php.ini and set:

    register_globals = on

    To promote request variables for one script only, use the following function:

    import_request_variables("GPC",$prefix);

    where “GPC” indicates that all variables from GET, POST and COOKIE are prompted. $prefix defines a prefix string that are to be added to the variable names.

    Here is a sample script, RequestVariables.php

    <?php # RequestVariables.php
    
       print "<pre>\n";
       print "\nContents of \$_REQUEST:\n";
       foreach ($_REQUEST as $k => $v) {
          print "   $k = $v\n";
       }
    #
       print "\nLocl imported variables from the request:\n";
       import_request_variables("GPC","r_");
       print "   \$r_lang = $r_lang\n";
       print "   \$r_search = $r_search\n";
    #
       print "\nGlobaly imported variables from the request:\n";
       print "   \$lang = $lang\n";
       print "   \$search = $search\n";
       print "</pre>\n";
    ?>

    Try the script with http://localhost/RequestVariables.php?lang=PHP&search, you will get:

    Contents of $_REQUEST:
       lang = PHP
       search = 
    
    Locl imported variables from the request:
       $r_lang = PHP
       $r_search = 
    
    Globaly imported variables from the request:
       $lang = PHP
       $search =

    Conclusion:

    $_GET in PHP is similar to the request.QueryString object in ASP.

    $_POST in PHP is similar to the request.Form object in ASP.

    Promoting variables in the request to be stand alone variable makes it easy to use them. But it also increases the risk of colliding them with other variables used in the script.

    • Sessions In PHP

    This chapter describes:

    • What is a session.
    • How use session in a PHP script.
    • A session test with 3 scripts.
    • How session ID can be managed without cookies.
    • Where is session data stored.

    What is a Session?

    Session: An abstract concept to represent a series of HTTP requests and responses exchanged between a specific Web browser and a specific Web server. Session concept is very useful for Web based applications to pass and share information from one Web page (request) to another Web page (request).

    Since the current design of HTTP protocol does not support session concept, all Web server side scripting technologies, including PHP, have designed their own way to support session concept. The key design element of session support is about how to identify a session and how to maintain the session ID (identification). One common way to maintain the session ID is use the cookie technology. The following diagram shows you how to do this:

               Server                Browser
    ID created  | <-- Request #1  --- |
                | --- Response #1 --> | ID kept as cookie
                | <-- Request #2  --- | ID send back to server
                | --- Response #2 --> |
                | <-- Request #3  --- | ID send back to server
                | --- Response #3 --> |
                |     ......          |

    The session concept should be managed by the server. When the first request comes from a browser on a client host, the server should create a new session, and assigns a new session ID. The session ID will be then send back to the same browser as a cookie. The browser will remember this ID, and send the ID back to the server in the subsequent requests. When the server receives a request with a session ID in them, it knows this is a continuation of an existing session.

    When the server receives a request from a browser on a new client host (request without a session ID), the server should not only create a new session ID, it should also create a new session object associated with the new session ID. This session object should become the storage place for different requests of the same session to store and share information.

    If there is no subsequent request coming back for a long time for a particular session ID, that session should be timed out. After the session has been timed out, if the browser comes back again with the associated session ID, the server should give an invalid session error.

    PHP’s Session Support

    Like JavsServer Page (JSP), PHP manages the session ID with as a cookie, a GET variable, or a POST variable. It offer a built-in array as the session object, and a number of built-in functions to allow the PHP script to interact with the session:

    • $_SESSION – A built-in array to store and share variables for the session.
    • session_start() – A built-in function to create a new session or resume an existing session based on the current session id that’s being passed via a request, such as GET, POST, or a cookie.
    • session_name() – A built-in function to set and get the session name.
    • session_id() – A built-in function to set and get the session ID.
    • session_destroy() – A built-in function to destroy all variables stored in $_SESSION.

    Session Test Scripts – SessionPageN.php

    To help testing the session concept, I wrote 3 PHP scripts.

    SessionPage1.php:

    <?php # SessionPage1.php
    
       session_start();
       $quantity = 3;
       $_SESSION['quantity'] = $quantity;
       if (isset($_SESSION['count'])) {
          $count = $_SESSION['count'];
       } else {
          $count = 0;
       }
       $count++;
       $_SESSION['count'] = $count;
    #
       print "<pre>\n";
       print "\nI am buying $quantity PHP books.\n";
    
       print "\n<a href=SessionPage2.php>Next</a>\n";
       print "\nCounter = $count\n";
       print "Session name = ".session_name()."\n";
       print "Session id = ".session_id()."\n";
    #
       print "\nContents of \$_GET:\n";
       foreach ($_GET as $k => $v) {
          print "   $k = $v\n";
       }
    #
       print "\nContents of \$_POST:\n";
       foreach ($_POST as $k => $v) {
          print "   $k = $v\n";
       }
    #
       print "\nContents of \$_COOKIE:\n";
       foreach ($_COOKIE as $k => $v) {
          print "   $k = $v\n";
       }
       print "</pre>\n";
    ?>

    SessionPage2.php:

    <?php # SessionPage2.php

    session_start();

    $quantity = $_SESSION['quantity'];

    $price = 9.99;

    $_SESSION['price'] = $price;

    $count = $_SESSION['count'];

    $count++;

    $_SESSION['count'] = $count;

    # print “<pre>\n”;

    print “\nI am buying $quantity PHP books.\n”;

    print “The unit price is $price per book.\n”;

    # print “\n<a href=SessionPage3.php>Next</a> “;

    print ” <a href=SessionPage1.php>Prev</a>\n”;

    print “\nCounter = $count\n”;

    print “Session name = “.session_name().”\n”;

    print “Session id = “.session_id().”\n”;

    # print “\nContents of \$_GET:\n”;

    foreach ($_GET as $k => $v) { print ” $k = $v\n”; } # print “\nContents of \$_POST:\n”;

    foreach ($_POST as $k => $v) { print ” $k = $v\n”; } # print “\nContents of \$_COOKIE:\n”;

    foreach ($_COOKIE as $k => $v) { print ” $k = $v\n”; } print “</pre>\n”; ?>

    SessionPage3.php:

    <?php # SessionPage3.php

    session_start();

    $quantity = $_SESSION['quantity'];

    $price = $_SESSION['price'];

    $total = $quantity * $price;

    $count = $_SESSION['count'];

    $count++; $_SESSION['count'] = $count;

    # print “<pre>\n”;

    print “\nI am buying $quantity PHP books.\n”;

    print “The unit price is $price per book.\n”;

    print “The total price is $total.\n”;

    # print “\n<a href=SessionPage2.php>Prev</a>\n”; print “\nCounter = $count\n”;

    print “Session name = “.session_name().”\n”;

    print “Session id = “.session_id().”\n”;

    # print “\nContents of \$_GET:\n”;

    foreach ($_GET as $k => $v) { print ” $k = $v\n”; }

    # print “\nContents of \$_POST:\n”;

    foreach ($_POST as $k => $v) { print ” $k = $v\n”; }

    # print “\nContents of \$_COOKIE:\n”;

    foreach ($_COOKIE as $k => $v) { print ” $k = $v\n”; }

    print “</pre>\n”; ?>

    If you run http://localhost/SessionPage1.php, you will get:

    I am buying 3 PHP books. Next Counter = 1 Session name = PHPSESSID Session id = o9oipjgc4r3fqmfk8mlldl5sl5 Contents of $_GET: Contents of $_POST: Contents of $_COOKIE:

    If click “Next” on the first page, you will be running http://localhost/SessionPage2.php, and you will get:

    I am buying 3 PHP books. The unit price is 9.99 per book. Next Prev Counter = 2 Session name = PHPSESSID Session id = o9oipjgc4r3fqmfk8mlldl5sl5 Contents of $_GET: Contents of $_POST: Contents of $_COOKIE: PHPSESSID = o9oipjgc4r3fqmfk8mlldl5sl5

    If click “Next” on the second page, you will be running http://localhost/SessionPage3.php, and you will get:

    I am buying 3 PHP books. The unit price is 9.99 per book. The total price is 29.97. Prev Counter = 3 Session name = PHPSESSID Session id = o9oipjgc4r3fqmfk8mlldl5sl5 Contents of $_GET: Contents of $_POST: Contents of $_COOKIE: PHPSESSID = o9oipjgc4r3fqmfk8mlldl5sl5

    As you can see, the session concept is working. Several points should be noted here:

    • Data can be stored into the session in one page, and retrieve it in another page. For example, the quantity is stored into the session in the first page, and retrieved in the second and third page.
    • The session name is a string defined in the php.ini file.
    • The session ID is created by PHP, and managed as a cookie.
    • You can use the session object to manage a count of pages visited in a particular session. But you can not use the session object to manage a count of pages visited in all sessions. To manage information across versions, you need something called application object provided in Active Server Page (ASP).

    PHP can also manage session IDs without using the cookie technology. To do this, we need to modify \php\php.ini to stop using cookie and start transparent session id:

    session.use_cookies = 0
    session.use_trans_sid = 1

    Now if you re-run http://localhost/SessionPage1.php, you will get:

    I am buying 3 PHP books.
    
    Next
    
    Counter = 1
    Session name = PHPSESSID
    Session id = mg04r204ctuloo2uegmih14ri5
    Session module = files
    
    Contents of $_GET:
    
    Contents of $_POST:
    
    Contents of $_COOKIE:

    If click “Next” on the first page, you will be running http://localhost/SessionPage2.php, and you will get:

    I am buying 3 PHP books.
    The unit price is 9.99 per book.
    
    Next  Prev
    
    Counter = 2
    Session name = PHPSESSID
    Session id = mg04r204ctuloo2uegmih14ri5
    
    Contents of $_GET:
       PHPSESSID = mg04r204ctuloo2uegmih14ri5
    
    Contents of $_POST:
    
    Contents of $_COOKIE:

    If click “Next” on the second page, you will be running http://localhost/SessionPage3.php, and you will get:

    I am buying 3 PHP books.
    The unit price is 9.99 per book.
    The total price is 29.97.
    
    Prev
    
    Counter = 3
    Session name = PHPSESSID
    Session id = mg04r204ctuloo2uegmih14ri5
    
    Contents of $_GET:
       PHPSESSID = mg04r204ctuloo2uegmih14ri5
    
    Contents of $_POST:
    
    Contents of $_COOKIE:

    A couple of interesting things happened here:

    • If you ask PHP to use transparent session ID management, it will modify all the links to include the session ID as part of the URL. See the source of the first page in the browser, you will see the ULR of “Next” button as href=SessionPage2.php?PHPSESSID=mg04r204ctuloo2uegmih14ri5.
    • The outputs show that now the session ID is stored in $_GET.
    • Since the session ID in the URL field of the browser, everyone can see it. Not so secure.

    Where Is Session Data Stored?

    Question, where does PHP store the session data? The answer is not so obvious.

    Since I am running PHP in CGI mode, PHP pages are running with individual instances of PHP executables. So there is no easy to store session data in memory and share it between PHP pages. If not stored in memory, the session data can be stored on hard disk and share it between PHP pages. Let’s see if we can find where the session data is stored on the hard disk.

    First run http://localhost/SessionPage1.php again:

    I am buying 3 PHP books.
    
    Next
    
    Counter = 1
    Session name = PHPSESSID
    Session id = mg04r204ctuloo2uegmih14ri5
    Session module = files
    
    Contents of $_GET:
    
    Contents of $_POST:
    
    Contents of $_COOKIE:

    Then use Windows find tool to search for file names with “mg04r204ctuloo2uegmih14ri5″. No surprise, you will get \windows\temp\sess_mg04r204ctuloo2uegmih14ri5. Open this file in a text editor, you will see:

    quantity|i:3;count|i:1;

    The file format is so simple, session data is stored as clear text, with “;” as delimiters. If you want to change where the data is stored, you can modify \php\php.ini with:

    session.save_path = "/tmp"

    Conclusion

    • PHP can manage session IDs in two ways: as a cookie and as GET variable.
    • Managing sessions with cookies is much secure.
    • Session data is stored on hard disk permanently.
    • You must call session_start() at the beginning of the PHP script.
    • Session data is shared in an array called $_SESSION.
    • Using Cookies

    This chapter describes:

    • What is a Cookie?
    • Sending and Receiving Cookies
    • Output Control Functions
    • Persistent Cookies
    • Other Cookie Properties

    What is a Cookie?

    Cookie: A small amount of information sent by a Web server to a Web browser, saved by the browser, and sent back to the server later. Cookies are transmitted inside the HTTP header.

    Cookies move from server to browser, and back to server as follows:

    Web         Web         Local       Web           Web
    Server      Browser     System      Browser       Server
    Send        Receive     Save        Send back     Receive
    cookies --> cookies --> cookies --> cookies   --> cookies

    As you can see from the diagram, cookies are actually saved to the hard disk of Web browser user’s machines. Many users are concerned about this. But I think it is pretty safe to allow your browser to save cookies.

    If you are really concerned, you can change your browser’s settings to reject cookies. But this may cause many Web based applications fail to run on your browser.

    Sending and Receiving Cookies

    Cookies are supported in PHP in the following ways:

    1. setcookie() – A built-in function that defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and return FALSE. setcookie() can be called using the following simple syntax:

    bool setcookie(string name, string value)

    where “name” is the name of the cookie, and “value” is the value of the cookie.

    2. $_COOKIE[] – A pre-defined associate array that stores cookies submitted by the browser.

    To demontrate how to send and receive cookies, I wrote the following PHP script page, CookieTest.php:

    <?php #CookieTest.php
    #
       $numCookies = count( array_keys($_COOKIE) );
       $numCookies++;
       $cookieName = "Cookie_$numCookies";
       $cookieValue = "My cookie value";
       setcookie($cookieName, $cookieValue);
    
       print("<pre>\n");
       print("Cookies added by the server:\n");
       print("   $cookieName: $cookieValue\n");
    
       print("\nCookies received by the server:\n");
       foreach ($_COOKIE as $k => $v) {
          print "   $k = $v\n";
       }
    
       print "</pre>\n";
    ?>

    I opened this page with IE, I got:

    Cookies added by the server:
       Cookie_1: My cookie value
    
    Cookies received by the server:

    I clicked the refresh button on the IE window, I got:

    Cookies added by the server: Cookie_2: My cookie value Cookies received by the server: Cookie_1 = My cookie value

    What happened here was that when I opened the page the first time, the server received no cookie from the browser’s request. But my page added one cookie named as “Cookie_1″ to the response.

    When I clicked the refresh button, the browser sent my cookie back to the server in the request. Then my page added another cookie named as “Cookie_2″ in the response.

    If I keep clicking the refresh button, more and more cookies would be added to the request and response. But there is a limit. The browser will only take up to 20 cookies from one Web server.

    Output Control Functions

    As you can see from setcookie() definition, the PHP engine provides no buffer for the HTTP response body. That means as soon the PHP script starts to send output to the HTTP response body, the HTTP header block will be finalized, and no allowed to change.

    But this default behavior can be altered by calling output control functions:

    • setcookie() must be called before any output to the HTTP response. The main reason is that PHP is not buffering the HTTP response. But you can alter this behavior by using ob_*() functions.
    • ob_start() – A built-in function that turns on output buffering.
    • flush() – A built-in function that flushes out the contents of the output buffer to the HTTP response body.

    Of course, default behavior can also be altered by the configuration file, php.ini. Open php.ini and set the following line:

    output_buffering = 4096

    The above configuration line tells the PHP engine to turn on output buffering, and set the buffer size to 4096 bytes. Once “output_buffering” is turned on, you don’t have to call ob_start() in your scripts.

    To test the PHP engine default behavior, I modified CookieTest.php into CookieOutputBuffer.php:

    <?php

    #CookieOutputBuffer.php

    #

    print(“<pre>\n”);

    print(“Adding cookies by the server:\n”);

    $numCookies = count( array_keys($_COOKIE) );

    $numCookies++;

    $cookieName = “Cookie_$numCookies”;

    $cookieValue = “My cookie value”;

    print(” $cookieName:

    $cookieValue\n”);

    setcookie($cookieName,

    $cookieValue);

    print(“\nCookies received by the server:\n”);

    foreach ($_COOKIE as $k => $v)

    {

    print ” $k = $v\n”;

    }

    print “</pre>\n”;

    ?>

    I then opened php.ini and set the following line:

    output_buffering = 0

    Running IE on CookieOutputBuffer.php gave me this:

    Adding cookies by the server: Cookie_2: My cookie value Cookies received by the server: User = Herong Yang PHP Warning: Cannot modify header information – headers already sent by (output started at …\CookieOutputBuffer.php:4) …

    Now I truly beblieve that PHP engine’s default behavior is no output buffering. Make sure to change “output_buffering” back to 4096 before continuing to the next test.

    Persistent Cookies

    There are two kinds of cookies: persistent cookies and temporary cookies.

    A persistent cookie is stored in a file on your computer. It remains there when you close Internet Explorer. The cookie can be read by the Web site that created it when you visit that site again.

    A temporary or session cookie is stored only for your current browsing session. It is deleted from your computer when you close Internet Explorer.

    The default behavior of setcookie(name,value) is to set a cookie as a temporary cookie. To set a persistent cookie, we need to add another parameter to the setcookie() function call as in the following syntax:

    bool setcookie(string name, string value, int expire)

    where “expire” specifies when this cookie should be expired. If the expiration time is a future time, like 30 days from today, this cookie will be set as a persistent cookie. Note that “expire” should be represented in number of seconds since the epoch. The best way to set “expire” is use the time() function, which represents the current time in number of seconds since the epoch. Example, 30 days from today can be expressed as “time()+60*60*24*30″.

    If “expire” is not given, a temporary cookie will be created.

    To show you how to set a persistent cookie, and how the cookie is store in a file, I wrote the following PHP script page, CookiePersisted.php:

    <?php #CookiePersisted.php
    #
       $cookieName = "User";
       $cookieValue = "Herong Yang";
       $expiration = time()+60*60*24*30;
       setcookie($cookieName, $cookieValue, $expiration);
    
       print("<pre>\n");
       print("Cookies added by the server:\n");
       print("   $cookieName: $cookieValue\n");
       print("   Expires at: $expiration\n");
       print "</pre>\n";
    ?>

    I opened this page with IE, I got:

    Cookies added by the server:
       User: Herong Yang
       Expires at: 1134531525

    To find out in which file this cookie is stored in my computer, I clicked at IE “Tools” menu, selected “Internet Options…”. and clicked the “Settings…” button in the “Temporary Internet files” section of the “General” tab. I saw where is my “Temporary Internet files folder”. So I went to that folder, and saw a cookie file named something like “Cookie:user@localhost/”. I double clicked on that file, and managed to open it in notepad:

    User
    Herong+Yang
    localhost/
    1024
    3801469056
    29753439
    3934260416
    29747404
    *

    Actually, I saw a lots of other cookie files created by other Web sites that I have visited in the past. I deleted all of them.

    Other Cookie Properties

    A cookie also has two other properties:

    1. “domain” – A property that defines the domain of Web servers to which this cookie should be made available. Web browsers will send a cookie back to a Web server when the Web server matches its defined domain. Web browsers will never send back a cookie to a domain other than its defined domain.

    For example, if a cookie’s domain is www.google.com, the browser will send back this cookie to the server only when the browser is visiting www.google.com. The browser will never send back this cookie to www.yahoo.com.

    To make a cookie available for all sub domains of a top level domain, set the domain property to the top level domain name. For example, if a cookie’s domain is set to “.google.com”, this cookie will be available to all google sub domains, like groups.google.com and gmail.google.com.

    2. “path” - A property that defines a Web server path to which this cookie should be made available. Web browsers will send a cookie back to a Web server when the Web server matches its defined domain, and the requested page matches its defined path. Web browsers will never send back a cookie to requested path other than its defined path.

    Note that the defined path also includes all its sub paths. For example, if a cookie’s domain is “www.amazon.com”, and path is “/order/”, then a browser will send back this cookie for requests like “http://www.amazon.com/order/checkout.html”, and “http://www.amazon.com/order/report/invoice.html”. But a browser should not send back this cookie for requests like “http://www.amazon.com/catelog/book.html”.

    The setcookie() function offers two more parameters to allow you to set “domain” and “path” properties on a cookie as in the following syntax:

    bool setcookie(string name, string value, int expire, string path,
       string domain)

    where “path” specifies the cookie’s path property, and “domain” specifies the cookie’s domain property. If “path” is not given, the cookie will have “/” as the default path. If “domain” is not given, the cookie will have the current domain as the default domain.

    Okay. Let’s play the properties with the following script, CookieProperties.php:

    <?php #CookieProperties.php
    #
       print("<pre>\n");
       print("\nAdding a cookie with default properties:\n");
    
       $cookieName = "User";
       $cookieValue = "Herong Yang";
       $expiration = time()+60*60*24*30;
       setcookie($cookieName, $cookieValue, $expiration);
       print("   Name: $cookieName\n");
       print("   Value: $cookieValue\n");
       print("   Expiration: $expiration\n");
    
       print("\nAdding a cookie with non-default properties:\n");
       $cookieName = "Book";
       $cookieValue = "Herong's Tutorial Notes on PHP";
       $expiration = time()+60*60*24*30;
       $path = "/";
       $domain = "localhost";
       setcookie($cookieName, $cookieValue, $expiration, $path, $domain);
       print("   Name: $cookieName\n");
       print("   Value: $cookieValue\n");
       print("   Expiration: $expiration\n");
       print("   Path: $path\n");
       print("   Domain: $domain\n");
    
       print("\nCookies received by the server:\n");
       foreach ($_COOKIE as $k => $v) {
          print "   $k = $v\n";
       }
    
       print "</pre>\n";
    ?>

    Ran this script in IE, I got:

    Adding a cookie with default properties:
       Name: User
       Value: Herong Yang
       Expiration: 1134622043
    
    Adding a cookie with non-default properties:
       Name: Book
       Value: Herong's Tutorial Notes on PHP
       Expiration: 1134622043
       Path: /
       Domain: localhost

    Clicked the refresh button on IE, I got:

    Adding a cookie with default properties:
       Name: User
       Value: Herong Yang
       Expiration: 1134622059
    
    Adding a cookie with non-default properties:
       Name: Book
       Value: Herong's Tutorial Notes on PHP
       Expiration: 1134622059
       Path: /
       Domain: localhost
    
    Cookies received by the server:
       User = Herong Yang

    Apparently, my script did not set the properties correctly. The browser should have sent back my second cookie also. So either the “path=/” or “domain=localhost” did not match my local IIS environment. I could not figure it out why.

    Conclusion

    • setcookie() must be called before any output to the HTTP response. The main reason is that PHP is not buffering the HTTP response. But you can alter this behavior by using ob_*() functions.
    • A persistent cookie is stored in a cookie file on the browser’s local machine.
    • A persistent cookie can have a expiration time to be expressed in number of seconds since epoch.
    • Web browser will only send back a cookie when both domain and path match the requested domain and path.
    • To make a cookie available for all sub domains of a top level domain, set the domain property to the
    • top level domain name.

    &lt;a href=”http://www.bidvertiser.com” mce_href=”http://www.bidvertiser.com”&gt;internet advertising&lt;/a&gt;

    2 Responses

    1. [...] PHP, programming Do you know which programming languages is popular on web? I got the idea from technolearn. I started search on Google and in before I read a blog post about it. Try out and see the result [...]

    2. Thanks for tutorials. So great for newbie.

    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 )

    Connecting to %s

    Follow

    Get every new post delivered to your Inbox.