Download presentation
Presentation is loading. Please wait.
1
Web Programming– UFCFB3-30-1 PHP Basics Lecture 18
Instructor : Mazhar H Malik Global College of Engineering and Technology
2
What is PHP? What is a PHP File?
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 is free to download and use 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"
3
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 be used to control user-access PHP can encrypt data 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.
4
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. PHP is easy to learn and runs efficiently on the server side PHP program can be run under various Servers like WAMP, XAMPP etc. WAMP Server: this server is a web development platform which helps in creating dynamic web applications. XAMPP Server: It is a free open source cross-platfrom web server package.(in this Module we will use XAMPP ).
5
PHP 5 Syntax A 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 <?php and ends with ?>: The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP scripting code.
6
Run a PHP program in XAMPP Server
Step1 Install XAMPP Step2 Assume you installed xampp in C Drive. Go to: C:\xampp\htdocs Create your own folder, name it for example as GCET. Step3 Now create your first php program in xampp and name it as “Hello.php”: <!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html>
7
Basics of PHP PHP normally operates with PHP mode off - i.e. it treats what it sees as plain text <?php turns PHP mode on - starts executing PHP statements ?> turns it back off again <! DOCTYPE HTML > <html > <head > <title >PHP program </title > </head > <body > <h1 >PHP Example 1</h1 > <?php echo "<p> Hello PHP !!! </p>"; ?> </body > </html >
8
http://writecodeonline.com/php/ Exercise:
Execute the following PHP script online Go to the URL And copy the above script and paste it in the PHP source textbox. Then click Run Code <! DOCTYPE HTML > <html > <head > <title >PHP program </ title > </head > <body > <h1 >PHP Example 1</h1 > <?php echo "<p> Hello PHP !!! </p>"; ?> </body > </html >
10
PHP Comments <?php echo "A string "; # This is a PHP comment /
// This is also a comment / /*And so is this spanning multiple lines*/ echo " More text "; ?>
11
PHP Variable A named location to store data (a container for data)
It can hold only one type of data at a time for example only integers, only floating point (real) numbers, or only characters A variable with a scalar type holds one scalar value A variable with a compound type holds multiple scalar values, BUT the variable still holds only a single (the compound type itself) value Syntax for a variable is $<identifier> Example: $name, $age Case sensitive!
12
Creating PHP variable A variable is declared the first time a value is set for it A variable declaration associates a name with a storage location in memory and specifies the type of data it will store: Examples: $a = 1.1 ; // declares and sets a real number $a = true ; // declares and sets a Boolean $a = 'Zip Zap' ; // declares and sets a string
13
Naming PHP variable Good Programming Practice (these should be obeyed)
Rules (these must be obeyed) all identifiers must follow the same rules must not start with a digit must contain only numbers, letters, underscore (_) and some other special characters names are case-sensitive (ThisName and thisName are two different variable names) No spaces! Good Programming Practice (these should be obeyed) always use meaningful names from the problem domain (for example, eggsPerBasket instead of n, which is meaningless, or count, which is not meaningful enough) start variable names with lower case capitalize interior words (use eggsPerBasket instead of eggsperbasket) use underscore (_) for spaces CAPITALIZE constants (i.e. variables that do not change values)
14
Exercise: Which of the following is not a suitable variable name
Exercise: Which of the following is not a suitable variable name? Explain your answer. 1. cars 2.two jars 3.2D 4. _long 5. –long Rules (these must be obeyed) must not start with a digit must contain only numbers, letters, underscore (_) and some other special characters No spaces!
15
Variable Default Values
Variables have default values Examples: $a = $a + 1; // $a=0 by default $s = $s."Fred"; // default $s="" IMPORTANT: It is best to not assume the default value is what you want. Always explicitly (clearly) set the initial value of a variable!!!! e.g. $a = 0; $s = ""; $b = false;
16
Assigning Values to Variables
The assignment operator: "=" "sets" a value for a variable not the "is equal to" sign; not the same as in algebra It means - "Assign the value of the expression on the right side to the variable on the left side." Can have the variable on both sides of the equals sign: Examples: $count = 10;// initialize counter to ten $count = $count - 1;// decrement counter new value of count = = 9
17
Data types in PHP Scalar Compound the simplest types
also called "primitive" or "basic" types cannot decompose into other types contain single values only Examples: Integer Floating point (real) String Boolean Compound also call class types more complex composed of other types (primitive or class types) can contain multiple values Examples: Arrays Objects
18
Data types in PHP floating point integer
real numbers, both positive and negative (e.g. 11.1) has a decimal point (fractional part) two formats number with decimal point, e.g e (or scientific, or floating-point) notation, e.g E2, which means x 102 In PHP these are referred to as double null The 'nothing' type (more on this later) integer just whole numbers (e.g., 11) may be positive or negative no decimal point may use Octal: 0755 // starts '0' Hex: 0xFF // starts '0x' In PHP these are referred to as int boolean only two values – true or false used for 'conditional' tests (e.g. if, when) In PHP these are referred to as bool
19
Data types in PHP null is a special type that means "no value“
A string is a sequence of characters A very common data type: Names, passwords, addresses, histories, etc. Often used to represent complex data: Dates, phone numbers, etc. A common data-interchange or data-sharing type: key-value pairs, XML, comma delimited data, logs PHP has a vast and powerful set of functions for working with strings (Manipulation, searching, comparing, translation, etc.). null is a special type that means "no value“ It can be used to unset a variable It is used as a place holder within compound types (more on this later…) $a = NULL; // $a is unset
20
Defining constants A constant contains information that does not change during the course of program execution Constant names do not begin with a dollar sign ($) Constant names use all uppercase letters Use the define() function to create a constant define("CONSTANT_NAME", value); The value you pass to the define() function can be a text string, number, or Boolean value Examples: define("MAX_SIZE",100); define("PI",3.14); define("CITY", "Ibri"); 20
21
Casting Data types Casting is the process of converting from one data type to another data type. This is sometimes useful. Casting only changes the type of the returned value (the single instance where the cast is done), not the type of the variable Example: $n = 5.0; $x = (int) $n; Since $n is a float, (int) $n converts the value to an int, now $x is an integer type. ***careful*** Odd things can happen when casting from a higher to a lower type $n = (int) ; // returns 5
22
What is the output of the following PHP code?
$x = (int) $n; echo " n = ", $n; echo " x = ", $x; ?>
23
Implicit Type Casting Casting is done implicitly (automatically) when a "lower" type is assigned to a "higher" type, depending on the operator The data type hierarchy (from lowest to highest): bool --> int --> double --> string --> array --> object Example: $x = 0; $n = ; $x = $n; the value 5 is cast to a double, then assigned to $n $x now is a double This is called implicit casting because it is done automatically
24
Operators Operators take operands and perform some operation
There are unary and binary operators that use 1, 2, and 3 operands respectively. Examples: Unary: $endOfFile++, !is_string() Binary: 2 * 3, $a % 3, $a = 40, $a > 3, $a == 5, $a || $b
25
Operator Precedence Expressions follow certain rules that determine the order an expression is evaluated Example: Should * 4 be 5*4 or ? PHP operators have precedence similar to algebra to deal with this (Operators with higher preference are evaluated first) Example: In the expression 2 + 3*4, the * operator has higher precedence than + so 3*4 is evaluated first to return the value 12, then the expression is evaluated to return 14 Use parentheses '( )' to force evaluation for lower precedence Example: (2 + 3)*4 Do not clutter (disorderly) expressions with parentheses when the precedence is correct and obvious
26
Operator Associativity
Some operators have the same precedence order. Example: Is 4 / 2 *3 first evaluated 4 / 6 or 2 * 3 ? Same as a*(b*c)=(a*b)*c In such cases, the associativity determines the order of evaluation (The / and * operators are left-associative and so the operations are performed from left to right) Example: 4 / 2 is first, returning 2, then 2 * 3 returning 6
27
Operator Associativity
Operators non-associative ++ -- (int) (float) (string) (array) (object) (bool) right ! left * / % + - . < <= > >= <> == != === !== && ||
28
Increment/Decrement Operators
Shorthand notation for common arithmetic operations used for counting (up or down) The counter can be incremented (or decremented) before or after using its current value ++$count; // preincrement: $count = $count + 1 before using it $count++; // postincrement: $count = $count + 1 after using it --$count; // predecrement: $count = $count - 1 before using it $count--; // postdecrement: $count = $count - 1 after using it You can also increment and decrement non-integers Examples: $var = 'a'; $var++; // $var now 'b‘ What if $var = 'az' ?
29
Exercise <?php $var = 'az'; $var++; echo $var; ?>
30
Specialized Assignment Operators
A shorthand notation for performing an operation on and assigning a new value to a variable General form: var <op>= expression; equivalent to: var = var <op> (expression); Where <op> is +, -, *, /, %, . , |, ^, ~, &, <<, >> Examples: $amount += 5; //same as $amount = $amount + 5; $amount *= 1 + $interestRate; //$amount = $amount * (1 + $interestRate); Note that the right side is treated as a unit
31
Echo/Print Both are language constructs, not functions
But print behaves like a function - it returns true if it succeeds and false otherwise print can only take one argument echo can take many, separated by commas New line for console output: echo "line1\nline2"; New line for HTML output: echo 'line1<br>line2'; Echo examples: echo 'hello'; //output: hello echo 'hello', ' goodbye'; //output: hello goodbye echo ('hello'); Print examples: print 'hello'; //output: hello print 'hello', 'goodbye'; //PHP error print('hello');
32
Strings Any sequence of characters e.g. abc123$%! (In PHP these are referred to as string) Designated as a literal (genuine) by single or double quotes ('string', "string") Note: Any variables inside a double quoted string are expanded into that string, Any variables inside a single quoted strings are not expanded $a = 10; echo "I have $a more slides"; I have 10 more slides $a = 10; echo 'I have $a more slides'; I have $a more slides
33
I need more $ but they \'ed the budget
Escape Sequences To use characters in strings that can't be typed or seen or are interpreted specially by php (such as $, {,},\, etc.) there are escape sequences \n newline (note: not the same as HTML <br>) \t tab \$ the $ character \\ the \ character Example: echo "I need more \$ but they \\'ed the budget\n"; I need more $ but they \'ed the budget
34
Single vs. double quotes
The way you declare a string will affect how Escape codes (e.g. \n ) are recognized; variables are interpreted Single quotes are literal (actual) $variable = 10; echo 'This prints $variable\n'; This prints $variable\n All characters print as written, No escape codes are recognized except \' and \\ Double quotes expand variable values and escape characters echo "This prints $variable\n"; This prints 10
35
Concatenating Strings
The '.' operator is used for string concatenation (merging two strings): $name = "Mondo"; $greeting = "Hi, there!"; echo $greeting . $name . "Welcome"; causes the following to display on the screen: Hi, there!MondoWelcome Note that you have to remember to include spaces if you want it to look right: $greeting . " " . $name . " Welcome"; Hi, there! Mondo Welcome
36
Useful Tools: print_r(), var_dump()
You can easily output variable types and their values with print_r(), var_dump() These functions are very useful for debugging (correcting) your programs print_r() displays just the value, var_dump() displays the type and value Examples: $a=1.2; $b= " hello "; $c=4; print_r($a); //output: 1.2 print_r($b); //output: hello print_r($c); // output: 4 var_dump($a); // output: float(1.2) var_dump($b); // output: string(5) "hello" var_dump($c); //output: int(4)
37
1. What does PHP stand for? a. Personal Hypertext Processor b. Private Home Page c. Personal Home Page d. PHP: Hypertext Preprocessor
38
2. PHP server scripts are surrounded by delimiters, which?
a. <?php…?> b. <script>...</script> c. <&>...</&> d. <?php>...</?>
39
3. How do you write "Hello World" in PHP?
a. "Hello World"; b. Document.Write("Hello World"); c. echo "Hello World";
40
4. All variables in PHP start with which symbol?
41
5. What is the correct way to end a PHP statement?
b. </php> c. New line d. ;
42
6. In PHP you can use both single quotes ( ' ' ) and double quotes ( " " ) for strings:
a. False b. True
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.