lecture 3 PHP

Embed Size (px)

Citation preview

  • 8/7/2019 lecture 3 PHP

    1/66

    What is PHPWhat is PHP??

    y PHP stands for PHP: Hypertext Preprocessory PHP is a server-side scripting language, like

    ASP

    y PHP scripts are executed on the servery PHP supports many databases (MySQL,

    Informix, Oracle, Sybase, Solid, PostgreSQL,

    Generic ODBC, etc.)y PHP is an open source software

    y PHP is free to download and use

  • 8/7/2019 lecture 3 PHP

    2/66

    What is a PHP FileWhat is a PHP File??

    y PHP files can contain text, HTML tags and

    scripts

    y PHP files are returned to the browser as

    plain HTML

    y PHP files have a file extension of ".php",".php3", or ".phtml"

  • 8/7/2019 lecture 3 PHP

    3/66

    Why PHP?Why PHP?

    y PHP runs on different platforms

    (Windows, Linux, Unix, etc.)

    y PHP is compatible with almost all servers

    used today (Apache, IIS, etc.)

    y PHP is FREE to download from the officialPHP resource: www.php.net

    y PHP is easy to learn and runs efficientlyon the server side

  • 8/7/2019 lecture 3 PHP

    4/66

    PHPPHP SyntaxSyntax

    y PHP code is executed on the server, and the

    plain HTML result is sent to the browser.

    y

    A PHP scripting block always startswith . A PHP scriptingblock can be placed anywhere in the

    document.

    y On servers with shorthand support enabled

    you can start a scripting block with .

  • 8/7/2019 lecture 3 PHP

    5/66

    ThereThere areare twotwo basicbasic statementsstatements toto outputoutput texttext withwith

    PHPPHP:: echoecho andand printprint.. InIn thethe exampleexample aboveabove wewe havehave usedusedthethe echoecho statementstatement toto outputoutput thethe texttext "Hello"Hello World"World"..

    //hellow

  • 8/7/2019 lecture 3 PHP

    6/66

  • 8/7/2019 lecture 3 PHP

    7/66

    Naming Rules forNaming Rules forVariablesVariables

    y

    A variable name must start with a letter or anunderscore "_"

    y A variable name can only contain alpha-

    numeric characters and underscores (a-z, A-Z,0-9, and _ )

    y A variable name should not contain spaces. If avariable name is more than one word, it

    should be separated with an underscore($my_string), or with capitalization

    ($myString)

  • 8/7/2019 lecture 3 PHP

    8/66

    StringVariables inStringVariables in PHPPHP

    y String variables are used for values thatcontains characters.

    y In this chapter we are going to look at themost common functions and operators usedto manipulate strings in PHP.

    y After we create a string we can manipulateit. A string can be used directly in a functionor it can be stored in a variable.

    y

  • 8/7/2019 lecture 3 PHP

    9/66

    The ConcatenationThe Concatenation OperatorOperator

    y The concatenation operator (.) is used to

    put two string values together.

    y

  • 8/7/2019 lecture 3 PHP

    10/66

    TheThe strlenstrlen()() functionfunction

    y

    y The strpos() function is used to search forcharacter within a string.

    y If a match is found, this function will returnthe position of the first match. If no match isfound, it will return FALSE.

    y

  • 8/7/2019 lecture 3 PHP

    11/66

    PHPPHP OperatorsOperators

    Operator Description Example Result

    + Addition x=2x+2

    4

    - Subtraction x=2

    5-x

    3

    * Multiplication x=4x*5

    20

    / Division 15/55/2

    32.5

    % Modulus (division remainder) 5%210%810%2

    120

    ++ Increment x=5x++

    x=6

    -- Decrement x=5x--

    x=4

  • 8/7/2019 lecture 3 PHP

    12/66

    Assignment operatorsAssignment operators

    Operator Example Is The Same As

    = x=y x=y

    += x+=y x=x+y

    -= x-=y x=x-y

    *= x*=y x=x*y

    /= x/=y x=x/y

    .= x.=y x=x.y

    %= x%=y x=x%y

  • 8/7/2019 lecture 3 PHP

    13/66

    Comparison and logical operatorsComparison and logical operatorsperator Description Example== is equal to 5==8 returns false

    != is not equal 5!=8 returns true

    is not equal 58 returns true

    > is greater than 5>8 returns false

    < is less than 5= is greater than or equal to 5>=8 returns false

  • 8/7/2019 lecture 3 PHP

    14/66

    PHPPHP If...ElseIf...Else StatementsStatements

    y The if Statement

    y if (condition) code to be executed if condition is true;

    y

  • 8/7/2019 lecture 3 PHP

    15/66

    The if...elseThe if...else StatementStatementy

    if (condition)code to be executed if condition is true;elsecode to be executed if condition is false;

    y

  • 8/7/2019 lecture 3 PHP

    16/66

    y

  • 8/7/2019 lecture 3 PHP

    17/66

    TheThe if...if...elseifelseif....else....else StatementStatementy if (condition)

    code to be executed if condition is true;elseif (condition)code to be executed if condition is true;

    elsecode to be executed if condition is false;

    y

  • 8/7/2019 lecture 3 PHP

    18/66

    The PHP SwitchThe PHP Switch StatementStatement

    y switch (n){case label1:code to be executed if n=label1;

    break;case label2:code to be executed if n=label2;break;

    default:code to be executed if n is different from both

    label1 and label2;}

  • 8/7/2019 lecture 3 PHP

    19/66

  • 8/7/2019 lecture 3 PHP

    20/66

    The whileThe while LoopLoopy while (condition)

    {code to be executed;}

    y

  • 8/7/2019 lecture 3 PHP

    21/66

    The do...whileThe do...while StatementStatementy do

    {

    code to be executed;}

    while (condition);

    y

  • 8/7/2019 lecture 3 PHP

    22/66

    The forThe for LoopLoop

    y for (init; condition; increment){code to be executed;}

    y

  • 8/7/2019 lecture 3 PHP

    23/66

    TheThe foreachforeach looploop is used to loop through arrays.is used to loop through arrays.

    y foreach ($arrayas $value){code to be executed;}

    y

  • 8/7/2019 lecture 3 PHP

    24/66

    PHPPHP ArraysArrays

    In PHP, there are three kind of arrays:yNumeric array - An array with a numeric

    index

    y

    Associative

    arr

    ay - An array where each IDkey is associated with a value

    yMultidimensional array - An arraycontaining one or more arrays

  • 8/7/2019 lecture 3 PHP

    25/66

    NumericNumeric ArraysArraysy

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

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

    $cars[3]="Toyota";y

  • 8/7/2019 lecture 3 PHP

    26/66

    AssociativeAssociative ArraysArrays

    y each ID key is associated with a value.

    y $ages = array("Peter"=>32, "Quagmire"=>30,"Joe"=>34);

    y

  • 8/7/2019 lecture 3 PHP

    27/66

    MultidimensionalMultidimensional ArraysArrays

    y $families = array

    ("Griffin"=>array ( "Peter", "Lois","Megan" ),

    "Quagmire"=>array ( "Glenn" ),

    "Brown"=>array ("Cleveland", "Loretta", "Junior"));

    y echo "Is " . $families['Griffin'][2] .

    " a part of the Griffin family?";y Output=Is Megan a part of the Griffin family?

  • 8/7/2019 lecture 3 PHP

    28/66

    PHPPHP FunctionsFunctionsy function functionName()

    {code to be executed;}

    y

  • 8/7/2019 lecture 3 PHP

    29/66

    AddingAdding parametersparameters

    y

  • 8/7/2019 lecture 3 PHP

    30/66

    y

  • 8/7/2019 lecture 3 PHP

    31/66

    PHP FunctionsPHP Functions -- ReturnReturn valuesvalues

    y

  • 8/7/2019 lecture 3 PHP

    32/66

    PHPPHP Forms and UserForms and User InputInputy

    Name: Age:

    y When a user fills out the form above and click on the submit button, theform data is sent to a PHP file, called "welcome.php":

    y

    Welcome !
    You are years old.

  • 8/7/2019 lecture 3 PHP

    33/66

    PHPPHP $_GET$_GET FunctionFunctiony The built-in $_GET function is used to collect values from

    a form sent with method="get".

    y Information sent from a form with the GET method isvisible to everyone (it will be displayed in the browser'saddress bar) and has limits on the amount of informationto send.

    y Whentousemethod="get"?

    y When using method="get" in HTML forms, all variablenames and values are displayed in the URL.

    y Note: This method should not be used when sendingpasswords or other sensitive information!

    y However, because the variables are displayed in the URL, itis possible to bookmark the page. This can be useful insome cases.

    y Note: The get method is not suitable for very largevariable values.

  • 8/7/2019 lecture 3 PHP

    34/66

    PHPPHP $_POST$_POST FunctionFunction

    y The built-in $_POST function is used to collect valuesfrom a form sent with method="post".

    y Information sent from a form with the POST method

    is invisible to others and has no limits on the amountof information to send.

    y Name: Age:

    y Welcome !
    You are years old.

  • 8/7/2019 lecture 3 PHP

    35/66

    When to use method="post"?When to use method="post"?

    y Information sent from a form with the

    POST method is invisible to others and

    has no limits on the amount of

    information to send.y However, because the variables are not

    displayed in the URL, it is not possible to

    bookmark the page.

  • 8/7/2019 lecture 3 PHP

    36/66

    PHP Date FunctionPHP Date Function

    date(format,timestamp)

    y format - Always required. Specifies the format ofthe timestamp

    y timestamp - Optional. Specify UNIX time stamp.

    If not passed, the current timestamp is used.

    Here are some characters that can be used:

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

    y m - Represents a month (01 to 12)

    y Y - Represents a year (in four digits)

  • 8/7/2019 lecture 3 PHP

    37/66

    2010/12/20

    2010.12.202010-12-20

  • 8/7/2019 lecture 3 PHP

    38/66

    Whatis a cookie?Whatis a cookie?

    y A cookie is often used to store data

    which can be used to identify a user, for

    example, person's username.

    y Cookie is a small flat file which sits onusers computer. Each time that user

    requests a page or goes to a webpage, all

    cookie information is sent too. This isused to identify who you are.

  • 8/7/2019 lecture 3 PHP

    39/66

    How to Create a Cookie?How to Create a Cookie?y The setcookie() function is used to set a cookie.

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

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

    y $name - name of the cookie. Example: "username"

    y $value - value of the cookie. Example: "john"

    y $expire - time (in UNIX timestamp) when the cookie will expire. Example:time()+"3600". Cookie is set to expire after one hour.

    y $path - path on the server where cookie will be available.For example, if the path is set to "/", the cookie will be available through out thewhole site. If the cookie is set to say "/news/", the cookie will only be availableunder /news/ and all its sub-directories.

    If no path is given, cookie in created under the current directory.

    y $domain - domain where cookie will be available. Instead of path you can use

    domain settings.For example, if the domian is set to ".yourdomian.com", the cookie will beavailable within the domain nd all its sub-domains, examplenews.yourdomain.com.

    If the cookie is set say "www.yourdomian.com" the cookie will be available underall www sub-domains, example " www.yourdomian.com/news

  • 8/7/2019 lecture 3 PHP

    40/66

    y The PHP $_COOKIE variable is used to retrieve a

    cookie value.y

    y Will print john

  • 8/7/2019 lecture 3 PHP

    41/66

    print the entire $_COOKIE arrayprint the entire $_COOKIE array

    Array ( [username] => john )

  • 8/7/2019 lecture 3 PHP

    42/66

    Deleting a Cookie:Deleting a Cookie:

  • 8/7/2019 lecture 3 PHP

    43/66

    PHP SessionsPHP Sessions

    y Sessions are used to store information which can be usedthrough-out the application for the entire time the user islogged in or running the application. Each time a user visitsyour website, you can create a session for that user to storeinformation pertaining to that user.

    y Unlike other applications, in web applications, all the storedvariables and objects are not globally available throughout allpages (unless sent through POST or GET methods to the nextpage), so to tackle this problem sessions are utilized.

    y A usage of sessions would be for example, storing products in

    a shopping cart. On your favorite merchant site, when you, theuser, clicks on "add to shopping cart", the product informationis then stored in a session (using session variables) which isthen available on the server for later use for the entire thetime you browse the website.

  • 8/7/2019 lecture 3 PHP

    44/66

    y When you start a session a unique session id

    (PHPSESSID) for each visitor/user is created. Youcan access the session id using the PHP predefinedconstant PHPSESSID.

    y The code above starts a session for the user on theserver, and assign a session id for that user'ssession.

  • 8/7/2019 lecture 3 PHP

    45/66

    Storinginformationin a sessionStoringinformationin a session

    Retrievingstoredsessioninformation

  • 8/7/2019 lecture 3 PHP

    46/66

    Destroying/deletingsessioninformationDestroying/deletingsessioninformation

    Remember sessions are destroyed automatically

    after user leaves your website or closes the

    browser, but if you wish to clear a session variable

    yourself, you can simple use the unset() functionto clean the session variable.

    destroy all session

    variables in one go,

  • 8/7/2019 lecture 3 PHP

    47/66

    DifferenceDifference betweenSession and CookiebetweenSession and Cookiey If you set the variable to "cookies", then your users will not

    have to log in each time they enter your community.

    y The cookie will stay in place within the users browser until it isdeleted by the user.

    y But Sessions are popularly used, as there is a chance of yourcookies getting blocked if the user browser security setting is sethigh.

    y If you set the variable to "sessions", then user activity will betracked using browser sessions, and your users will have to log ineach time they re-open their browser. Additionally, if you areusing the "sessions" variable, you need to secure the "sessions"directory, either by placing it above the web root or by

    requesting that your web host make it a non-browsabledirectory.

    y The Key difference would be cookies are stored in your harddisk whereas a session aren't stored in your hard disk. Sessionsare basically like tokens, which are generated at authentication. Asession is available as long as the browser is opened.

  • 8/7/2019 lecture 3 PHP

    48/66

    PHP:MultidimensionalArraysPHP:MultidimensionalArrays

    Title Price Numberrose 1.25 15

    Daisy 0.75 25

    Orchid 1.15 7

  • 8/7/2019 lecture 3 PHP

    49/66

  • 8/7/2019 lecture 3 PHP

    50/66

    ThreeThree--dimensionalArraysdimensionalArraysEach element can be referenced by its layer, row,

    and column.

  • 8/7/2019 lecture 3 PHP

    51/66

    PHPPHP implode()implode() FunctionFunction

    implode(separator,array), returns a string

    from the elements of an array.

  • 8/7/2019 lecture 3 PHP

    52/66

    PHPPHP explode()explode() FunctionFunction

    explode(separator,string,limit), breaks a stringinto an array.

  • 8/7/2019 lecture 3 PHP

    53/66

    PHPPHP File HandlingFile Handling

    howtocreate a file?$ourFileName = "testFile.txt";

    $fileptr = fopen($ourFileName, 'w') or

    exit("Unable to open file!");fclose($fileptr);

  • 8/7/2019 lecture 3 PHP

    54/66

    The file opening modes:The file opening modes:y Modes Description

    y r Read only. Starts at the beginning of the file

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

    y w Write only. Opens and clears the contents of file; orcreates a new file if it doesn't exist

    y w+ Read/Write. Opens and clears the contents of file; or

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

    creates a new file if it doesn't exist

    y a+ Read/Append. Preserves file content by writing to the endof the file

    y

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

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

  • 8/7/2019 lecture 3 PHP

    55/66

    y The feof() function checks if the "end-of-file"

    (EOF) has been reached. Syntax: feof(file)

    y The fgets() function is used to read a single line

    from a file. Syntax : fgets(file,length), length is in

    bytes.y The fgetc() function is used to read a single

    character from a file. Syntax: fgetc(file)

    y

    The file_exists() function checks whether or nota file or directory exists.

    y The filesize() function returns the size of the

    specified file.

  • 8/7/2019 lecture 3 PHP

    56/66

    y The fread() reads from an open file.

    fread(file,length)

    y The fseek() function seeks in an open file.fseek(file,offset,whence)

    y SEEK_SET - Set position equal to offset. Default

    y SEEK_CUR - Set position to current locationplus offset

    y SEEK_END - Set position to EOF plus offset

    y The ftell() function returns the current positionin an open file

    y exit(),and die():Terminates execution of the

    script

  • 8/7/2019 lecture 3 PHP

    57/66

  • 8/7/2019 lecture 3 PHP

    58/66

    y The fwrite() writes to an open file.

    y The function will stop at the end of the file or

    when it reaches the specified length, whichevercomes first.

    y This function returns the number of bytes

    written, or FALSE on failure.y fwrite(file,string,length)

    y The fputs() writes to an open file.

    y fputs(file,string,length)

  • 8/7/2019 lecture 3 PHP

    59/66

    PhpPhp file creationfile creation

  • 8/7/2019 lecture 3 PHP

    60/66

    Read the fileRead the file

    $myFile = "testFile.txt";

    $fh = fopen($myFile, 'r');

    $theData = fread($fh, filesize($myFile));

    fclose($fh);

    echo $theData;

  • 8/7/2019 lecture 3 PHP

    61/66

    Append data inAppend data in phpphp

    $myFile = "testFile.txt";

    $fh = fopen($myFile, 'a') or die("can't open file");

    $stringData = "New Stuff 1\n"; fwrite($fh,

    $stringData);

    $stringData = "New Stuff 2\n"; fwrite($fh,

    $stringData);

    fclose($fh);

  • 8/7/2019 lecture 3 PHP

    62/66

  • 8/7/2019 lecture 3 PHP

    63/66

  • 8/7/2019 lecture 3 PHP

    64/66

  • 8/7/2019 lecture 3 PHP

    65/66

  • 8/7/2019 lecture 3 PHP

    66/66