Download presentation
Presentation is loading. Please wait.
1
Creating php Pages Done By: Hind Talafha
2
What’s php ? PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. PHP programs are written using a text editor, such as Notepad or WordPad, just like HTML pages. Unlike HTML, though, PHP pages, for the most part, end in a (.php) extension. This extension signifies to the server that it needs to parse the PHP code before sending the resulting HTML code to the viewer’s Web browser. 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 can create, open, read, write, delete, and close files on the server PHP can collect form data PHP can add, delete, modify data in your database With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML. Done By: Hind Talafha
3
Basic php syntax The PHP code is enclosed in special start and end processing instructions <? php and ?> which tell PHP to start and stop interpreting the code between them. <?php // PHP code goes here ?> The default file extension for PHP files is ".php". php statements end with a semicolon ; In php, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user- defined functions are NOT case-sensitive. Done By: Hind Talafha
4
Basic php syntax Cont.. // This is a single-line comment.
Comments in php: is a line that is not read/executed as part of the program. Its only purpose is to be read by someone who is looking at the code to understand what you are doing and remind you of what you were thinking when you wrote the code at a later time. Php supports several ways of commenting: // This is a single-line comment. # This is also a single-line comment. /* This is a multiple-lines comment block that spans over multiple lines */ Done By: Hind Talafha
5
Your First php Program Your first php enabled page
Create a file named hello.php <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> "echo" it’s a php built in function to output the text on a web page Done By: Hind Talafha
6
Display Output on Screen
In php there are two basic ways to get output: echo and print. The PHP echo Statement: It is used to send text (or variable values or a variety of other things) to the browser. The PHP print Statement Done By: Hind Talafha
7
What happened when you save the file as .php ?
If you save your previous program with the .html or .htm extension, it will not display the welcome statement, because your HTTP Server (Such as Apache) just passes the contents of the file on to the browser, without processing the php code. But files with the extension .php are handled differently, they are scanned for PHP Code and then interpreted so you can see the welcome statement. That’s about the files Now what about the code ??? When your HTTP server encounters <?php ?> tags, then it is the time to begin processing the code within PHP Script. It executes the PHP Code and sends the scripts output to the browser, when the end of the PHP tag is reached “?>” the web server reverts to HTML Mode and continue sending the HTML tags to the browser . Done By: Hind Talafha
8
Integrating html with php
HTML Mode Client Side scripting Php Mode Server Side scripting HTML Mode Client Side scripting Integrating html with php Done By: Hind Talafha
9
Integrating HTML with PHP
Check for double quotes As noticed in the previous examples using echo statement and HTML attribute values need the double quotes which sometime cause confusion. you can do one of two things to avoid it: Use single quotes inside your HTML. Escape your HTML double quotes with a backslash, as in the following: echo “<font size=\”2\”>”; This is especially useful if you want to display double quotes in your text, such as: echo “He was about 6’5\” tall.”; Done By: Hind Talafha
10
Integrating HTML with PHP Cont..
Don’t try to cram too much HTML into your PHP sections. If you find yourself in the middle of a PHP portion of your program, and your HTML is becoming increasingly complex or lengthy, consider ending the PHP section and coding strictly in HTML. Consider the following example: <?php echo “<table width=’100%’ border=’2’ bgcolor=’#FFFFFF’>”; echo “<tr>”; echo “<td width=’50%’>”; echo “<font face=’Verdana, Arial’ size=’2’>”; echo “First Name:”; echo “</font></td”>; echo “</tr>”; echo “</table>”; ?> Done By: Hind Talafha
11
Integrating HTML with PHP Cont..
Do this instead: <table width=”100%” border=”2” bgcolor=”#FFFFFF”>; <tr> <td width=”50%”> <font face=”Verdana, Arial” size=”2”> First Name: </font> </td> <td> <?php echo $_POST[“fname”]; ?> </td> </tr> </table> Done By: Hind Talafha
12
Php Constants A constant is an identifier for a simple value. The value cannot be modified during the script's execution. A valid constant name starts with a letter or underscore (no dollar($) sign before the name) and by convention constant identifier are always uppercase. Case sensitive names. To create a constant, use the define( ) function. The name of the constant and the value must be placed within the parentheses. Note: Unlike variables, constants are automatically global across the entire script. Done By: Hind Talafha
13
Php Constants Cont.. PHP valid and invalid constant names
Constants are Global Done By: Hind Talafha
14
Php Variables Declaring PHP variables:
Variables are "containers" for storing information. can be changed at some point in the program. do not need to be defined or declared and can simply be assigned when needed. are used for storing values such as numeric values, characters, character strings. Declaring PHP variables: All variables in PHP start with a $ (dollar) sign followed by the name of the variable. A valid variable name starts with a letter (A-Z, a-z) or underscore (_), followed by any number of letters, numbers, or underscores. If a variable name is more than one word, it can be separated with underscore (for example $employee_code instead of $employeecode). Variable name is a case sensitive. Done By: Hind Talafha
15
Php Variables Cont.. Example: Valid and invalid PHP variables
Example: PHP variable name is case-sensitive Done By: Hind Talafha
16
Php Math Functions on Variables
PHP also has numerous built-in mathematical functions that you can use on variables that contain numbers, such as the following: rand([min],[max]) Function: generates a random integer between the lowest number to be returned (Default is 0) and the highest number to be returned. Ceil(number): Round numbers up to the nearest integer. Done By: Hind Talafha Done By: Hind Talafha
17
Php Math Functions on Variables Cont..
Floor(number): Round numbers down to the nearest integer. Min(List of numbers):returns the lowest value of several specified values. Max(List of numbers): returns the highest value of several specified values. Done By: Hind Talafha
18
Done By: Hind Talafha
19
Passing Variables between Pages
$_GET[‘varname’] When the method of passing the variable is the “GET” method in HTML forms. $_POST[‘varname’] When the method of passing the variable is the “POST” method in HTML forms $_REQUEST[‘varname’] When it doesn’t matter ($_REQUEST includes variables passed from any of the above methods) Done By: Hind Talafha
20
Type Juggling PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer. An example of PHP's automatic type conversion is the multiplication operator ‘*'. String Conversion Done By: Hind Talafha
21
Type Juggling Cont.. PHP performs type juggling between the two numeric types. If you perform a numerical operation between integer and double the result will be a double. Done By: Hind Talafha
22
String Conversion A string is series of characters, where a character is the same as a byte If you perform s numerical operation on a string, PHP will evaluate the string as a number. This is known as string conversion ,although the variable containing the String itself my not necessarily change. Done By: Hind Talafha
23
String Conversion Cont..
Only the beginning of the string is evaluated as a number. If the string begins with A valid numerical value, the string will evaluate as that value; otherwise it will Evaluate as zero. The string “33 students” would evaluate as 3 if used in a numerical Operation, but the string “students 33” would evaluate 0 (zero). Done By: Hind Talafha
24
String Conversion Cont..
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits, the string will be evaluated as an integer. In all other cases it will be evaluated as a float. Done By: Hind Talafha
25
Type Casting To force a variable to be evaluated as a certain type (explicitly change the data type of a variable). Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be casted. (int), (integer) - cast to integer (bool), (boolean) - cast to Boolean (float), (double), (real) - cast to float (string) - cast to string Done By: Hind Talafha
26
Variable handling Functions
Gettype( ): Get the type of a variable. Determines the data type of a variable. Syntax: gettype($var) It returns one of the following values. Integer Double String Array Object Class Boolean Null Done By: Hind Talafha
27
Variable handling Functions
Settype( ): Set the type of a variable explicitly. Syntax: settype ($var, type). Possibles values of type are: "boolean" (or, since PHP 4.2.0, "bool") "integer" (or, since PHP 4.2.0, "int") "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double") "string“ "array“ "object“ "null" (since PHP 4.2.0) NOTE: Returns TRUE on success or FALSE on failure. Done By: Hind Talafha
28
Variable handling Functions settype ( )
Done By: Hind Talafha
29
Variable handling Functions
Unset( ): used to destroy a given variable. freeing all the memory that is associated with the variable so it is then available again. Syntax: unset( $var1, $var2, ….). $var1 is required while $var2 and others are optional. Return value: No value is returned. Done By: Hind Talafha
30
Variable handling Functions
isset( ): is used to check whether a variable is set or not. If a variable is already unset with unset() function, it will no longer be set. The isset() function return false if testing variable contains a NULL value. Syntax: isset( $var1, $var2, ….). $var1 is required while $var2 and others are optional. Return value: TRUE if variable (variable1,variable2..) exists and has value not equal to NULL, FALSE otherwise. Value Type : Boolean.. See if statement No value after applying unset Done By: Hind Talafha
31
Done By: Hind Talafha
32
Variable handling Functions
Empty( ): is nearly the opposite of isset( ). It returns true if the variable is not set Or has a value of zero or an empty string. Other wise it returns false. Syntax: empty( $var ). Return value: FALSE if $var has a non-empty and non-zero value. List of empty things : "0" (0 as a string) 0 (0 as an integer) "" (an empty string) NULL FALSE array() (an empty array) $var_name; (a variable declared but without a value in a class) NO output here Done By: Hind Talafha
33
Variable handling Functions
Var_dump( ): is used to display structured information (type and value) about one or more variables. Syntax: var_dump( $var1, $var2, …,$varn). Example: Done By: Hind Talafha
34
Php Arithmetic Operators
There are five basic 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 % $y Remainder of $x divided by $y. Done By: Hind Talafha
35
Php Arithmetic Operators example:
The Minus sign can be used to Negate a number $z= - 4 Done By: Hind Talafha
36
Php Comparison Operators
In PHP, comparison operators take simple values (numbers or strings) as arguments and evaluate to either TRUE or FALSE. Done By: Hind Talafha
37
Php Comparison Operators Example:
Done By: Hind Talafha
38
Php Logical Operators The standard logical operators and, or, not and xor are supported by PHP. Logical operators first convert their operands to boolean values and then perform the respective comparison. Example Name Result $a and $b And TRUE if both $a and $b are TRUE. $a or $b Or TRUE if either $a or $b is TRUE. $a xor $b Xor TRUE if either $a or $b is TRUE, but not both. ! $a Not TRUE if $a is not TRUE. $a && $b $a || $b Done By: Hind Talafha
39
Done By: Hind Talafha
40
String Operator concatenation operator (‘ . ') and concatenating assignment operator (‘ .= '). Done By: Hind Talafha
41
Incrementing/Decrementing Operators
PHP supports C-style pre- and post-increment and decrement operators. Example Name Effect ++$a Pre-increment Increments $a by one, then returns $a. $a++ Post-increment Returns $a, then increments $a by one. --$a Pre-decrement Decrements $a by one, then returns $a. $a-- Post-decrement Returns $a, then decrements $a by one. Done By: Hind Talafha
42
Done By: Hind Talafha
43
Php Assignment Operator
Done By: Hind Talafha
44
Done By: Hind Talafha
45
Php Conditional Statement
Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - executes some code if one condition is true if...else statement - executes some code if a condition is true and another code if that condition is false if...elseif....else statement - executes different codes for more than two conditions switch statement - selects one of many blocks of code to be executed Done By: Hind Talafha
46
Php If Statement The if statement executes some code if one condition is true. Syntax if (condition) { code to be executed if condition is true; } If more one statement is to be executed when the condition is true, curly braces {} Are used to indicate which lines belong inside the if block: Done By: Hind Talafha
47
Php If Statement Cont.. Any Condition which is not met, zero, an empty string (“”), undefined values, and the Built in constant false all evaluate to false Example: If(3<2) If (3>2) Echo “this will not print”; Echo “this will print”; If (false) If (“false”) If(“0”) If(“00”) if($x) if(0==0) Done By: Hind Talafha
48
Php If..else Statement The if....else statement executes some code if a condition is true and another code if that condition is false. Syntax if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } Done By: Hind Talafha
49
Php If..elseif.. else Statement
PHP also provides the elseif keyword to test alternative conditions if the condition. In the if portion of the statement is not true. Any number of elseif statements may be Used with an if statement. The final else branch then allows us to specify code that Should be executed if none of the if or elseif condition is true In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word) Done By: Hind Talafha
50
It is also common to nest if statements within another if statement
It is also common to nest if statements within another if statement. Example: Done By: Hind Talafha
51
Php Switch Statement The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. Syntax: switch (n) { single expression n (most often a variable), that is evaluated once 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; } Done By: Hind Talafha
52
Done By: Hind Talafha
53
Php Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task 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 the specified 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 Done By: Hind Talafha
54
Php While Loops 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; } Done By: Hind Talafha
55
Php Do..While Loops 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); Done By: Hind Talafha
56
Php For Loops 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 Done By: Hind Talafha
57
Done By: Hind Talafha
58
Php Foreach Loops The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. when foreach first starts executing, the internal array pointer is automatically reset to the first element of the 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 array pointer is moved by one, until it reaches the last array element. Done By: Hind Talafha
59
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 function functionName() { code to be executed; } Note: A function name can start with a letter or underscore (not a number). Tip: Give the function a name that reflects what the function does! Function names are NOT case-sensitive. Done By: Hind Talafha
60
Php User Defined Functions
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 many arguments as you want, just separate them with a comma. Done By: Hind Talafha
61
Php User Defined Functions
PHP Default Argument Value PHP Functions - Returning values Done By: Hind Talafha
62
By default, arguments are passed by value
By default, arguments are passed by value. This means that the parameter variable within the function holds a copy of the value passed to it. If the parameter’s value changes, it will not change the value of a variable in the calling statement. Consider the following : When an argument is passed by reference, changes to the parameter variable do Result in changes to the calling statement’s variable, An ampersand (&) is placed before the parameter’s name to indicate that the argument should passed by reference. Done By: Hind Talafha
63
Done By: Hind Talafha
64
PHP Variables Scope In PHP, variables can be declared anywhere in the script. 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: A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function. Global: A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. Static: 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 static keyword when you first declare the variable. Done By: Hind Talafha
65
PHP Variables Scope Global
It will generate an error. We need the global keyword to fix if (before the variables (inside the function) Done By: Hind Talafha
66
Done By: Hind Talafha
67
PHP Variables Scope Local
Note: You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. Done By: Hind Talafha
68
Done By: Hind Talafha
69
PHP Variables Scope Static
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called. Note: The variable is still local to the function. Done By: Hind Talafha
70
PHP Nested Functions All functions in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa. Done By: Hind Talafha
71
When the function has been called once, its child functions will be accessible from that point on. The below example demonstrates how to use functions, that are placed inside other functions. Done By: Hind Talafha
72
PHP Recursive Functions
A recursive function is a function that calls itself. Done By: Hind Talafha
73
PHP Arrays An array stores multiple values in one single variable.
Initializing Arrays: We can create an array without using indices numbers. In this case, the default will be 0,1,2.. Etc. It is usually practical to assign indices in sequential order, as we have done below; but if necessary, we can assign any integer index you please : Done By: Hind Talafha
74
Another way to initialize an array is with array() construct.
Done By: Hind Talafha
75
If we need to know how many elements are in array, we can use the count() function
Done By: Hind Talafha
76
PHP Looping Through an Array
To loop through and print all the values of an indexed array, you could use a for loop, like this: Looping Through an Array ( Non Sequentially Indexed Arrays) Functions. Each( ). Next( ) List( ). Prev( ) Current( ). Key( ). End( ). Done By: Hind Talafha
77
PHP Looping Through an Array Cont..
Each( ): returns the current element key and value, and moves the internal pointer forward. This element key and value is returned in an array with four elements. Two elements (1 and Value) for the element value, and two elements (0 and Key) for the element key. List( ): used to assign values to a list of variables in one operation. Done By: Hind Talafha
78
Done By: Hind Talafha
79
PHP Looping Through an Array Cont..
Key( ): Returns the key of the array element that is currently being pointed to by the internal pointer. Current( ): returns the value of the current element in an array. Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array. Done By: Hind Talafha
80
PHP Looping Through an Array Cont..
Next( ): Returns the value of the next element in the array on success, or FALSE if there are no more elements. Output the value of the current and the next element in the array: Prev( ): Returns the value of the previous element in the array on success, or FALSE if there are no more elements. End( ): Returns the value of the last element in the array on success, or FALSE if the array is empty. Done By: Hind Talafha
81
PHP Looping Through an Array Cont..
Reset( ): Returns the value of the first element in the array on success, or FALSE if the array is empty. Done By: Hind Talafha
82
While (list ($key,$val)= each($fruit) )
For each element in the array, set $key equal to the element’s key (or index), and $value equal to the value of the element, reset() function sets the internal Pointer to the first element. The each() function moves the array pointer one element forward every time it is called. String Indexed Arrays Done By: Hind Talafha
83
Sorting Arrays Functions
Sort( ): sorts an indexed array in ascending order. Done By: Hind Talafha
84
Done By: Hind Talafha
85
Asort( ): sorts an associative array in ascending order, according to the value.
associative array: are arrays that use named keys that you assign to them. They can be defined as the example below. Done By: Hind Talafha
86
rsort( ): sorts an indexed array in descending order.
arsort( ): sorts an associative array in descending order, according to the value. rsort( ): sorts an indexed array in descending order. Done By: Hind Talafha
87
ksort(): sorts an associative array in ascending order, according to the key.
krsort( ): sorts an associative array in descending order, according to the key. Done By: Hind Talafha
88
String manipulation functions
In many applications you will need to do some kind of manipulation or parsing of strings, whether you are attempting to validate user data or extract data from text files, you need to know how to handle strings. PHP String Functions strlen( ): function returns the length of a string. trim( ): function removes whitespace and other predefined characters (spaces, tabs, new lines) from both sides of a string. Related functions ltrim( ): Removes whitespace or other predefined characters from the left side of a string rtrim(): Removes whitespace or other predefined characters from the right side of a string chop( ) function removes whitespaces or other predefined characters from the right end of a string Done By: Hind Talafha
89
Done By: Hind Talafha
90
Done By: Hind Talafha
91
substr( ): returns a part of a string.
Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0. Syntax: substr (string, start, length ) string Required. Specifies the string to return a part of start Required. Specifies where to start in the string A positive number - Start at a specified position in the string A negative number - Start at a specified position from the end of the string 0 - Start at the first character in string length Optional. Specifies the length of the returned string. Default is to the end of the string. A positive number - The length to be returned from the start parameter Negative number - The length to be returned from the end of the string Done By: Hind Talafha
92
Done By: Hind Talafha
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.