+ All Categories
Home > Documents > Introduction to PHP (w3school)

Introduction to PHP (w3school)

Date post: 13-Apr-2018
Category:
Upload: jatmiko-heri-setiawan
View: 264 times
Download: 0 times
Share this document with a friend

of 86

Transcript
  • 7/27/2019 Introduction to PHP (w3school)

    1/86

    PHP 5 Introduction

    PHP scripts are executed on the server.

    What You Should Already Know

    Before you continue you should have a basic understanding of the following:

    HTML CSS JavaScript

    If you want to study these subjects first, find the tutorials on ourHome page.

    What is PHP? PHP is an acronym for "PHP Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP costs nothing, it is free to download and use

    PHP is simple for beginners.

    PHP also offers many advanced features for professional programmers.

    What is a PHP File?

    PHP files can contain text, HTML, CSS, JavaScript, and PHP code PHP code are executed on the server, and the result is returned to the browser as plain

    HTML PHP files have extension ".php"

    What Can PHP Do?

    PHP can generate dynamic page content PHP can create, open, read, write, delete, and close files on the server PHP can collect form data PHP can send and receive cookies PHP can add, delete, modify data in your database PHP can restrict users to access some pages on your website PHP can encrypt data

    http://www.w3schools.com/default.asphttp://www.w3schools.com/default.asphttp://www.w3schools.com/default.asphttp://www.w3schools.com/default.asp
  • 7/27/2019 Introduction to PHP (w3school)

    2/86

    With PHP you are not limited to output HTML. You can output images, PDF files, and evenFlash movies. You can also output any text, such as XHTML and XML.

    Why PHP?

    PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP supports a wide range of databases PHP is free. Download it from the official PHP resource:www.php.net PHP is easy to learn and runs efficiently on the server side

    PHP 5 Syntax

    The PHP script is executed on the server, and the plain HTML result is sent back to the browser.

    Basic PHP Syntax

    A PHP script can be placed anywhere in the document.

    A PHP script starts with

    :

    The default file extension for PHP files is ".php".

    A PHP file normally contains HTML tags, and some PHP scripting code.

    Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHPfunction "echo" to output the text "Hello World!" on a web page:

    http://www.php.net/http://www.php.net/http://www.php.net/http://www.php.net/
  • 7/27/2019 Introduction to PHP (w3school)

    3/86

    Example

    My first PHP page

    Note:PHP statements are terminated by semicolon (;).The closing tag of a block of PHP codealso automatically implies a semicolon (so you do not have to have a semicolon terminating the

    last line of a PHP block).

    Comments in PHP

    A comment in PHP code is a line that is not read/executedas part of the program. Its onlypurpose is to be read by someone who is editing the code!

    Comments are useful for:

    To let others understand what you are doing- Comments let other programmers

    understand what you were doing in each step (if you work in a group) To remind yourself what you did- Most programmers have experienced coming back to

    their own work a year or two later and having to re-figure out what they did. Commentscan remind you of what you were thinking when you wrote the code

    PHP supports three ways of commenting:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    4/86

    This is a multiple lines comment blockthat spans over more thanone line*/?>

    PHP Case Sensitivity

    In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) areNOT case-sensitive.

    In the example below, all three echo statements below are legal (and equal):

    Example

    However; in PHP, all variables are case-sensitive.

    In the example below, only the first statement will display the value of the $color variable (this isbecause $color, $COLOR, and $coLOR are treated as three different variables):

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    5/86

    echo "My car is " . $color . "
    ";echo "My house is " . $COLOR . "
    ";echo "My boat is " . $coLOR . "
    ";?>

    PHP 5 Variables

    Variables are "containers" for storing information:

    Example

    Much Like Algebra

    x=5

    y=6z=x+y

    In algebra we use letters (like x) to hold values (like 5).

    From the expression z=x+y above, we can calculate the value of z to be 11.

    In PHP these letters are called variables.

    Think of variables as containers for storing data.

    PHP Variables

    As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).

    A variable can have a short name (like x and y) or a more descriptive name (age, carname,total_volume).

  • 7/27/2019 Introduction to PHP (w3school)

    6/86

    Rules for PHP variables:

    A variable starts with the $ sign, followed by the name of the variable A variable name must start with a letter or the underscore character A variable name cannot start with a number

    A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,and _ ) Variable names are case sensitive ($y and $Y are two different variables)

    Remember that PHP variables are case-sensitive.

    Creating (Declaring) PHP Variables

    PHP has no command for declaring a variable.

    A variable is created the moment you first assign a value to it:

    Example

    After the execution of the statements above, the variable txtwill hold the value Hello world!,the variable xwill hold the value 5, and the variable ywill hold the value 10.5.

    Note:When you assign a text value to a variable, put quotes around the value.

    PHP is a Loosely Type Language

    In the example above, notice that we did not have to tell PHP which data type the variable is.

    PHP automatically converts the variable to the correct data type, depending on its value.

    In other languages such as C, C++, and Java, the programmer must declare the name and type ofthe variable before using it.

    PHP Variables Scope

    In PHP, variables can be declared anywhere in the script.

  • 7/27/2019 Introduction to PHP (w3school)

    7/86

    The scope of a variable is the part of the script where the variable can be referenced/used.

    PHP has three different variable scopes:

    local

    global static

    Local and Global Scope

    A variable declared outsidea function has a GLOBAL SCOPE and can only be accessed outsidea function.

    A variable declared withina function has a LOCAL SCOPE and can only be accessed withinthat function.

    The following example tests variables with local and global scope:

    Example

    In the example above there are two variables $x and $y and a function myTest(). $x is a globalvariable since it is declared outside the function and $y is a local variable since it is createdinside the function.

  • 7/27/2019 Introduction to PHP (w3school)

    8/86

    When we output the values of the two variables inside the myTest() function, it prints the valueof $y as it is the locally declared, but cannot print the value of $x since it is created outside thefunction.

    Then, when we output the values of the two variables outside the myTest() function, it prints the

    value of $x, but cannot print the value of $y since it is a local variable and it is created inside themyTest() function.

    You can have local variables with the same name in different functions, because localvariables are only recognized by the function in which they are declared.

    PHP The global Keyword

    The global keyword is used to access a global variable from within a function.

    To do this, use the global keyword before the variables (inside the function):

    Example

    PHP also stores all global variables in an array called $GLOBALS[index]. The indexholds thename of the variable. This array is also accessible from within functions and can be used toupdate global variables directly.

    The example above can be rewritten like this:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    9/86

    PHP The static Keyword

    Normally, when a function is completed/executed, all of its variables are deleted. However,

    sometimes we want a local variable NOT to be deleted. We need it for a further job.

    To do this, use the statickeyword when you first declare the variable:

    Example

    Then, each time the function is called, that variable will still have the information it containedfrom the last time the function was called.

    Note:The variable is still local to the function.

  • 7/27/2019 Introduction to PHP (w3school)

    10/86

    PHP 5 echo and print Statements

    In PHP there is two basic ways to get output: echo and print.

    In this tutorial we use echo (and print) in almost every example. So, this chapter contains a littlemore info about those two output statements.

    PHP echo and print Statements

    There are some differences between echo and print:

    echo - can output one or more strings print - can only output one string, and returns always 1

    Tip:echo is marginally faster compared to print as echo does not return any value.

    The PHP echo Statement

    echo is a language construct, and can be used with or without parentheses: echo or echo().

    Display Strings

    The following example shows how to display different strings with the echo command (alsonotice that the strings can contain HTML markup):

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    11/86

    The following example shows how to display strings and variables with the echo command:

    Example

    Result:Learn PHPStudy PHP at W3Schools.comMy car is a Volvo

    The PHP print Statement

    print is also a language construct, and can be used with or without parentheses: print or print().

    Display Strings

    The following example shows how to display different strings with the print command (alsonotice that the strings can contain HTML markup):

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    12/86

    Example

    PHP Data Types

    String, Integer, Floating point numbers, Boolean, Array, Object, NULL.

    PHP Strings

    A string is a sequence of characters, like "Hello world!".

    A string can be any text inside quotes. You can use single or double quotes:

    Example

    Result:Hello world!Hello world!

    PHP Integers

    An integer is a number without decimals.

    Rules for integers:

  • 7/27/2019 Introduction to PHP (w3school)

    13/86

    An integer must have at least one digit (0-9) An integer cannot contain comma or blanks An integer must not have a decimal point An integer can be either positive or negative Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based -

    prefixed with 0x) or octal (8-based - prefixed with 0)

    In the following example we will test different numbers. The PHP var_dump() functionreturnsthe data type and value of variables:

    Example

    Result:

    int(5985)int(-345)int(140)int(39)

    PHP Floating Point Numbers

    A floating point number is a number with a decimal point or a number in exponential form.

    In the following example we will test different numbers. The PHP var_dump() function returnsthe data type and value of variables:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    14/86

    Result:float(10.365)float(2400)float(8.0E-5)

    PHP Booleans

    Booleans can be either TRUE or FALSE.

    $x=true;$y=false;

    Booleans are often used in conditional testing. You will learn more about conditional testing in alater chapter of this tutorial.

    PHP ArraysAn array stores multiple values in one single variable.

    In the following example we create an array, and then use the PHP var_dump() function to returnthe data type and value of the array:

    Example

    Result:

  • 7/27/2019 Introduction to PHP (w3school)

    15/86

    array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }

    You will learn a lot more about arrays in later chapters of this tutorial.

    PHP Objects

    An object is a data type which stores data and information on how to process that data.

    In PHP, an object must be explicitly declared.

    First we must declare a class of object. For this, we use the class keyword. A class is a structurethat can contain properties and methods.

    We then define the data type in the object class, and then we use the data type in instances of thatclass:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    16/86

    ?>

    Result :\herbie: Properties color = white

    You will learn more about objects in a later chapter of this tutorial.

    PHP NULL Value

    The special NULL value represents that a variable has no value. NULL is the only possible valueof data type NULL.

    The NULL value identifies whether a variable is empty or not. Also useful to differentiatebetween the empty string and null values of databases.

    Variables can be emptied by setting the value to NULL:

    Example

    PHP String Functions

    A string is a sequence of characters, like "Hello world!".

    PHP String Functions

    In this chapter we will look at some commonly used functions to manipulate strings.

    The PHP strlen() functionThe strlen() function returns the length of a string, in characters.

    The example below returns the length of the string "Hello world!":

    Example

    http://www.w3schools.com/php/showphp.asp?filename=demo_datatypes_objecthttp://www.w3schools.com/php/showphp.asp?filename=demo_datatypes_object
  • 7/27/2019 Introduction to PHP (w3school)

    17/86

    Result:

    12

    The output of the code above will be: 12

    Tip:strlen() is often used in loops or other functions, when it is important to know when a stringends. (i.e. in a loop, we might want to stop the loop after the last character in a string).

    The PHP strpos() function

    The strpos() function is used to search for a specified characteror text within a string.

    If a match is found, it will return the character position of the first match. If no match is found, itwill return FALSE.

    The example below searches for the text "world" in the string "Hello world!":

    Example

    Result:6

    The output of the code above will be: 6.

    Tip:Theposition of the string "world"in the example above is 6. The reason that it is 6 (and not7), is that the first character position in the string is 0, and not 1.

    Complete PHP String Reference

    For a complete reference of all string functions, go to our completePHP String Reference.

    The PHP string reference contains description and example of use, for each function!

    http://www.w3schools.com/php/php_ref_string.asphttp://www.w3schools.com/php/php_ref_string.asphttp://www.w3schools.com/php/php_ref_string.asphttp://www.w3schools.com/php/php_ref_string.asp
  • 7/27/2019 Introduction to PHP (w3school)

    18/86

    PHP Constants

    Constants are like variablesexcept that once they are defined they cannot be changed orundefined.

    PHP Constants

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

    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 ConstantTo set a constant, use the define() function - it takes three parameters: The first parameter definesthe name of the constant, the second parameter defines the value of the constant, and the optionalthird 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 toW3Schools.com!":

    Example

    Result:Welcome to W3Schools.com!greeting

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

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    19/86

    echo greeting;?>

    Result:Welcome to W3Schools.com!

    Welcome to W3Schools.com!

    PHP Operators

    This chapter shows the different operators that can be used in PHP scripts.

    PHP Arithmetic Operators

    Operator Name Example Result

    + Addition $x + $y Sum of $x and $y

    - Subtraction $x - $y Difference of $x and $y

    * Multiplication $x * $y Product of $x and $y

    / Division $x / $y Quotient of $x and $y

    % Modulus $x % $yRemainder of $xdivided by $y

    The example below shows the different results of using the different arithmetic operators:

    Example

    PHP Assignment Operators

    The PHP assignment operators is used to write a value to a variable.

    The basic assignment operator in PHP is "=". It means that the left operand gets set to the valueof the assignment expression on the right.

  • 7/27/2019 Introduction to PHP (w3school)

    20/86

    Assignment Same as... Description

    x = y x = yThe left operand gets set to the value of the expressionon the right

    x += y x = x + y Addition

    x -= y x = x - y Subtraction

    x *= y x = x * y Multiplication

    x /= y x = x / y Division

    x %= y x = x % y Modulus

    The example below shows the different results of using the different assignment operators:

    Example

    PHP String Operators

    Operator Name Example Result

    . Concatenation $txt1 = "Hello" Now $txt2 contains "Hello

  • 7/27/2019 Introduction to PHP (w3school)

    21/86

    $txt2 = $txt1 . "world!"

    world!"

    .=Concatenationassignment

    $txt1 = "Hello"$txt1 .= " world!"

    Now $txt1 contains "Helloworld!"

    The example below shows the results of using the string operators:

    Example

    PHP Increment / Decrement Operators

    Operator Name Description

    ++$x Pre-increment Increments $x by one, then returns $x

    $x++ Post-increment Returns $x, then increments $x by one

    --$x Pre-decrement Decrements $x by one, then returns $x$x-- Post-decrement Returns $x, then decrements $x by one

    The example below shows the different results of using the different increment/decrementoperators:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    22/86

    $i=5;echo $i--; // outputs 5?>

    PHP Comparison Operators

    The PHP comparison operators are used to compare two values (number or string):

    Operator Name Example Result

    == Equal $x == $y True if $x is equal to $y

    === Identical $x === $y True if $x is equal to $y, andthey are of the same type

    != Not equal $x != $y True if $x is not equal to $y

    Not equal $x $y True if $x is not equal to $y

    !== Not identical $x !== $yTrue if $x is not equal to $y, orthey are not of the same type

    > Greater than $x > $y True if $x is greater than $y

    < Less than $x < $y True if $x is less than $y

    >= Greater than or equal to $x >= $yTrue if $x is greater than or equalto $y

  • 7/27/2019 Introduction to PHP (w3school)

    23/86

    Result:

    bool(true)

    bool(false)

    bool(false)

    bool(true)

    bool(false)

    bool(true)

    PHP Logical Operators

    Operator Name Example Result

    and And $x and $y True if both $x and $y are true

    or Or $x or $y True if either $x or $y is true

    xor Xor $x xor $yTrue if either $x or $y is true, butnot both

    && And $x && $y True if both $x and $y are true

    || Or $x || $y True if either $x or $y is true! Not !$x True if $x is not true

    PHP Array Operators

    The PHP array operators are used to compare arrays:

  • 7/27/2019 Introduction to PHP (w3school)

    24/86

    Operator Name Example Result

    + Union $x + $yUnion of $x and $y (butduplicate keys are notoverwritten)

    == Equality $x == $yTrue if $x and $y have the samekey/value pairs

    === Identity $x === $yTrue if $x and $y have the samekey/value pairs in the same orderand of the same types

    != Inequality $x != $y True if $x is not equal to $y

    Inequality $x $y True if $x is not equal to $y

    !== Non-identity $x !== $y True if $x is not identical to $y

    The example below shows the different results of using the different array operators:

    Example

    Result:

    array(4) { ["a"]=> string(3) "red" ["b"]=> string(5) "green" ["c"]=> string(4) "blue" ["d"]=>

    string(6) "yellow" }

    bool(false)

    bool(false)

    bool(true)

    bool(true)

    bool(true)

  • 7/27/2019 Introduction to PHP (w3school)

    25/86

    PHP if...else...elseif Statements

    Previous

    Next Chapter

    Conditional statements are used to perform different actions based on different conditions.

    PHP Conditional Statements

    Very often when you write code, you want to perform different actions for different decisions.

    You can use conditional statements in your code to do this.

    In PHP we have the following conditional statements:

    if statement- executes some code only if a specified condition is true

    if...else statement- executes some code if a condition is true and another code if the condition

    is false

    if...elseif....else statement- selects one of several blocks of code to be executed

    switch statement- selects one of many blocks of code to be executed

    PHP - The if Statement

    The if statement is used to execute some code only if a specified condition is true.

    Syntax

    if (condition)

    {

    code to be executed if condition is true;

    }

    The example below will output "Have a good day!" if the current time (HOUR) is less than 20:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    26/86

    if ($t

    Result:

    Have a good day!

    PHP - The if...else Statement

    Use the if....else statement to execute some code if a condition is true and another code if thecondition is false.

    Syntax

    if (condition)

    {

    code to be executed if condition is true;

    }

    else

    {

    code to be executed if condition is false;

    }

    Result:

    Have a good day!

    The example below will output "Have a good day!" if the current time is less than 20, and "Havea good night!" otherwise:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    27/86

    }

    else

    {

    echo "Have a good night!";

    }

    ?>

    Run example

    PHP - The if...elseif....else Statement

    Use the if....elseif...else statement to select one of several blocks of code to be executed.

    Syntax

    if (condition)

    {

    code to be executed if condition is true;

    }

    elseif (condition)

    {

    code to be executed if condition is true;

    }

    else

    {

    code to be executed if condition is false;

    }

    The example below will output "Have a good morning!" if the current time is less than 10, and"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a goodnight!":

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    28/86

    }

    elseif ($t

    PHP switch Statement

    Previous

    Next Chapter

    The switch statement is used to perform different actions based on different conditions.

    The PHP switch Statement

    Use the switch statement to select one of many blocks of code to be executed.

    http://www.w3schools.com/php/php_if_else.asphttp://www.w3schools.com/php/php_if_else.asphttp://www.w3schools.com/php/php_looping.asphttp://www.w3schools.com/php/php_looping.asphttp://www.w3schools.com/php/php_looping.asphttp://www.w3schools.com/php/php_if_else.asp
  • 7/27/2019 Introduction to PHP (w3school)

    29/86

    Syntax

    switch (n)

    {

    case label1:

    code to be executed if n=label1;

    break;

    case label2:

    code to be executed if n=label2;

    break;

    case label3:

    code to be executed if n=label3;

    break;

    ...

    default:

    code to be executed if n is different from all labels;

    }

    This is how it works: First we have a single expression n(most often a variable), that isevaluated once. The value of the expression is then compared with the values for each case in thestructure. If there is a match, the block of code associated with that case is executed. Use breakto prevent the code from running into the next case automatically. The defaultstatement is usedif no match is found.

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    30/86

    default:

    echo "Your favorite color is neither red, blue, or green!";

    }

    ?>

    Result:

    Your favorite color is red!

    PHP while Loops

    PHP while loops execute a block of code while the specified condition is true.

    PHP Loops

    Often when you write code, you want the same block of code to run over and over again in arow. Instead of adding several almost equal code-lines in a script, we can use loops to perform atask like this.

    In PHP, we have the following looping statements:

    while - loops through a block of code as long as the specified condition is true

    do...while- loops through a block of code once, and then repeats the loop as long as thespecified condition is true

    for - loops through a block of code a specified number of times

    foreach - loops through a block of code for each element in an array

    The PHP while Loop

    The while loop executes a block of code as long as the specified condition is true.

    Syntax

    while (condition is true)

    {

    code to be executed;

    }

  • 7/27/2019 Introduction to PHP (w3school)

    31/86

    The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to runas long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):

    Example

    Result:

    The number is: 1

    The number is: 2

    The number is: 3

    The number is: 4

    The number is: 5

    The PHP do...while Loop

    The do...while loop will always execute the block of code once, it will then check the condition,and repeat the loop while the specified condition is true.

    Syntax

    do{

    code to be executed;

    }

    while (condition is true);

  • 7/27/2019 Introduction to PHP (w3school)

    32/86

    The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write someoutput, and then increment the variable $x with 1. Then the condition is checked (is $x less than,or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

    Example

    Result:

    The number is: 1

    The number is: 2

    The number is: 3

    The number is: 4

    The number is: 5

    Notice that in a do while loop the condition is tested AFTER executing the statements within the loop.

    This means that the do while loop would execute its statements at least once, even if the condition fails

    the first time.

    The example below sets the $x variable to 6, then it runs the loop, and then the condition ischecked:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    33/86

    Result:

    The number is: 6

    PHP for Loops

    PHP for loops execute a block of code a specified number of times.

    The PHP for Loop

    The for loop is used when you know in advance how many times the script should run.

    Syntax

    for (init counter; test counter; increment counter)

    {

    code to be executed;

    }

    Parameters:

    init counter: Initialize the loop counter value

    test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it

    evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value

    The example below displays the numbers from 0 to 10:

    Example

    Result:

    The number is: 0

    The number is: 1

  • 7/27/2019 Introduction to PHP (w3school)

    34/86

    The number is: 2

    The number is: 3

    The number is: 4

    The number is: 5

    The number is: 6

    The number is: 7

    The number is: 8

    The number is: 9

    The number is: 10

    The PHP foreach Loop

    The foreach loop works only on arrays, and is used to loop through each key/value pair in an

    array.

    Syntax

    foreach ($array as$value)

    {

    code to be executed;

    }

    For every loop iteration, the value of the current array element is assigned to $value and the arraypointer is moved by one, until it reaches the last array element.

    The following example demonstrates a loop that will output the values of the given array($colors):

    Example

    Result:

  • 7/27/2019 Introduction to PHP (w3school)

    35/86

    red

    green

    blue

    yellow

    PHP Functions

    The real power of PHP comes from its functions; it has more than 1000 built-in functions.

    PHP User Defined Functions

    Besides the built-in PHP functions, we can create our own functions.

    A function is a block of statements that can be used repeatedly in a program.

    A function will not execute immediately when a page loads.

    A function will be executed by a call to the function.

    Create a User Defined Function in PHP

    A user defined function declaration starts with the word "function":

    Syntax

    functionfunctionName()

    {

    code to be executed;

    }

    Note:A function name can start with a letter or underscore (not a number).

  • 7/27/2019 Introduction to PHP (w3school)

    36/86

    Tip:Give the function a name that reflects what the function does!

    Remember that function names are case-insensitive.

    In the example below, we create a function named "writeMsg()". The opening curly brace ( { )indicates the beginning of the function code and the closing curly brace ( } ) indicates the end ofthe function. The function outputs "Hello world!". To call the function, just write its name:

    Example

    Result:

    Hello world!

    PHP Function Arguments

    Information can be passed to functions through arguments. An argument is just like a variable.

    Arguments are specified after the function name, inside the parentheses. You can add as manyarguments as you want, just seperate them with a comma.

    The following example has a function with one argument ($fname). When the familyName()function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,which outputs several different first names, but an equal last name:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    37/86

    familyName("Jani");

    familyName("Hege");

    familyName("Stale");

    familyName("Kai Jim");

    familyName("Borge");

    ?>

    Result:

    Jani Refsnes.

    Hege Refsnes.

    Stale Refsnes.

    Kai Jim Refsnes.

    Borge Refsnes.

    The following example has a function with two arguments ($fname and $year):

    Example

    Result:

    Hege Refsnes. Born in 1975

    Stale Refsnes. Born in 1978

    Kai Jim Refsnes. Born in 1983

    PHP Default Argument Value

    The following example shows how to use a default parameter. If we call the function setHeight()without arguments it takes the default value as argument:

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    38/86

    Result:

    The height is : 350

    The height is : 50

    The height is : 135The height is : 80

    PHP Functions - Returning values

    To let a function return a value, use the return statement:

    Example

    Result:

    5 + 10 = 15

    7 + 13 = 20

    2 + 4 = 6

  • 7/27/2019 Introduction to PHP (w3school)

    39/86

    PHP Arrays

    An array stores multiple values in one single variable:

    Example

    Result:

    I like Volvo, BMW and Toyota.

    What is an Array?

    An array is a special variable, which can hold more than one value at a time.

    If you have a list of items (a list of car names, for example), storing the cars in single variablescould look like this:

    $cars1="Volvo";$cars2="BMW";$cars3="Toyota";

    However, what if you want to loop through the cars and find a specific one? And what if you hadnot 3 cars, but 300?

    The solution is to create an array!

    An array can hold many values under a single name, and you can access the values by referringto an index number.

    Create an Array in PHP

  • 7/27/2019 Introduction to PHP (w3school)

    40/86

    In PHP, the array() function is used to create an array:

    array();

    In PHP, there are three types of arrays:

    Indexed arrays- Arrays with numeric index Associative arrays- Arrays with named keys Multidimensional arrays- Arrays containing one or more arrays

    PHP Indexed Arrays

    There are two ways to create indexed arrays:

    The index can be assigned automatically (index always starts at 0):

    $cars=array("Volvo","BMW","Toyota");

    or the index can be assigned manually:

    $cars[0]="Volvo";$cars[1]="BMW";$cars[2]="Toyota";

    The following example creates an indexed array named $cars, assigns three elements to it, and

    then prints a text containing the array values:

    Example

    Run example

    Get The Length of an Array - The count() Function

    The count() function is used to return the length (the number of elements) of an array:

    http://www.w3schools.com/php/showphp.asp?filename=demo_array_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_num
  • 7/27/2019 Introduction to PHP (w3school)

    41/86

    Example

    Run example

    Loop Through an Indexed Array

    To loop through and print all the values of an indexed array, you could use a for loop, like this:

    Example

    Run example

    PHP Associative Arrays

    Associative arrays are arrays that use named keys that you assign to them.

    There are two ways to create an associative array:

    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

    or:

    http://www.w3schools.com/php/showphp.asp?filename=demo_array_lengthhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_lengthhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_num_loophttp://www.w3schools.com/php/showphp.asp?filename=demo_array_num_loophttp://www.w3schools.com/php/showphp.asp?filename=demo_array_num_loophttp://www.w3schools.com/php/showphp.asp?filename=demo_array_length
  • 7/27/2019 Introduction to PHP (w3school)

    42/86

    $age['Peter']="35";$age['Ben']="37";$age['Joe']="43";

    The named keys can then be used in a script:

    Example

    Result:

    Peter is 35 years old.

    Loop Through an Associative Array

    To loop through and print all the values of an associative array, you could use a foreach loop,like this:

    Example

    Result:

    Key=Peter, Value=35

    Key=Ben, Value=37

    Key=Joe, Value=43

    Multidimensional Arrays

    Multidimensional arrayswill be explained in the PHP advanced section.

    http://www.w3schools.com/php/php_arrays_multi.asphttp://www.w3schools.com/php/php_arrays_multi.asphttp://www.w3schools.com/php/php_arrays_multi.asp
  • 7/27/2019 Introduction to PHP (w3school)

    43/86

    Complete PHP Array Reference

    For a complete reference of all array functions, go to our completePHP Array Reference.

    The reference contains a brief description, and examples of use, for each function!

    PHP Sorting Arrays

    The elements in an array can be sorted in alphabetical or numerical order, descending orascending.

    PHP - Sort Functions For Arrays

    In this chapter, we will go through the following PHP array sort functions:

    sort() - sort arrays in ascending order rsort() - sort arrays in descending order asort() - sort associative arrays in ascending order, according to the value

    ksort() - sort associative arrays in ascending order, according to the key arsort() - sort associative arrays in descending order, according to the value krsort() - sort associative arrays in descending order, according to the key

    Sort Array in Ascending Order - sort()

    The following example sorts the elements of the $cars array in ascending alphabetical order:

    Example

    Result:

    http://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_array.asp
  • 7/27/2019 Introduction to PHP (w3school)

    44/86

    BMW

    Toyota

    Volvo

    The following example sorts the elements of the $numbers array in ascending numerical order:

    Example

    Run example

    Sort Array in Descending Order - rsort()

    The following example sorts the elements of the $cars array in descending alphabetical order:

    Example

    Run example

    The following example sorts the elements of the $numbers array in descending numerical order:

    Example

    Run example

    Sort Array in Ascending Order, According to Value - asort()

    http://www.w3schools.com/php/showphp.asp?filename=demo_array_sort_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_sort_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_rsort_alphahttp://www.w3schools.com/php/showphp.asp?filename=demo_array_rsort_alphahttp://www.w3schools.com/php/showphp.asp?filename=demo_array_rsort_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_rsort_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_rsort_numhttp://www.w3schools.com/php/showphp.asp?filename=demo_array_rsort_alphahttp://www.w3schools.com/php/showphp.asp?filename=demo_array_sort_num
  • 7/27/2019 Introduction to PHP (w3school)

    45/86

    The following example sorts an associative array in ascending order, according to the value:

    Example

    Run example

    Sort Array in Ascending Order, According to Key - ksort()

    The following example sorts an associative array in ascending order, according to the key:

    Example

    Run example

    Sort Array in Descending Order, According to Value -

    arsort()

    The following example sorts an associative array in descending order, according to the value:

    Example

    Run example

    http://www.w3schools.com/php/showphp.asp?filename=demo_array_asorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_asorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_ksorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_ksorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_arsorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_arsorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_arsorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_ksorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_asort
  • 7/27/2019 Introduction to PHP (w3school)

    46/86

    Sort Array in Descending Order, According to Key - krsort()

    The following example sorts an associative array in descending order, according to the key:

    Example

    Run example

    Complete PHP Array Reference

    For a complete reference of all array functions, go to our completePHP Array Reference.

    The reference contains a brief description, and examples of use, for each function!

    PHP Global Variables - Superglobals

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

    PHP Global Variables - Superglobals

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

    http://www.w3schools.com/php/showphp.asp?filename=demo_array_krsorthttp://www.w3schools.com/php/showphp.asp?filename=demo_array_krsorthttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/showphp.asp?filename=demo_array_krsort
  • 7/27/2019 Introduction to PHP (w3school)

    47/86

    The PHP superglobal variables are:

    $GLOBALS $_SERVER $_REQUEST

    $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION

    This chapter will explain some of the superglobals, and the rest will be explained in laterchapters.

    PHP $GLOBAL

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

    PHP stores all global variables in an array called $GLOBALS[index]. The indexholds the nameof the variable.

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

    Example

    Result:

    100

  • 7/27/2019 Introduction to PHP (w3school)

    48/86

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

    PHP $_SERVER

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

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

    Example

    Result:

    /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.1; rv:13.0) Gecko/20100101 Firefox/13.0.1

    /php/demo_global_server.php

    The following table lists the most important elements that can go inside $_SERVER:

    Element/Code Description

    $_SERVER['PHP_SELF'] Returns the filename of the currently executingscript

    $_SERVER['GATEWAY_INTERFACE']Returns the version of the Common GatewayInterface (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 aswww.w3schools.com)

  • 7/27/2019 Introduction to PHP (w3school)

    49/86

    $_SERVER['SERVER_SOFTWARE']Returns the server identification string (such asApache/2.2.24)

    $_SERVER['SERVER_PROTOCOL']Returns the name and revision of the informationprotocol (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 aquery string

    $_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request

    $_SERVER['HTTP_ACCEPT_CHARSET']Returns the Accept_Charset header from the currentrequest (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 (notreliable because not all user-agents support it)

    $_SERVER['HTTPS']Is the script queried through a secure HTTPprotocol

    $_SERVER['REMOTE_ADDR']Returns the IP address from where the user isviewing the current page

    $_SERVER['REMOTE_HOST']Returns the Host name from where the user isviewing the current page

    $_SERVER['REMOTE_PORT']Returns the port being used on the user's machine tocommunicate with the web server

    $_SERVER['SCRIPT_FILENAME']Returns the absolute pathname of the currentlyexecuting script

    $_SERVER['SERVER_ADMIN']

    Returns the value given to the SERVER_ADMINdirective in the web server configuration file (ifyour script runs on a virtual host, it will be the valuedefined for that virtual host) (such [email protected])

    $_SERVER['SERVER_PORT']Returns the port on the server machine being usedby the web server for communication (such as 80)

    $_SERVER['SERVER_SIGNATURE']Returns the server version and virtual host namewhich are added to server-generated pages

    $_SERVER['PATH_TRANSLATED'] Returns the file system based path to the currentscript

    $_SERVER['SCRIPT_NAME'] Returns the path of the current script

    $_SERVER['SCRIPT_URI'] Returns the URI of the current page

  • 7/27/2019 Introduction to PHP (w3school)

    50/86

    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 attributeof the tag. In this example, we point to this file itself for processing form data. If youwish 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:

    Example

    Run example

    PHP $_POST

    PHP $_POST is widely used to collect form data after submitting an HTML form withmethod="post". $_POST is also widely used to pass variables.

    The example below shows a form with an input field and a submit button. When a user submitsthe data by clicking on "Submit", the form data is sent to the file specified in the action attributeof the tag. In this example, we point to this file itself for processing form data. If youwish 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 $_POST to collect the value of the input field:

    Example

    http://www.w3schools.com/php/showphp.asp?filename=demo_global_requesthttp://www.w3schools.com/php/showphp.asp?filename=demo_global_requesthttp://www.w3schools.com/php/showphp.asp?filename=demo_global_request
  • 7/27/2019 Introduction to PHP (w3school)

    51/86

    Run example

    PHP $_GET

    PHP $_GET can also be used to collect form data after submitting an HTML form withmethod="get".

    $_GET can also collect data sent in the URL.

    Assume we have an HTML page that contains a hyperlink with parameters:

    Test $GET

    When a user clicks on the link "Test $GET", the parameters "subject" and "web" is sent to

    "test_get.php", and you can then acces their values in "test_get.php" with $_GET.

    The example below shows the code in "test_get.php":

    Example

    http://www.w3schools.com/php/showphp.asp?filename=demo_global_posthttp://www.w3schools.com/php/showphp.asp?filename=demo_global_posthttp://www.w3schools.com/php/showphp.asp?filename=demo_global_post
  • 7/27/2019 Introduction to PHP (w3school)

    52/86

    Run example

    Tip:You will learn more about $_POST and $_GET in thePHP Formschapter.

    PHP Multidimensional Arrays

    Earlier in this tutorial, we have described arrays that are a single list of key/value pairs.

    However, sometimes you want to store values with more than one key.

    This can be stored in multidimensional arrays.

    PHP - Multidimensional Arrays

    A multidimensional array is an array containing one or more arrays.

    PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.However, arrays more than three levels deep are hard to manage for most people.

    The dimension of an array indicates the number of indices you need to select an element.

    For a two-dimensional array you need two indices to select an element

    For a three-dimensional array you need three indices to select an element

    http://www.w3schools.com/php/showphp.asp?filename=demo_global_gethttp://www.w3schools.com/php/showphp.asp?filename=demo_global_gethttp://www.w3schools.com/php/php_forms.asphttp://www.w3schools.com/php/php_forms.asphttp://www.w3schools.com/php/php_forms.asphttp://www.w3schools.com/php/php_forms.asphttp://www.w3schools.com/php/showphp.asp?filename=demo_global_get
  • 7/27/2019 Introduction to PHP (w3school)

    53/86

    PHP - Two-dimensional Arrays

    A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays ofarrays).

    First, take a look at the following table:

    Name StockSold

    Volvo 22 18

    BMW 15 13

    Saab 5 2

    Land Rover17 15

    We can store the data from the table above in a two-dimensional array, like this:

    $cars = array

    (

    array("Volvo",22,18),

    array("BMW",15,13),

    array("Saab",5,2),

    array("Land Rover",17,15)

    );

    Now the two-dimensional $cars array contains four arrays, and it has two indices: row andcolumn.

    To get access to the elements of the $cars array we must point to the two indices (row andcolumn):

    Example

  • 7/27/2019 Introduction to PHP (w3school)

    54/86

    Volvo: In stock: 22, sold: 18.

    BMW: In stock: 15, sold: 13.

    Saab: In stock: 5, sold: 2.

    Land Rover: In stock: 17, sold: 15.

    We can also put a For loop inside another For loop to get the elements of the $cars array (we still have

    to point to the two indices):

    Example

    Row number 0

    Volvo

    22 18

    Row number 1

    BMW 15 13

  • 7/27/2019 Introduction to PHP (w3school)

    55/86

    Row number 2

    Saab 5 2

    Row number 3

    Land Rover 17 15

    PHP Date() Function

    Previous

    Next Chapter

    The PHP date() function is used to format a time and/or date.

    The PHP Date() Function

    The PHP date() function formats a timestamp to a more readable date and time.

    A timestamp is a sequence of characters, denoting the date and/or time at which a certain event

    occurred.

    Syntax

    date(format,timestamp)

    http://www.w3schools.com/php/php_arrays_multi.asphttp://www.w3schools.com/php/php_arrays_multi.asphttp://www.w3schools.com/php/php_includes.asphttp://www.w3schools.com/php/php_includes.asphttp://www.w3schools.com/php/php_includes.asphttp://www.w3schools.com/php/php_arrays_multi.asp
  • 7/27/2019 Introduction to PHP (w3school)

    56/86

    Parameter Description

    format Required. Specifies the format of the timestamp

    timestamp Optional. Specifies a timestamp. Default is the current date and time

    PHP Date() - Format the Date

    The requiredformatparameter in the date() function specifies how to format the date/time.

    Here are some characters that can be used:

    d - Represents the day of the month (01 to 31)

    m - Represents a month (01 to 12)

    Y - Represents a year (in four digits)

    A list of all the characters that can be used in theformatparameter, can be found in our PHPDate reference,date() function.

    Other characters, like"/", ".", or "-" can also be inserted between the letters to add additionalformatting:

    The output of the code above could be something like this:

    2009/05/11

    2009.05.11

    2009-05-11

    PHP Date() - Adding a Timestamp

    http://www.w3schools.com/php/func_date_date.asphttp://www.w3schools.com/php/func_date_date.asphttp://www.w3schools.com/php/func_date_date.asphttp://www.w3schools.com/php/func_date_date.asp
  • 7/27/2019 Introduction to PHP (w3school)

    57/86

    The optional timestampparameter in the date() function specifies a timestamp. If you do notspecify a timestamp, the current date and time will be used.

    The mktime() function returns the Unix timestamp for a date.

    The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 197000:00:00 GMT) and the time specified.

    Syntax for mktime()

    mktime(hour,minute,second,month,day,year,is_dst)

    To go one day in the future we simply add one to the day argument of mktime():

    The output of the code above could be something like this:

    Tomorrow is 2009/05/12

    Complete PHP Date ReferenceFor a complete reference of all date functions, go to ourcomplete PHP Date Reference.

    The reference contains a brief description, and examples of use, for each function!

    PHP Include Files

    Previous

    Next Chapter

    http://www.w3schools.com/php/php_ref_date.asphttp://www.w3schools.com/php/php_ref_date.asphttp://www.w3schools.com/php/php_ref_date.asphttp://www.w3schools.com/php/php_date.asphttp://www.w3schools.com/php/php_date.asphttp://www.w3schools.com/php/php_file.asphttp://www.w3schools.com/php/php_file.asphttp://www.w3schools.com/php/php_file.asphttp://www.w3schools.com/php/php_date.asphttp://www.w3schools.com/php/php_ref_date.asp
  • 7/27/2019 Introduction to PHP (w3school)

    58/86

    PHP include and require Statements

    In PHP, you can insert the content of one PHP file into another PHP file before the serverexecutes it.

    The include and require statements are used to insert useful codes written in other files, in theflow of execution.

    Include and require are identical, except upon failure:

    require will produce a fatal error (E_COMPILE_ERROR) and stop the script

    include will only produce a warning (E_WARNING) and the script will continue

    So, if you want the execution to go on and show users the output, even if the include file ismissing, use include. Otherwise, in case of FrameWork, CMS or a complex PHP applicationcoding, always use require to include a key file to the flow of execution. This will help avoid

    compromising your application's security and integrity, just in-case one key file is accidentallymissing.

    Including files saves a lot of work. This means that you can create a standard header, footer, ormenu file for all your web pages. Then, when the header needs to be updated, you can onlyupdate the header include file.

    Syntax

    include 'filename';

    or

    require 'filename';

    PHP include and require Statement

    Basic Example

    Assume that you have a standard header file, called "header.php". To include the header file in apage, use include/require:

  • 7/27/2019 Introduction to PHP (w3school)

    59/86

    Welcome to my home page!

    Some text.

    Example 2

    Assume we have a standard menu file that should be used on all pages.

    "menu.php":

    echo 'Home

    Tutorials

    References

    Examples

    About Us

    Contact Us';

    All pages in the Web site should include this menu file. Here is how it can be done:

    Welcome to my home page.

    Some text.

    Example 3

    Assume we have an include file with some variables defined ("vars.php"):

  • 7/27/2019 Introduction to PHP (w3school)

    60/86

    $car='BMW';

    ?>

    Then the variables can be used in the calling file:

    Welcome to my home page.

    PHP File Handling

    Previous

    Next Chapter

    The fopen() function is used to open files in PHP.

    Opening a File

    http://www.w3schools.com/php/php_includes.asphttp://www.w3schools.com/php/php_includes.asphttp://www.w3schools.com/php/php_file_upload.asphttp://www.w3schools.com/php/php_file_upload.asphttp://www.w3schools.com/php/php_file_upload.asphttp://www.w3schools.com/php/php_includes.asp
  • 7/27/2019 Introduction to PHP (w3school)

    61/86

    The fopen() function is used to open files in PHP.

    The first parameter of this function contains the name of the file to be opened and the secondparameter specifies in which mode the file should be opened:

    The file may be opened in one of the following modes:

    Modes Description

    r Read only. Starts at the beginning of the file

    r+ Read/Write. Starts at the beginning of the file

    wWrite only. Opens and clears the contents of file; or creates a new file if it doesn't

    exist

    w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn'texist

    aAppend. Opens and writes to the end of the file or creates a new file if it doesn't

    exist

    a+ Read/Append. Preserves file content by writing to the end of the file

    x Write only. Creates a new file. Returns FALSE and an error if file already exists

    x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

    Note:If the fopen() function is unable to open the specified file, it returns 0 (false).

  • 7/27/2019 Introduction to PHP (w3school)

    62/86

    Example

    The following example generates a message if the fopen() function is unable to open thespecified file:

    Closing a File

    The fclose() function is used to close an open file:

    Check End-of-file

    The feof() function checks if the "end-of-file" (EOF) has been reached.

    The feof() function is useful for looping through data of unknown length.

    Note:You cannot read from files opened in w, a, and x mode!

    if (feof($file)) echo "End of file";

  • 7/27/2019 Introduction to PHP (w3school)

    63/86

    Reading a File Line by Line

    The fgets() function is used to read a single line from a file.

    Note:After a call to this function the file pointer has moved to the next line.

    Example

    The example below reads a file line by line, until the end of file is reached:

    Reading a File Character by Character

    The fgetc() function is used to read a single character from a file.

    Note:After a call to this function the file pointer moves to the next character.

    Example

    The example below reads a file character by character, until the end of file is reached:

  • 7/27/2019 Introduction to PHP (w3school)

    64/86

    fclose($file);

    ?>

    PHP Filesystem Reference

    For a full reference of the PHP filesystem functions, visit ourPHP Filesystem Reference.

    PHP File Upload

    Previous

    Next Chapter

    With PHP, it is possible to upload files to the server.

    Create an Upload-File Form

    To allow users to upload files from a form can be very useful.

    Look at the following HTML form for uploading files:

    Filename:


    http://www.w3schools.com/php/php_ref_filesystem.asphttp://www.w3schools.com/php/php_ref_filesystem.asphttp://www.w3schools.com/php/php_ref_filesystem.asphttp://www.w3schools.com/php/php_file.asphttp://www.w3schools.com/php/php_file.asphttp://www.w3schools.com/php/php_cookies.asphttp://www.w3schools.com/php/php_cookies.asphttp://www.w3schools.com/php/php_cookies.asphttp://www.w3schools.com/php/php_file.asphttp://www.w3schools.com/php/php_ref_filesystem.asp
  • 7/27/2019 Introduction to PHP (w3school)

    65/86

    Notice the following about the HTML form above:

    The enctype attribute of the tag specifies which content-type to use when submitting

    the form. "multipart/form-data" is used when a form requires binary data, like the contents of a

    file, to be uploaded

    The type="file" attribute of the tag specifies that the input should be processed as a file.

    For example, when viewed in a browser, there will be a browse-button next to the input field

    Note:Allowing users to upload files is a big security risk. Only permit trusted users to performfile uploads.

    Create The Upload Script

    The "upload_file.php" file contains the code for uploading a file:

    By using the global PHP $_FILES array you can upload files from a client computer to theremote server.

    The first parameter is the form's input name and the second index can be either "name", "type","size", "tmp_name" or "error". Like this:

    $_FILES["file"]["name"] - the name of the uploaded file

  • 7/27/2019 Introduction to PHP (w3school)

    66/86

    $_FILES["file"]["type"] - the type of the uploaded file

    $_FILES["file"]["size"] - the size in bytes of the uploaded file

    $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server

    $_FILES["file"]["error"] - the error code resulting from the file upload

    This is a very simple way of uploading files. For security reasons, you should add restrictions onwhat the user is allowed to upload.

    Restrictions on Upload

    In this script we add some restrictions to the file upload. The user may upload .gif, .jpeg, and.png files; and the file size must be under 20 kB:

  • 7/27/2019 Introduction to PHP (w3school)

    67/86

    }

    ?>

    Saving the Uploaded File

    The examples above create a temporary copy of the uploaded files in the PHP temp folder on theserver.

    The temporary copied files disappears when the script ends. To store the uploaded file we needto copy it to a different location:

  • 7/27/2019 Introduction to PHP (w3school)

    68/86

    else

    {

    move_uploaded_file($_FILES["file"]["tmp_name"],

    "upload/" . $_FILES["file"]["name"]);

    echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

    }

    }

    }

    else

    {

    echo "Invalid file";

    }

    ?>

    The script above checks if the file already exists, if it does not, it copies the file to a folder called

    "upload".

    PHP Cookies

    Previous

    Next Chapter

    A cookie is often used to identify a user.

    http://www.w3schools.com/php/php_file_upload.asphttp://www.w3schools.com/php/php_file_upload.asphttp://www.w3schools.com/php/php_sessions.asphttp://www.w3schools.com/php/php_sessions.asphttp://www.w3schools.com/php/php_sessions.asphttp://www.w3schools.com/php/php_file_upload.asp
  • 7/27/2019 Introduction to PHP (w3school)

    69/86

    What is a Cookie?

    A cookie is often used to identify a user. A cookie is a small file that the server embeds on theuser's computer. Each time the same computer requests a page with a browser, it will send thecookie too. With PHP, you can both create and retrieve cookie values.

    How to Create a Cookie?

    The setcookie() function is used to set a cookie.

    Note:The setcookie() function must appear BEFORE the tag.

    Syntax

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

    Example 1

    In the example below, we will create a cookie named "user" and assign the value "Alex Porter"to it. We also specify that the cookie should expire after one hour:

    .....

    Note: The value of the cookie is automatically URLencoded when sending the cookie, andautomatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

    Example 2

    You can also set the expiration time of the cookie in another way. It may be easier than usingseconds.

    .....

  • 7/27/2019 Introduction to PHP (w3school)

    70/86

    In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30days).

    How to Retrieve a Cookie Value?

    The PHP $_COOKIE variable is used to retrieve a cookie value.

    In the example below, we retrieve the value of the cookie named "user" and display it on a page:

    In the following example we use the isset() function to find out if a cookie has been set:

    How to Delete a Cookie?

    When deleting a cookie you should assure that the expiration date is in the past.

    Delete example:

  • 7/27/2019 Introduction to PHP (w3school)

    71/86

    What if a Browser Does NOT Support Cookies?

    If your application deals with browsers that do not support cookies, you will have to use othermethods to pass information from one page to another in your application. One method is to passthe data through forms (forms and user input are described earlier in this tutorial).

    The form below passes the user input to "welcome.php" when the user clicks on the "Submit"

    button:

    Name:

    Age:

    Retrieve the values in the "welcome.php" file like this:

    Welcome .

    You are years old.

  • 7/27/2019 Introduction to PHP (w3school)

    72/86

    PHP Sessions Previous

    Next Chapter

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

    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 theapplication and when you end. But on the internet there is one problem: the web server does notknow 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 andwill be deleted after the user has left the website. If you need a permanent storage you may wantto store the data in a database.

    Sessions work by creating a unique id (UID) for each visitor and store variables based on thisUID. 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 tag:

    http://www.w3schools.com/php/php_cookies.asphttp://www.w3schools.com/php/php_cookies.asphttp://www.w3schools.com/php/php_mail.asphttp://www.w3schools.com/php/php_mail.asphttp://www.w3schools.com/php/php_mail.asphttp://www.w3schools.com/php/php_cookies.asp
  • 7/27/2019 Introduction to PHP (w3school)

    73/86

    The code above will register the user's session with the server, allow you to start saving userinformation, 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:

    Output:

    Pageviews=1

    In the example below, we create a simple page-views counter. The isset() function checks if the"views" variable has already been set. If "views" has been set, we can increment our counter. If"views" doesn't exist, we create a "views" variable, and set it to 1:

  • 7/27/2019 Introduction to PHP (w3school)

    74/86

    $_SESSION['views']=$_SESSION['views']+1;

    else

    $_SESSION['views']=1;

    echo "Views=". $_SESSION['views'];

    ?>

    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:

    You can also completely destroy the session by calling the session_destroy() function:

    Note:session_destroy() will reset your session and you will lose all your stored session data.

    PHP Connect to the MySQL Server

    Previous

    Next Chapter

    Use the PHP mysqli_connect() function to open a new connection to the MySQL server.

    http://www.w3schools.com/php/php_mysql_intro.asphttp://www.w3schools.com/php/php_mysql_intro.asphttp://www.w3schools.com/php/php_mysql_create.asphttp://www.w3schools.com/php/php_mysql_create.asphttp://www.w3schools.com/php/php_mysql_create.asphttp://www.w3schools.com/php/php_mysql_intro.asp
  • 7/27/2019 Introduction to PHP (w3school)

    75/86

    Open a Connection to the MySQL Server

    Before we can access data in a database, we must open a connection to the MySQL server.

    In PHP, this is done with the mysqli_connect() function.

    Syntax

    mysqli_connect(host,username,password,dbname);

    Parameter Description

    host Optional. Either a host name or an IP address

    username Optional. The MySQL user name

    password Optional. The password to log in with

    dbname Optional. The default database to be used when performing queries

    Note:There are more available parameters, but the ones listed above are the most important.

    In the following example we store the connection in a variable ($con) for later use in the script:

    Close a Connection

  • 7/27/2019 Introduction to PHP (w3school)

    76/86

    The connection will be closed automatically when the script ends. To close the connectionbefore, use the mysqli_close() function:

    AJAX Introduction

    Previous

    Next Chapter

    AJAX is about updating parts of a web page, without reloading the whole page.

    What is AJAX?

    AJAX = Asynchronous JavaScript and XML.

    AJAX is a technique for creating fast and dynamic web pages.

    AJAX allows web pages to be updated asynchronously by exchanging small amounts of datawith the server behind the scenes. This means that it is possible to update parts of a web page,without reloading the whole page.

    http://www.w3schools.com/php/php_xml_simplexml.asphttp://www.w3schools.com/php/php_xml_simplexml.asphttp://www.w3schools.com/php/php_ajax_php.asphttp://www.w3schools.com/php/php_ajax_php.asphttp://www.w3schools.com/php/php_ajax_php.asphttp://www.w3schools.com/php/php_xml_simplexml.asp
  • 7/27/2019 Introduction to PHP (w3school)

    77/86

    Classic web pages, (which do not use AJAX) must reload the entire page if the content shouldchange.

    Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

    How AJAX Works

    AJAX is Based on Internet Standards

    AJAX is based on internet standards, and uses a combination of:

    XMLHttpRequest object (to exchange data asynchronously with a server)

    JavaScript/DOM (to display/interact with the information)

    CSS (to style the data)

    XML (often used as the format for transferring data)

    AJAX applications are browser- and platform-independent!

  • 7/27/2019 Introduction to PHP (w3school)

    78/86

    Google Suggest

    AJAX was made popular in 2005 by Google, with Google Suggest.

    Google Suggestis using AJAX to create a very dynamic web interface: When you start typing in

    Google's search box, a JavaScript sends the letters off to a server and the server returns a list ofsuggestions.

    Start Using AJAX Today

    In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, withoutreloading the whole page. The server script will be written in PHP.

    If you want to learn more about AJAX, visit ourAJAX tutorial.

    PHP - AJAX and PHP

    Previous

    Next Chapter

    AJAX is used to create more interactive applications.

    AJAX PHP Example

    The following example will demonstrate how a web page can communicate with a web serverwhile a user type characters in an input field:

    Example

    http://www.google.com/http://www.google.com/http://www.w3schools.com/ajax/default.asphttp://www.w3schools.com/ajax/default.asphttp://www.w3schools.com/ajax/default.asphttp://www.w3schools.com/php/php_ajax_intro.asphttp://www.w3schools.com/php/php_ajax_intro.asphttp://www.w3schools.com/php/php_ajax_database.asphttp://www.w3schools.com/php/php_ajax_database.asphttp://www.w3schools.com/php/php_ajax_database.asphttp://www.w3schools.com/php/php_ajax_intro.asphttp://www.w3schools.com/ajax/default.asphttp://www.google.com/
  • 7/27/2019 Introduction to PHP (w3school)

    79/86

    Start typing a name in the input field below:

    First name:

    Suggestions:

    Example Explained - The HTML Page

    When a user types a character in the input field above, the function "showHint()" is executed.

    The function is triggered by the "onkeyup" event:

    function showHint(str)

    {

    if (str.length==0)

    {

    document.getElementById("txtHint").innerHTML="";

    return;

    }

    var xmlhttp=new XMLHttpRequest();

    xmlhttp.onreadystatechange=function()

    {

    if (xmlhttp.readyState==4 && xmlhttp.status==200)

    {

    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

    }

    }

    xmlhttp.open("GET","gethint.php?q="+str,true);xmlhttp.send();

    }

  • 7/27/2019 Introduction to PHP (w3school)

    80/86

    Start typing a name in the input field below:

    First name:

    Suggestions:

    Source code explanation:

    If the input field is empty (str.length==0), the function clears the content of the txtHintplaceholder and exits the function.

    If the input field is not empty, the showHint() function executes the following:

    Create an XMLHttpRequest object

    Create the function to be executed when the server response is ready

    Send the request off to a file on the server

    Notice that a parameter (q) is added to the URL (with the content of the input field)

    The PHP File

    The page on the server called by the JavaScript above is a PHP file called "gethint.php".

    The source code in "gethint.php" checks an array of names, and returns the correspondingname(s) to the browser:

  • 7/27/2019 Introduction to PHP (w3school)

    81/86

    $a[]="Linda";

    $a[]="Nina";

    $a[]="Ophelia";

    $a[]="Petunia";

    $a[]="Amanda";

    $a[]="Raquel";

    $a[]="Cindy";

    $a[]="Doris";

    $a[]="Eve";

    $a[]="Evita";

    $a[]="Sunniva";

    $a[]="Tove";

    $a[]="Unni";

    $a[]="Violet";

    $a[]="Liza";

    $a[]="Elizabeth";

    $a[]="Ellen";

    $a[]="Wenche";

    $a[]="Vicky";

    // get the q parameter from URL

    $q=$_REQUEST["q"]; $hint="";

    // lookup all hints from array if $q is different from ""

    if ($q !== "")

    { $q=strtolower($q); $len=strlen($q);

    foreach($a as $name)

    { if (stristr($q, substr($name,0,$len)))

    { if ($hint==="")

    { $hint=$name; }

    else

    { $hint .= ", $name"; }

    }

    }

    }

    // Output "no suggestion" if no hint were found

    // or output the correct values

    echo $hint==="" ? "no suggestion" : $hint;

    ?>

  • 7/27/2019 Introduction to PHP (w3school)

    82/86

    PHP - AJAX and MySQL

    Previous

    Next Chapter

    AJAX can be used for interactive communication with a database.

    AJAX Database Example

    The following example will demonstrate how a web page can fetch information from a database

    with AJAX:

    Example

    Person info will be listed here...

    Example Explained - The MySQL Database

    The database table we use in the example above looks like this:

    idFirstNameLastNameAgeHometown Job

    1 Peter Griffin 41 Quahog Brewery

    2 Lois Griffin 40 Newport Piano Teacher

    3 Joseph Swanson 39 Quahog Police Officer

    4 Glenn Quagmire 41 Quahog Pilot

    http://www.w3schools.com/php/php_ajax_php.asphttp://www.w3schools.com/php/php_ajax_php.asphttp://www.w3schools.com/php/php_ajax_xml.asphttp://www.w3schools.com/php/php_ajax_xml.asphttp://www.w3schools.com/php/php_ajax_xml.asphttp://www.w3schools.com/php/php_ajax_php.asp
  • 7/27/2019 Introduction to PHP (w3school)

    83/86

    Example Explained - The HTML Page

    When a user selects a user in the dropdown list above, a function called "showUser()" isexecuted. The function is triggered by the "onchange" event:

    function showUser(str)

    {

    if (str=="")

    {

    document.getElementById("txtHint").innerHTML="";

    return;

    }

    if (window.XMLHttpRequest)

    {// code for IE7+, Firefox, Chrome, Opera, Safari

    xmlhttp=new XMLHttpRequest();

    }

    else

    {// code for IE6, IE5

    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    }

    xmlhttp.onreadystatechange=function()

    {

    if (xmlhttp.readyState==4 && xmlhttp.status==200)

    {

    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

    }

    }

    xmlhttp.open("GET","getuser.php?q="+str,true);

    xmlhttp.send();

    }

    Select a person:

    Peter Griffin

    Lois Griffin

  • 7/27/2019 Introduction to PHP (w3school)

    84/86

    Glenn Quagmire

    Joseph Swanson


    Person info will be listed here.

    The showUser() function does the following:

    Check if a person is selected

    Create an XMLHttpRequest object

    Create the function to be executed when the server response is ready

    Send the request off to a file on the server

    Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

    The PHP File

    The page on the server called by the JavaScript above is a PHP file called "getuser.php".

    The source code in "getuser.php" runs a query against a MySQL database, and returns the resultin an HTML table:

  • 7/27/2019 Introduction to PHP (w3school)

    85/86

    Firstname

    Lastname

    Age

    Hometown

    Job

    ";

    while($row = mysqli_fetch_array($result))

    {

    echo "";

    echo "" . $row['FirstName'] . "";

    echo "" . $row['LastName'] . "";

    echo "" . $row['Age'] . "";

    echo "" . $row['Hometown'] . "";

    echo "" . $row['Job'] . "";

    echo "";

    }

    echo "";

    mysqli_close($con);

    ?>

    Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

    1. PHP opens a connection to a MySQL server

    2.

    The correct person is found3.

    An HTML table is created, filled with data, and sent back to the "txtHint" placeholder

    AJAX Example

    Previous

    Next Chapter

    To understand how AJAX works, we will create a small AJAX application:

    Example

    http://www.w3schools.com/ajax/ajax_intro.asphttp://www.w3schools.com/ajax/ajax_intro.asphttp://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asphttp://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asphttp://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asphttp://www.w3schools.com/ajax/ajax_intro.asp
  • 7/27/2019 Introduction to PHP (w3school)

    86/86

    Let AJAX change this text

    Try it yourself

    AJAX Example Explained

    The AJAX application above contains one div section and one button.

    The div section will be used to display information returned from a server. The button calls afunction named loadXMLDoc(), if it is clicked:

    Let AJAX change this text

    Change Content

    Next, add a tag to the page's head section. The script section contains theloadXMLDoc() function:

    function loadXMLDoc()

    {

    .... AJAX script goes here ...

    }

    http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_firsthttp://www.w3schools.com/ajax/tryit.asp?filename=tryajax_firsthttp://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

Recommended