Download presentation
Presentation is loading. Please wait.
Published byGabriella Wilkins Modified over 6 years ago
1
CGS 3066: Web Programming and Design Spring 2017
PHP
2
PHP PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages quickly. PHP is a widely used, free, and efficient alternative to competitors such as Microsoft’s ASP. Manage cookies and sessions. Where is it used? It is powerful enough to be at the core of the biggest blogging system in the web (WordPress) It is deep enough to run the largest social network (Facebook) It is also easy enough to be a beginner’s first server side language
3
PHP Capabilities Generate dynamic page content
Create, open, read, write, delete, and close files on the server. Collect form data. Manage cookies and sessions. Add, delete, modify data in database. User management (i.e. restrict users to access some specific webpages) PHP can encrypt data.
4
PHP files 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" Image Source:
5
PHP Syntax ..even before <!DOCTYPE html>
A PHP script can be placed anywhere in the document ..even before <!DOCTYPE html> A PHP script starts with <?php and ends with ?>: contains commands separated by ; A PHP file normally contains HTML tags, and some PHP scripting code. <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body></html>
6
PHP Comments <html> <body> <?php
// This is a single line comment # This is also a single line comment /* This is a multiple lines comment block that spans over more than one line */ ?> </body></html>
7
PHP Case Sensitivity (php_keywords.php)
In PHP, all user-defined functions, classes, and keywords NOT case sensitive (unlike Javascript) <html><body> <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> </body> </html>
8
PHP Variable Case Sensitivity (php_variable.php)
However, in PHP, all variables are case-sensitive. <html><body> <?php $color = “red”; echo “May car is ”.$color.“<br>”; echo “May car is ”.$COLOR.“<br>”; echo “May car is ”.$coLor.“<br>”; ?> </body> </html>
9
Variables in PHP A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ ). Variable names are case sensitive ($y and $Y are two different variables).
10
Data Types String Integer Float (also double) Boolean Array Object
PHP supports the following data types String Integer Float (also double) Boolean Array Object NULL Resource A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. As resource variables hold special handles to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.
11
PHP Constants A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Unlike variables, constants are automatically global across the entire script. To set a constant, use the define() function – it takes three parameters: The first parameter defines the name of the constant, The second parameter defines the value of the constant The optional third parameter specifies whether the constant name should be case- sensitive. Default is false. define("MAXSIZE", 100);
12
PHP Operators Arithmetic: +,-,*,/,**,%
Various operators can be used in PHP Arithmetic: +,-,*,/,**,% Assignment: =, +=, -=, *=, /=, %= String: .(concatenation), .= Increment/decrement: ++ and -- (post and pre) Relational: ==, ===, !=, !==, <, <=, >, >=, <> Logical: and, &&, or, ||, xor, ! Array: +, ==, ===, !=, <>, !==
13
Conditional Statements
if ... if … else … if … elseif … else … Switch <?php if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?> additional control structures(If necessary):
14
Loops while : do...while: $x = 2; while ($x < 1000) {
echo $x . “\n”; // \n is newline character $x = $x * $x; } do...while: do { echo $x . “\n”; } while ($x < 1000); // note the semicolon
15
Loops(Contd.) for: foreach (works only on arrays and objects):
for ($i = 1; $i <= 10; $i++) { echo $i . “\n”; //prints 1 through 10, one number per line } foreach (works only on arrays and objects): $arr = array(1, 2, 3, 4); foreach ($arr as $value) { //$value corresponds to each element in $arr echo $value “\n”; }
16
PHP Functions The real power of PHP comes from its functions; it has more than 1000 built-in functions. Besides the built-in PHP functions, we can create our own functions. A user defined function declaration starts with the word “function” Example: <?php function foo($x, $y) { echo “example function \n”; echo $x + $y . \n”; return $x + $y; //optional } ?> … <?php foo(3,4); //prints 7 $retval = foo(5,6); // prints 11, copies 11 to $retval ?>
17
Indexed Arrays in PHP Maintains a list of values using the same variable name and unique index Array are three types Indexed array – Array with a numeric index. Arrays with named keys. Multidimensional Array- Arrays containing one or more arrays. array() function is used to create an array $colors = array(“blue”,”yellow”, “pink”); echo $colors[0]; //prints ‘blue’ echo $colors[2]; //prints ‘pink’ To append an element to the array: $colors[] = “purple”; // adds purple at $color[3] To remove an element from the array, use unset(): unset($colors[2]); // also removes the index 2 from array
18
Associative Arrays in PHP
keep track of a set of unique keys and the values that they associate to – called an associative array Same array()function, different syntax $myarray = array( "foo" => "bar", "bar" => "foo", ); To add an element to the array, use a new key value: $myarray[“newkey”] = “new value”; // adds purple at $color[3] Use isset() function to test if a variable/keyed value exists of not: isset($myarray[“bar”]); //function returns true isset($myarray[“barr”]); //function returns false
19
The for-each loop with PHP arrays
Easy way to iterate over all elements of an array Example, iterate and print all elements of an indexed array: $colors = array(“blue”,”yellow”, “pink”); //indexed array foreach ($colors as $color) { echo $color; // simply prints each color } foreach ($colors as $indexno => $color) { echo “$indexno => $color ”; // prints color with index $myarray = array("foo" => "bar", "bar" => "foo"); //associative array foreach ($myarray as $key => $value) { echo “$key => $value ”; // prints values with key
20
Collect Form data in PHP
21
Superglobals A collection of associative arrays those can be accessed from anywhere in PHP file $GLOBALS //array of all variables in ‘global scope’( not belonging to any function scope ) $_SERVER // Server and execution environment information $_GET // HTTP GET variables $_POST //HTTP POST variables $_FILES // HTTP File Upload variables $_COOKIE // HTTP Cookies $_SESSION // Session variables $_REQUEST // contains a copy of contents of $_GET, $_POST and $_COOKIE $_ENV //environment variables (information passed from web server shell environment) Source:
22
Forms with PHP Form data is sent to the server when the user clicks “Submit”. The PHP superglobals $_GET and $_POST are used to collect form-data (depending on the method attribute of the submitted form) $_GET array populated from the URL of the submitted form. Example: maps $_GET[“fname”] to “john”, $_GET[“lname”] to “doe” $_POST is an array of variables passed to the current script via the HTTP POST method.
23
$_GET vs. $_POST $_GET: HTTP GET requests can be cached, bookmarked
GET requests are limited by the length of the URL (2000 characters) No privacy, not suitable for user authentication $_POST: Cannot be cached , browser must make request to the server with form data Cannot be bookmarked Used to submit sensitive information No limit on the posted data volume
24
Example: client.html <html>
<head><title>Executing on Client Side</title></head> <body> <form action=“server.php" method="post"> Name: <input type="text" name="name"><br> <input type="submit" name="submit" value="Submit Form"><br> </form> </body> </html>
25
Example: server.php <html>
<head><title>Executing on the Server Side</title></head> <body> The name that was submitted was: <?php echo $_POST['name']; ?><br> </body> </html>
26
Example: self-submit form value (php_self_submit.php)
<html> <body> <!– form submits to same page by default, no need to set action --> <form method="post"> Name <input type="text" name="name"><br> <input type="submit" name="submit" value="Submit Form"><br> </form> <?php if(isset($_POST['submit'])) //tests if the submit button is clicked or not { $name = $_POST['name']; echo “From Server: The name that was submitted was: <b> $name </b>"; echo "<br>You can use the above form again to enter a new name."; } ?> </body> </html>
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.