76
PHP The Basic

PHP

  • Upload
    dinah

  • View
    22

  • Download
    0

Embed Size (px)

DESCRIPTION

PHP. The Basic. Mohammad Al- Samarah. Outline. History of PHP What is PHP? What does PHP code look like? Apache Server. Syntax PHP code . Anatomy of a PHP Script . Data Types. Variables. Constants &Operators. Control Structures. Errors and Error Management. History of PHP. - PowerPoint PPT Presentation

Citation preview

Page 1: PHP

PHPThe Basic

Page 2: PHP

Outline History of PHP

What is PHP?

What does PHP code look like?

Apache Server.

Syntax PHP code .

Anatomy of a PHP Script .

Data Types.

Variables.

Constants &Operators.

Control Structures.

Errors and Error Management .

Page 3: PHP

History of PHPPHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP

usage logging and server-side form generation in Unix.

PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc.

PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans .

PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added.

PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP

Page 4: PHP

What is PHP?• Personal Homepage Tools/Form Interpreter

• PHP is a server-side scripting language a server-side scripting language designed specifically for the Web.

• An open source language

• PHP code can be embedded within an HTML page, which will be executed each time that page is visited.

• Filenames end with .php by convention

Page 5: PHP

What is PHP? (cont’d)

Interpreted language, scripts are parsed at run-time rather than compiled beforehand

Executed on the server-side

Source-code not visible by client

‘View Source’ in browsers does not display the PHP code

Various built-in functions allow for fast development

Compatible with many popular databases

Page 6: PHP

Why PHP ?

