PHP 5 Data Types+

PHP Strings


PHP Integers


PHP Floating Point Numbers


PHP Booleans


PHP Arrays


PHP Objects


PHP NULL Value


Resources Type

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.

See also the get_resource_type() function.

Converting to resource Type

As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.

Freeing resources Type

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.

PHP Constants +

Constants are like variables except that once they are defined they cannot be changed or undefined.

A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

Set a PHP Constant

To set a constant, use the define() function - it takes three parameters: The first parameter defines the name of the constant, the second parameter defines the value of the constant, and the optional third parameter specifies whether the constant name should be case-insensitive. Default is false.

The example below creates a case-sensitive constant, with the value of "Welcome to W3Schools.com!":

// define a case-sensitive constant
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;

// will not output the value of the constant
echo greeting;
--------------------------------------------

The example below creates a case-insensitive constant, with the value of "Welcome to W3Schools.com!":

// define a case-insensitive constant
define("GREETING", "Welcome to W3Schools.com!", true);
echo GREETING;

// will also output the value of the constant
echo greeting;

The output will be :
Welcome to W3Schools.com!
Welcome to W3Schools.com!
--------------------------------------------------------------------------------------------------

There are a number of constants automatically set for you by PHP in order to save you having to recalculate complicated values each time in your script, but it also provides other helpful information. For example, PHP always sets the __FILE__, __LINE__, __FUNCTION__, __CLASS__, and __METHOD__ constants for you - note that those are double underscores on either side to make it unlikely you will want to use them for your own constants.

These five pre-set constants give you the following:

__FILE__

The script filename being parsed. Note that this reports the file that contains the current line of code, so this will report the name of an include file if used therein.

__LINE__

The line number PHP is executing

__FUNCTION__

The name of the function PHP is currently inside

__CLASS__

The name of the class of the object being used

__METHOD__

The name of the class function PHP is currently inside

PHP Variable Naming Convention +

Function

Function names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged in most cases.

Function names must always start with a lowercase letter. When a function name consists of more than one word, the first letter of each new word must be capitalized. This is commonly called "camelCase" formatting.

Verbosity is generally encouraged. Function names should be as verbose as is practical to fully describe their purpose and behavior.

Variables

Variable names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged in most cases.

For instance variables that are declared with the "private" or "protected" modifier, the first character of the variable name must be a single underscore. This is the only acceptable application of an underscore in a variable name. Member variables declared "public" should never start with an underscore.

Constants

Constants may contain both alphanumeric characters and underscores. Numbers are permitted in constant names.

All letters used in a constant name must be capitalized, while all words in a constant name must be separated by underscore characters.

For example, EMBED_SUPPRESS_EMBED_EXCEPTION is permitted but EMBED_SUPPRESSEMBEDEXCEPTION is not.

Constants must be defined as class members with the "const" modifier. Defining constants in the global scope with the "define" function is permitted but strongly discouraged.

$this

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

While the PHP runtime generates an error if you directly assign $this in code, it doesn't for $$name when name is 'this'.

<?php

$this = 'text'; // error

$name = 'this';
$$name = 'text'; // sets $this to 'text'
?>

9 Confusing Naming Conventions for Beginners

Referencing a variable +

When you use the = (equals) operator, PHP performs a "copy equals" - it takes the value from operand two and copies it into operand one. While this is fine for most purposes, it doesn't work when you want to be able to change operand two later on and have operand one also change.

In this situation, references are helpful - they allow you to have two variables pointing to the same data. Using references, setting operand one to equal operand two is instantaneous. Furthermore, once two variables are pointing to the same data, you can change either variable and the other one will also update. To assign by reference you need to use the reference operator, &, after the equals operator, giving =&. Here's how it looks:

<?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.
?>

PHP 5 Global Variables - Superglobals+

Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in all scopes.

Several predefined variables in PHP are "superglobals", which means that they are always accessible, 
regardless of scope - and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

    $GLOBALS
    $_SERVER
    $_REQUEST
    $_POST
    $_GET
    $_FILES
    $_ENV
    $_COOKIE
    $_SESSION
  

PHP $GLOBALS

$GLOBALS is a PHP super global variable which is used to access global variables 
from anywhere in the PHP script (also from within functions or methods).

PHP stores all global variables in an array called $GLOBALS[index]. 
The index holds the name of the variable.

The example below shows how to use the super global variable $GLOBALS:

$x = 75; 
$y = 25;
 
function addition() { 
  $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; 
}
 
addition(); 
echo $z; 

The ouput will be:
100

In the example above, since z is a variable present within the $GLOBALS array, 
it is also accessible from outside the function!
----------------------------------------------------------------------

PHP $_SERVER


$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

