Upload
jonah-norris
View
239
Download
2
Tags:
Embed Size (px)
Citation preview
PHPPHP
The Basic PHP
Out line
o History of PHPo What is PHP?o Why PHP ?o What you need to start using PHP ?o What does PHP code look like?o Syntax PHP code .o Echo Statement o Variables.o Anatomy of a PHP Script .o Data Types.o Constants &Operators.o Control Structures.o Errors and Error Management .
History of PHP PHP (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
What is PHP?
Personal Homepage Tools/Form Interpreter
PHP is 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
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
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
What you need to start using php ?
• Installation
• You will need
1. Web server ( Apache )
2. PHP ( version 5.3)
3. Database ( MySQL 5 )
4. Text editor (Notepad)
5. Web browser (Firefox )
6. www.php.net/manual/ en/install.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 …?>
Syntax PHP code• Standard Style :
<?php …… ?>
• Short Style:
<? … ?>
• Script Style:
<SCRIPT LANGUAGE=‘php’> </SCRIPT>
• ASP Style:
<% echo “Hello World!”; %>
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...]) 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
Echo - Example
• <?php
echo “ This my first statement in PHP language“;
• ?>
Variables• 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)
Variables
<?php
$name = “ali”
echo( $name);
?>
Variables
<?php
$name = “Mohamed”;
$age = 23;
Echo “ My name is $name and I am $age years old”;
?>
Variables<?php
$name = 'elijah'; $yearborn = 1975; $currentyear = 2005;$age = $currentyear - $yearborn; echo ("$name is $age years old.");
?>
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 echo( "$name" ); ?>!
</strong> </p>
</body>
</html>
Single & Double Quotes
<?php
echo “ Hello world <br>”;
echo ‘ Hello world’;
?>
<?php
$word = ‘ World’;
echo “ Hello $word <br>”;
echo ‘ Hello $word <br>’;
?>
Single & Double Quotes
Anatomy of a PHP Script
• // or # for single line
• /* */ for multiline
• /*
this is my comment one
this is my comment two
this is my comment three
*/
Comments
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
Anatomy of a PHP Script
• Is simply a series of statements' enclosed between two braces :
{//some comand }
Code Block
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
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.
<?php
$heading=“\”Computer Science\””;
$heading1=@“Computer Science”;
echo $heading;
echo $heading1;
?>
<?php
$heading=“\”Computer Science\””;
$heading1=@“Computer Science”;
echo $heading;
echo $heading1;
?>
“Computer Science”“Computer Science”
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 Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
Data typeData 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.
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 />”;
?>
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 />" );
?>
Data type
<?php
$data = "98.6 degrees";
echo( "Now using type casting instead: <br />As a string - " . (string) $data .
"<br />As a double - " . (double) $data ."<br />As an integer - " . (integer) $data );
?>
Data type
<?php
$a = “ 12.4 abc”
echo (int) $a;
echo (double) ($a);
echo (float) ($a);
echo (string) ($a);
?>
Arithmetic Operations
- Assignment operators• Syntactical shortcuts• Before being assigned values, variables have value undef
- Constants• Named values• define function
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;echo $total;
echo“<p><h1>$total</h1>”;// total is 45
?>
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
?>
Arithmetic Operators
<?php
$a =(int)(‘test’); // $a==0 echo ++$a;
?>
Math operations<?php
$num1 = 10;
$num2 =20;
// addition
echo $num1+$mum2 . ‘<br>’;
//subtraction
echo $num1 - $num2 . ‘<br>’;
// multiplication
?>
<?php
// Multiplication
echo $num1* $num2 . ‘<br>’;
// Division
Echo $num1/num2 . ‘<br>’ ;
//increment
$num1++;
$Num2--;
Echo $num1;
?>
Math operations
Example
Example cont..
Example cont..
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.
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")
Example cont..
<?php $x=13; $y=22; echo $x & $y;
?> <?php
$x=77; $y=198; echo $x & $y;
?>
<?php $x=5; $y=11; echo $x | $y;
?><?php
$x=12; $y=11; echo $x ^ $y;
?>
Example cont..
<?php $x=12; $y=10; echo $x & ~ $y;
?> <?php
$x=8; $y=3; echo $x << $y;
?
Example cont..
<?php $x=12; $y=10; echo $x & ~ $y;
?> <?php
$x=8; $y=3; echo $x << $y;
?
Example cont..
<?php $x=12; $y=4; echo $x << $y;
?> <?php
$x=8; $y=3;
echo $x >> $y; ?>
Example cont..
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:
<?php $a =10;
$b =$a;
$b =20
Echo $a; // 10
?>
Referencing Operators
• But we can change the value of variable $a by the reference ,
that mena connect right hand to left hand ,
• Example:
<?php
$a =10;
$b = &$a;
$b= 20;
echo $a; // 20
?>
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).
If Statement• if (condition)
{statements;
}else{
statement;}
<?php$user = “jone”;if($user==“john”){
print “hello john.”;}else{
print “you are not john.”;}
?>
hello john
if/else if/else statement
<?php
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;
}
?>
Switch Statment
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
Switch - Example<?php
$total = 0;
$i = 2;
switch($i) {
case 6: $total = 99; break;
case 1: $total += 1;break;
case 2:$total += 2;break;
case 3: $total += 3; ;break;
case 4:$total += 4; break;
default : $total += 5;break;
}
echo $total;
?>
For Loop
• 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.
For - Example
<?php
for ($i = 1; $i <= 10; $i++) { echo $i;}
?>
For - Example
<?php
for ($i = 1, $j = 0; $i <= 10; $j += $i, echo $i, $i++);
?>
For-Example<?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>";
?>
While Loopwhile (condition)
{statements;
}
<?php$count=0;while($count<3){
echo “hello PHP. ”;$count += 1;// $count = $count + 1;// or// $count++;
}?>
hello PHP. hello PHP. hello PHP.
While - Example
<?php$i = 0;while ($i++ < 5) {
echo “loop number : “.$i; }
?>
Do ... While Loopdo{
statements;
}while (condition);
<?php$count=0;do{echo “hello PHP. ”;
$count += 1;// $count = $count + 1;// or// $count++;
}while($count<3);?>
hello PHP. hello PHP. hello PHP.
Do..While
<?php$i = 0;do { echo $i;} while ($i > 0);?>
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);
?>
Isset Function
• bool isset ( $var )
• Determine if a variable is set and is not NULL.
• If a variable has been unset with unset(), it will no longer be set. isset() will
return FALSE if testing a variable that has been set to NULL. Also note that
a NULLbyte ("\0") is not equivalent to the PHP NULL constant.
• If multiple parameters are supplied then isset() will return TRUE only if all of
the parameters are set. Evaluation goes from left to right and stops as soon
as an unset variable is encountered.
Isset Function
<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var))
{
echo "This var is set so I will print.";
}
?>
Unset Function
• void unset ( $var)
• unset() destroys the specified variables.
• The behavior of unset() inside of a function can vary depending on what
type of variable you are attempting to destroy.
• If a globalized variable is unset() inside of a function, only the local variable
is destroyed. The variable in the calling environment will retain the same
value as before unset() was called.
unset Function
<?php
$foo = 'bar';
echo $foo;
unset($foo);
echo $foo;
?>
Info PHP Page
<?php
phpinfo();
?>
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>';
?>
For
<?php//this is a different way to use the 'for'//Essa é uma maneira diferente de usar o 'for'for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){ $p = $i + $x; echo "\$i = $i , \$x = $x , \$z = $z <br />"; }
?>
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.", "; } } } } ?>
While - Switch
<?php$i = 0;
while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* Exit the switch and the while. */ default: break; }}?>
Continue
<?phpfor ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$i\n";}?>
If - Switch<?php
$i = 1;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;}?>
Do..While - IF
<?phpdo { 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);?>
If in other style
<?php$hour = 11;
echo $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";
?>
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';?>