Open source / free software Cross platform to develop and deploy and to use Powerful, robust , scalable Web development specific Can be object oriented especially version 5 Large active developer community (20 millions websites Great documentation in many language www.php.net/docs.php

Page 7: PHP

What you need to start using PHP ?

• Installation • You will need

• Web server ( Apache )• PHP ( version 5.3)• Database ( MySQL 5 )• Text editor (Notepad) • Web browser (Firefox )• www.php.net/manual/ en/install.php

Page 8: PHP

What does PHP code look like?

• Structurally similar to C/C++

• Supports procedural and object-oriented paradigm (to some degree)

• All PHP statements end with a semi-colon

• Each PHP script must be enclosed in the reserved PHP tag

<?php …?>

Page 9: PHP

Syntax PHP code

• Standard Style : <?php …… ?>• Short Style: <? … ?>• Script Style: <SCRIPT LANGUAGE=‘php’> </SCRIPT>• ASP Style: <% echo “Hello World!”; %>

Page 10: PHP

Echo• The PHP command ‘echo’ is used to output the

parameters passed to it• The typical usage for this is to send data to the

client’s web-browser• Syntax void echo (string arg1 [, string argn...]) • In practice, arguments are not passed in parentheses

since echo is a language construct rather than an actual function

Page 11: PHP

Echo

<?phpecho “Welcome in PHP Page “;echo “my name is ali “;

?>

Page 12: PHP

Variables in PHP• PHP variables must begin with a “$” sign• Case-sensitive ($Foo != $foo != $fOo)• Global and locally-scoped variables• Global variables can be used anywhere• Local variables restricted to a function or class• Certain variable names reserved by PHP• Form variables ($_POST, $_GET)• Server variables ($_SERVER)• Etc.

Page 13: PHP

Variables in PHP

<?php $name ;?> <?php

$name = “ali” echo $name;?>

Page 14: PHP

Variables

<?php$name = “Mohamed”;$age = 23;Echo “ My name is $name and I am $age

years old”;

?>

Page 15: PHP

Variables <?php $name = “Ali"; // declaration ?> <html> <head> <title>A simple PHP document</title> </head> <body style = "font-size: 2em"> <p> <strong> <!-- print variable name’s value --> Welcome to PHP, <?php print( "$name" ); ?>! </strong> </p> </body> </html>

Page 16: PHP

Variable variables

• That is variable whose name is contained in another variable.

Example :<?php $data = “a";$$data = “b"; echo $a; // echo ${'a'};?>

Page 17: PHP

Single & Double Quotes

<?phpecho “ Hello world <br>”;echo ‘ Hello world’;?>

Page 18: PHP

<?php$word = ‘ World’;echo ‘ Hello’ . $word . ‘<br>’;?>

Single & Double Quotes

Page 19: PHP

General Example

• Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25• Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP • This is true for both variables and character escape-sequences (such as “\

n” or “\\”)

<?php$foo = 25; // Numerical variable$bar = “Hello”; // String variable

echo $bar; // Outputs Helloecho $foo,$bar; // Outputs 25Helloecho “5x5=”,$foo; // Outputs 5x5=25echo “5x5=$foo”; // Outputs 5x5=25echo ‘5x5=$foo’; // Outputs 5x5=$foo?>

Page 20: PHP

Concatenation

• Use a period to join strings into one.

<?php

$string1=“Hello”;$string2=“PHP”;$string3=$string1 . “ ” . $string2;Print $string3;

?>

<?php

$string1=“Hello”;$string2=“PHP”;$string3=$string1 . “ ” . $string2;Print $string3;

?>

Hello PHPHello PHP

Page 21: PHP

Anatomy of a PHP Script

• // or # for single line• /* */ for multiline• /***some info **this is type of comments */

Comments

Page 22: PHP

Anatomy of a PHP Script

• You cant have any whitespace between <? and php.

• You cant break apart keywords (e.g :whi le,func tion,fo r)

• You cant break apart varible names and function names (e.g:$var name,function f 2)

Whitespace

Page 23: PHP

Anatomy of a PHP Script

• Is simply a series of statements' enclosed between two braces :

{//some comand }

Code Block

Page 24: PHP

Math operations<?php

$num1 = 10;$num2 =20;// additionecho $num1+$mum2 . ‘<br>’;//subtraction echo $num1 - $num2 . ‘<br>’; // multiplication

?>

Page 25: PHP

<?php// multiplication echo $num1* $num2 . ‘<br>’;// division echo $num1/num2 . ‘<br>’ ;//increment $num1++;$num2--;echo $num1;

?>

Math operations

Page 26: PHP

Arithmetic

• Arithmetic operators– Assignment operators

• Syntactical shortcuts• Before being assigned values, variables have value undef

• Constants– Named values– define function

Page 27: PHP

Arithmetic Operators

• $a - $b // subtraction• $a * $b // multiplication• $a / $b // division• $a += 5 // $a = $a+5 Also works for *=

and /=

<?php$a=15;$b=30;$total=$a+$b;Print $total;Print “<p><h1>$total</h1>”;// total is 45

?>

<?php$a=15;$b=30;$total=$a+$b;Print $total;Print “<p><h1>$total</h1>”;// total is 45

?>

Page 28: PHP

Arithmetic Operators <?php

$a =1; echo $a++; // output 1,$a is now equal to 2 echo ++$a; // output 3,$a is now equal to 3

echo --$a; // output 2,$a is now equal to 2 echo $a--; // output 2,$a is now equal to 1

?>

Page 29: PHP

Arithmetic Operators

<?php

$a =(int)(‘test’); // $a==0 echo ++$a;

?>

Page 30: PHP

Data type

Data type Description int,

integer Whole numbers (i.e., numbers without a decimal

point). float, double

Real numbers (i.e., numbers containing a decimal point).

string Text enclosed in either single ('') or double ("") quotes.

bool, Boolean

True or false.

array Group of elements of the same type. object Group of associated data and methods.

Resource An external data source. NULL No value.

Fig. 26.2 PHP data types.

Page 31: PHP

Data type<?php

// declare a string, double and integer$testString = "3.5 seconds";$testDouble = 79.2; $testInteger = 12;

print( $testString ).”is a string<br/>”;print( $testDouble ).”is a double<br />”print( $testInteger ).”is an integer<br />”;

?>

Page 32: PHP

Data type<?php // call function settype to convert variable // testString to different data types print( "$testString" ); settype( $testString, "double" ); print( " as a double is $testString <br />" ); print( "$testString" ); settype( $testString, "integer" ); print( " as an integer is $testString <br />" ); settype( $testString, "string" ); print( "Converting back to a string results in $testString <br /><br />" ); ?>

Page 33: PHP

Data type

<?php $data = "98.6 degrees";print( "Now using type casting instead: <br />As a string - " . (string) $data . "<br />As a double - " . (double) $data . "<br />As an integer - " . (integer) $data );?>

Page 34: PHP

Data type

<?php

$a = “ 12.4 abc” echo (int) $a;echo (double) ($a);echo (float) ($a);echo (string) ($a);

?>

Page 35: PHP

Logic Operations Example Name Result

$a == $b Equal TRUE if $a is equal to $b after type juggling.

$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.

$a != $b Not equal TRUE if $a is not equal to $b after type juggling.

$a <> $b Not equal TRUE if $a is not equal to $b after type juggling.

$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type.

$a < $b Less than TRUE if $a is strictly less than $b.

$a > $b Greater than TRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.

$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Page 36: PHP

Bitwise Operations

ExampleExample NameName ResultResult

A & B And Bits that are set in both A and B are set.

A | B Or Bits that are set in either A or B are set.

A ^ B Xor Bits that are set in A or B but not both are set.

~ A Not Bits that are set in A are not set, and vice versa.

A << B Shift leftShift the bits of A B steps to the

left (each step means "multiply by two")

A >> B Shift rightShift the bits of A B steps to the

right (each step means "divide by two")

Page 37: PHP

Example cont..

<?php  $x=13;  $y=22;  echo $x & $y;  

?>  <?php  $x=77;  $y=198;  echo $x & $y;  

?> 

Page 38: PHP

Example cont..<?php

$x=5; $y=11; echo $x | $y;

?><?php  $x=12;  $y=11;  echo $x ^ $y;  

?>

Page 39: PHP

Example cont..<?php

$x=12; $y=10; echo $x & ~ $y;

?> <?php  $x=8;  $y=3;  echo $x << $y;  

?

Page 40: PHP

Example cont..<?php

$x=12; $y=10; echo $x & ~ $y;

?> <?php  $x=8;  $y=3;  echo $x << $y;  

?

Page 41: PHP

Example cont..

<?php $x=12; $y=4; echo $x << $y;

?> <?php

$x=8; $y=3;

echo $x >> $y;

?>

Page 42: PHP

Referencing Operators

• We know the assignment operators work by value ,by

copy the value to other expression ,if the value in right

hand change the value in left is not change .

• Ex:$A =10;

$B =$a;

$B =20

Echo $a; // 10

Page 43: PHP

Referencing Operators

• But we can change the value of variable $a by the

reference , that mena connect right hand to left hand ,

• Ex:

$A =10;

$B = &$a;

$B= 20;

Echo $a; // 20

Page 44: PHP

Constant Value

Page 45: PHP

Escaping the Character

• If the string has a set of double quotation marks that must remain visible, use the \ [backslash] before the quotation marks to ignore and display them.

Page 46: PHP

Escaping the Character

<?php

$heading=“\”Computer Science\””;$heading1=@“Computer Science”;

Print $heading;Print $heading1;

?>

<?php

$heading=“\”Computer Science\””;$heading1=@“Computer Science”;

Print $heading;Print $heading1;

?>

“Computer Science”“Computer Science”

Page 47: PHP

PHP Control Structures

• Control structures: are the structures within a language that

allow us to control the flow of execution through a program

or script.

• Grouped into conditional (branching) structures (e.G. If/else)

and repetition structures (e.G. While loops).

Page 48: PHP

If ... Else...• If (condition)

{Statements;

}Else{

Statement;}

<?php$user = “John”;If($user==“John”){

Print “Hello John.”;}Else{

Print “You are not John.”;}?>

Hello John.

Page 49: PHP

if/else if/else<?php

$foo = 4;

if ($foo == 0) {

echo ‘The variable foo is equal to 0’;

}

else if (($foo > 0) && ($foo <= 5)) {

echo ‘The variable foo is between 1 and 5’;

}

else {

echo ‘The variable foo is equal to ‘.$foo;

}

?>

Page 50: PHP

Example

Page 51: PHP

Example cont..

Page 52: PHP

Example cont..

Page 53: PHP

For Loops

• for ($varible = value ;condition;$value assigment ){

Statements;}

<?php$count=0;for($count = 0;$count <3,$count++){

Print “hello PHP. ”;?>

hello PHP. hello PHP. hello PHP.

Page 54: PHP

Example (break)<?php/* example 1 */

for ($i = 1; $i <= 10; $i++) {    echo $i;}

?>

Page 55: PHP

Example (break)

<?php

for ($i = 1; ; $i++) {    if ($i > 10) {        break;    }    echo $i;}

?>

Page 56: PHP

Example (break)<?php/* example 3 */

$i = 1;for (; ; ) {    if ($i > 10) {        break;    }    echo $i;    $i++;}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);?>

Page 57: PHP

Example (for)

<?php//this is a different way to use the 'for'

for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){        $p = $i + $x;        print "\$i = $i , \$x = $x , \$z = $z <br />";    }

?>

Page 58: PHP

Example – table <?php$brush_price = 5; echo "<table border=\"1\" align=\"center\">"; echo "<tr><th>Quantity</th>"; echo "<th>Price</th></tr>"; for ( $counter = 10; $counter <= 100; $counter += 10) { echo "<tr><td>"; echo $counter; echo "</td><td>"; echo $brush_price * $counter; echo "</td></tr>"; } echo "</table>";?>

Page 59: PHP

Example (nested For)

<?php for($a=0;$a<10;$a++){     for($b=0;$b<10;$b++){           for($c=0;$c<10;$c++){               for($d=0;$d<10;$d++){                 echo $a.$b.$c.$d.", ";               }            }       } } ?> 

Page 60: PHP

Example (continue)

<?phpfor ($i = 0; $i < 5; ++$i) {    if ($i == 2)        continue    print "$i\n";}?>

Page 61: PHP

Example (for..if)<?php

$rows = 4;

echo '<table><tr>';

for($i = 0; $i < 10; $i++){    echo '<td>' . $i . '</td>';    if(($i + 1) % $rows == 0){        echo '</tr><tr>';    }}

echo '</tr></table>';

?>

Page 62: PHP

While Loops

• While (condition){

Statements;}

<?php$count=0;While($count<3){

Print “hello PHP. ”;$count += 1;// $count = $count + 1;// or// $count++;

?>

hello PHP. hello PHP. hello PHP.

Page 63: PHP

Example (while switch)<?php$i = 0;

while (++$i) {    switch ($i) {    case 5:        echo "At 5<br />\n";        break 1;     case 10:        echo "At 10; quitting<br />\n";        break 2;  

    default:        break;    }}?>

Page 64: PHP

Example (nested while)<?php$i = 0;

while ($i++ < 5) {    echo "Outer<br />\n";    while (1) {        echo "&nbsp;Middle<br />\n";        while (1) {            echo "&nbsp;&nbsp;Inner<br />\n";            continue 3;        }        echo "This never gets output.<br />\n";    }    echo "Neither does this.<br />\n";}?>

Page 65: PHP

Do …While Loops

Do{

Statements;

}

While (condition);

<?php$count=0;Do{

Print “hello PHP. ”;$count += 1;

}While($count<3);?>

hello PHP.hello PHP.hello PHP.

Page 66: PHP

Example (do..while)

<?php$i = 0;do {    echo $i;} while ($i > 0);?>

Page 67: PHP

Example (do..while)<?php

do {    if ($i < 5) {        echo "i is not big enough";        break;    }    $i *= $factor;    if ($i < $minimum_limit) {        break;    }   echo "i is ok";

    /* process i */

} while (0);?>

Page 68: PHP

Switch• switch(expression )

{ case value: break;.. default: break; }

<?php$count=0;switch($count){ case 0:

Print “hello PHP3. ”;break;case 1:

Print “hello PHP4. ”;break; default:

Print “hello PHP5. ”;break;

?> hello PHP3

Page 69: PHP

Example <?php

if ($i == 0) {    echo "i equals 0";} elseif ($i == 1) {    echo "i equals 1";} elseif ($i == 2) {    echo "i equals 2";}

switch ($i) {    case 0:        echo "i equals 0";        break;    case 1:        echo "i equals 1";        break;    case 2:        echo "i equals 2";        break;}?>

Page 70: PHP

Example <?php

$total = 0;switch($i) {    case 6:        $total = 99;    break;    case 1:        $total += 1;    case 2:        $total += 2;    case 3:        $total += 3;    case 4:        $total += 4;    case 5:        $total += 5;}?>

Page 71: PHP

Errors & Error Management <?php

// Turn off all error reportingerror_reporting(0);

// Report simple running errorserror_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized// variables or catch variable name misspellings ...)error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE// This is the default value set in php.inierror_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)error_reporting(E_ALL);

// Report all PHP errorserror_reporting(-1);

// Same as error_reporting(E_ALL);ini_set('error_reporting', E_ALL);

?>

Page 72: PHP

Example 1<?php

$name = 'Elijah'; $yearBorn = 1975; $currentYear = 2005;$age = $currentYear - $yearBorn; print ("$name is $age years old.");

?>

Page 73: PHP

Example 2 <?php

phpinfo();?>

<?phpprint("<font face=\"Arial\" color\"#FF0000\">Hello and welcome to my website.</font>");

?>

Page 74: PHP

Example 3

<?php$hour = 11;

print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";

?>

Page 75: PHP

Example 4 (Isset)<?php

     $value = 'Jesus';

     // This is a simple if statement     if( isset( $value ) )     {          print $value;     }

     print '<br />';

     // This is an alternative     isset( $value ) AND print( $value );?>

Page 76: PHP

Example 5 (Goto)<?php

goto a;echo 'Foo'; a:echo 'Bar';?>

<?phpfor($i=0,$j=50; $i<100; $i++) {  while($j--) {    if($j==17) goto end;   }  }echo "i = $i";end:echo 'j hit 17';?>