The example below shows how to use some of the elements in $_SERVER:

echo $_SERVER['PHP_SELF'];
echo $_SERVER['SERVER_NAME'];
echo $_SERVER['HTTP_HOST'];
echo $_SERVER['HTTP_REFERER'];
echo $_SERVER['HTTP_USER_AGENT'];
echo $_SERVER['SCRIPT_NAME'];

The output will be:
/php/demo_global_server.php
www.w3schools.com
www.w3schools.com
http://www.w3schools.com/php/showphp.asp?filename=demo_global_server
Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
/php/demo_global_server.php
-----------------------------------------------------------------------

Element/Code			Description
------------			-------------

$_SERVER['PHP_SELF']	Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE']	Returns the version of the Common Gateway Interface (CGI) the server is using
$_SERVER['SERVER_ADDR']	Returns the IP address of the host server
$_SERVER['SERVER_NAME']	Returns the name of the host server (such as www.w3schools.com)
$_SERVER['SERVER_SOFTWARE']	Returns the server identification string (such as Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL']	Returns the name and revision of the information protocol (such as HTTP/1.1)
$_SERVER['REQUEST_METHOD']	Returns the request method used to access the page (such as POST)
$_SERVER['REQUEST_TIME']	Returns the timestamp of the start of the request (such as 1377687496)
$_SERVER['QUERY_STRING']	Returns the query string if the page is accessed via a query string
$_SERVER['HTTP_ACCEPT']	Returns the Accept header from the current request
$_SERVER['HTTP_ACCEPT_CHARSET']	Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST']	Returns the Host header from the current request
$_SERVER['HTTP_REFERER']	Returns the complete URL of the current page (not reliable because not all user-agents support it)
$_SERVER['HTTPS']	Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR']	Returns the IP address from where the user is viewing the current page
$_SERVER['REMOTE_HOST']	Returns the Host name from where the user is viewing the current page
$_SERVER['REMOTE_PORT']	Returns the port being used on the user's machine to communicate with the web server
$_SERVER['SCRIPT_FILENAME']	Returns the absolute pathname of the currently executing script
$_SERVER['SERVER_ADMIN']	Returns the value given to the SERVER_ADMIN directive in the web server configuration file 
							(if your script runs on a virtual host, it will be the value defined for that virtual host) (such as someone@w3schools.com)
$_SERVER['SERVER_PORT']	Returns the port on the server machine being used by the web server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE']	Returns the server version and virtual host name which are added to server-generated pages
$_SERVER['PATH_TRANSLATED']	Returns the file system based path to the current script
$_SERVER['SCRIPT_NAME']	Returns the path of the current script
$_SERVER['SCRIPT_URI']	Returns the URI of the current page

Note that you need to use HTTP_REFERER and not HTTP_REFERRER. This is one of the very few misspellings ever to make it into a web standard, but is now in widespread use and so too late to change.

<?php
    if (isset($_SERVER['HTTP_REFERER'])) {
        print "The page you were on previously was {$_SERVER['HTTP_REFERER']}<br />";
    } else {
        print "You didn't click any links to get here<br />";
    }
?>
<a href="refer.php">Click me!</a>

When that page is loaded up in your browser by typing the URL in by hand, the "You didn't click any links to get here" text is shown because HTTP_REFERER has not been set. However, if once the page is loaded you click the "Click me!" link, the page will reload itself and this time HTTP_REFERER will be set and the new message should appear. Although it can be spoofed, HTTP_REFERER is generally a good way to make sure a visitor came from a certain page - whether you want to use that to say, "you can't download my files because you came from another site", or "welcome, Google users!" is down to you, but there is a lot of scope for ideas.

The PATH_INFO element in $_SERVER is particularly interesting, because it allows you to grab directory information specified after the script. Consider this script:

<?php
    if (isset($_SERVER['PATH_INFO'])) {
        print "The page you requested was {$_SERVER['PATH_INFO']}<br />";
    } else {
        print "You didn't request a page
"; } ?>

If you save that as pathinfo.php in your document root, try loading it up in your web browser - you should see "you didn't request a page". Now, try editing the URL so that after pathinfo.php is a filename, with as much directory information as you want. For example:

www.yoursite.com/pathinfo.php/path/to/some/file.txt. Now when you load the page, you should see that extra path information printed out. This is commonly used in online filesystems, as it means that the URLs required to get to files are just the name of the script followed by the filename wanted.

Note: Remember that the referrer value is set by the web browser, which means it can easily be faked. One common example of this is to edit the "hosts" file of the computer (/etc/hosts in Unix; c:\windows\system32\drivers\etc\hosts in Windows) so that the current computer is used as www.example.com. Then, J. Evil Hacker loads a simple page on their computer with a link to your "secure" script, and his browser will report that he came from example.com. As a result, you should never rely on HTTP_REFERER to be set, valid, or truthful, but it is a good start.


PHP $_REQUEST

PHP $_REQUEST is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the form tag. In this example, we point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field:

PHP Sessions+

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

PHP Session Variables

When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start(); ?>

The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

Storing a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:


Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

The Anatomy of a Cookie: +

Cookies are usually set in an HTTP header

A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS["name"]

Setting Cookies with PHP:

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments:

  • Name - This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
  • Value - This sets the value of the named variable and is the content that you actually want to store.
  • Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
  • Path - This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
  • Domain - This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
  • Security - This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
  • Following example will create two cookies name and age these cookies will be expired after one hour.

    <?php
       setcookie("name", "John Watkin", time()+3600, "/","", 0);
       setcookie("age", "36", time()+3600, "/", "",  0);
    ?>
    <html>
    <head>
    <title>Setting Cookies with PHP</title>
    </head>
    <body>
    <?php echo "Set Cookies"?>
    </body>
    </html>
    

    Accessing Cookies with PHP

    PHP provides many ways to access cookies.Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

    <html>
    <head>
    <title>Accessing Cookies with PHP</title>
    </head<
    <body>
    <?php
    echo $_COOKIE["name"]. "<br />";
    /* is equivalent to */
    echo $HTTP_COOKIE_VARS["name"]. "<br />";
    
    echo $_COOKIE["age"] . "<br />";
    /* is equivalent to */
    echo $HTTP_COOKIE_VARS["name"] . "<br />";
    ?>
    </body>
    </html>
    

    You can use isset() function to check if a cookie is set or not.

    <html>
    <head>
    <title>Accessing Cookies with PHP</title>
    </head>
    <body>
    <?php
      if( isset($_COOKIE["name"]))
        echo "Welcome " . $_COOKIE["name"] . "<br />";
      else
        echo "Sorry... Not recognized" . "<br />";
    ?>
    </body>
    </html>
    

    Deleting Cookie with PHP

    Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.

    It is safest to set the cookie with a date that has already expired:

    <?php
      setcookie( "name", "", time()- 60, "/","", 0);
      setcookie( "age", "", time()- 60, "/","", 0);
    ?>
    <html>
    <head>
    <title>Deleting Cookies with PHP</title>
    </head>
    <body>
    <?php echo "Deleted Cookies" ?>
    </body>
    </html>
    

    Incrementing and decrementing operators +

    ++$a

    Pre-increment

    Increments $a by one, then returns $a

    $a++

    Post-increment

    Returns $a, then increments $a by one

    --$a

    Pre-decrement

    Decrements $a by one, then returns $a

    $a--

    Post-decrement

    Returns $a, then decrements by one

    The Ternary Operator +

    There are three operators that are complicated enough to get their own section, of which the first is the ternary operator. It is called the ternary operator because it takes three operands - a condition, a result for true, and a result for false. If that sounds like an if statement to you, you are right on the money - the ternary operator is a shorthand (albeit very hard to read) way of doing if statements. Here's an example:

    <?php      $agestr = ($age < 16) ? 'child' : 'adult';  ?>  

    First there is a condition ($age < 16), then there is a question mark, and then a true result, a colon, and a false result. If $age is less than 16, $agestr will be set to 'child', otherwise it will be set to 'adult'. That one-liner ternary statement can be expressed in a normal if statement like this:

    <?php      
      if ($age < 16) {
            $agestr = 'child';
        } else {
            $agestr = 'adult';
        }
      ?>

    So, in essence, using the ternary operator allows you to compact five lines of code into one, at the expense of some readability.

    OTHER +

    Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.

    $variable = "name";
    $literally = 'My $variable will not print!\\n';
    print($literally);
    $literally = "My $variable will print!\\n";
    print($literally);
    

    PHP for Loop in exclusive style basic to advance +

    <?php
    // cv= counter variable
    
    /* example 1
     Common style*/
    for ($cv = 1; $cv <= 10; $cv++) {
     echo $cv;
     }
    /* Bellow example 2
     no condition in  expression 2 in for loop
     but inside of for code block {}*/
     */
    for ($cv = 1; ; $cv ++) {
     if ($cv > 10) {
     break;
     }
     echo $cv;
     }
    /* Bellow example 3
     Variable initialize outside of for loop, no condition in 2nd expression and no increment/decrement in for loop, but inside of for code block {}*/
    $cv = 1;
     for (; ; ) {
     if ($cv > 10) {
     break;
     }
     echo $cv;
     $cv++;
     }
    /* example 4
     Is exclusive style and advance style*/
    for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
    ?>
    

    +