PHP
◼ PHP == ‘Hypertext Preprocessor’ ◼ Open-source, server-side scripting language ◼ Used to generate dynamic web-pages ◼ PHP scripts reside between reserved PHP tags ❑ This allows the programmer to embed PHP scripts within HTML pages. ◼ PHP is an 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. What is 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
PHP Overview ◼ Easy learning ◼ Perl- and C-like syntax. Relatively easy to learn. ◼ Large function library ◼ Embedded directly into HTML ◼ Interpreted, no need to compile ◼ Open Source server-side scripting language designed specifically for the web.
PHP Overview (cont.) ◼ Conceived in 1994, now used on +10 million web sites. ◼ Outputs not only HTML but can output XML, images (JPG & PNG), PDF files and even Flash movies all generated on the fly. Can write these files to the file system ◼ Supports a wide-range of databases (20+ODBC)
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". ◼ 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.
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. Download it from the official PHP resource: www.php.net • PHP is easy to learn and runs efficiently on the server side. • PHP is widely-used.
How Does PHP Work? ◼ PHP is a server-side programming language which means it runs in the server. PHP plays an intermediate role between a client and the date stored in the server and other servers.
◼ Client Request: A user requests a web page (that includes PHP code) from a web browser. ◼ Server Processing: The web server (like Apache or Nginx) receives the request and identifies any PHP code within the requested page. ◼ PHP Interpreter: The web server then passes the PHP code to a PHP interpreter, which processes the code. ◼ Dynamic Content Generation: The PHP interpreter executes the script, potentially interacting with databases or other resources to generate dynamic content. ◼ HTML Output: The PHP interpreter generates HTML output (or other content types) based on the script's execution. ◼ Server Response: The web server receives the HTML output from the PHP interpreter and sends it back to the client's browser. ◼ Browser Rendering: The browser receives the HTML and renders it, displaying the web page to the user.
What Do You Need to Start Using PHP? • Install a web server • Install PHP • Install a database, such as MySQL ◼ You can install a server on your personal computer such as XAMPP server from the link below: ◼ https://www.apachefriends.org/index.html ◼A PHP version and MySQL come out of the box when you install XAMPP server. You can use other development server instead of XAMPP such as WAMPSERVER that you can download from here (http://www.wampserver.com/en/).
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 … ?>
PHP 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 ?> Ex: <!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html>
Comments in PHP ◼ Standard C, C++, and shell comment symbols // C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */ Ex: // 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 */
PHP Case Sensitivity ◼ In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. ◼ In the example below, all three echo statements below are legal (and equal) ◼ Ex: <!DOCTYPE html> <html> <body> <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> </body> </html>
◼ Ex: <?php $color = "red"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?> BUT In the example above only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables)
ECHO/Print ◼ In PHP, there are two basic ways to get output: echo and print. ◼ 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 echo "Hello World”; ◼ Echo and echo( ) : 1. echo has no return value. 2. echo can take multiple parameters. 3. Ex: <?php echo "Hello"; echo("Hello"); ?>
print ◼ print has a return value of 1 so it can be used in expressions. ◼ print can take one argument. ◼ The print statement can be used with or without parentheses: print or print(). ◼ Ex: print "Hello"; print("Hello");
Variables in PHP ◼ PHP variables must begin with a “$” sign. ◼ Syntax: $variable_name = "value"; ◼ $a; ◼ 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.
Rules for PHP variables : ◼ 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 alpha-numeric characters and underscores (A-z, 0-9, and _ ) ◼ Variable names are case-sensitive ($age and $AGE are two different variables)
Variable usage <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?> Ex: <?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?> or
PHP $$ Signs ◼ A reference variable called $$x (double dollar) has a value that may be accessed by placing the $ sign before the $x value. ◼ In PHP, they are referred to as variable variables. ◼ Variables whose names are dynamically generated by the value of another variable are known as variable variables. <?php $a = 'hello'; $$a="word"; echo "$a {$$a}"; ?> Output : helloWord
Local variable ◼ A variable declared within a function has a LOCAL SCOPE. ◼ It cannot be accessed outside that function. ◼ Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. ◼ Ex: <?php function text () { $name = “Students"; //local variable echo "Hello ". $name; } text(); ?> OUTPUT: Hello Students
Static variable ◼ When a function is completed/executed, all of its variables are deleted. ◼ Sometimes we want a local variable NOT to be deleted. ◼ It completes its execution and the memory is free. But sometimes we need to store the variables even after the completion of function execution. ◼ To do this, use the static keyword when you first declare the variable. ◼ Example : ◼ <?php function myFunction() { static $count = 0; $count++; echo $count; } myFunction(); myFunction(); myFunction(); ?> //Output : 123
Global Variable ◼ A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. ◼ These variables can be accessed directly outside a function. ◼ To get access within a function, we need to use the “global” keyword before the variable to refer to the global variable. ◼ We can access global variables anywhere in our code, including inside functions and classes. Since global variables are available globally, we can use the variable name wherever needed. Also, we can modify global variables by directly assigning a new value to them. ◼ Ex: <?php $number = 1; function fun1() { global $number; $number++; } function fun2() { global $number; $number++; } fun1(); fun2(); echo $number; ?> //OUTPUT : 3
PHP Global Variables: Superglobal ◼ Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope ◼ Always accessible 1. $GLOBALS 2. $_SERVER 3. $_REQUEST 4. $_POST 5. $_GET 6. $_FILES 7. $_ENV 8. $_COOKIE 9. $_SESSION
PHP $GLOBALS ◼ $GLOBALS is an array that contains all global variables. ◼ $GLOBALS is a superglobal variable used to access global variables from anywhere in the PHP program ◼ Ex: <?php $x=5; $y=10; function myTest() { $GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y']; } myTest(); echo $y; ?> // outputs 15
$_REQUEST ◼ The $_REQUEST variable is a variable with the contents of $_GET and $_POST and $_COOKIE variables. ◼ Before you can use the the $_REQUEST variable you have to have a form in html that has the method equal to GET and POST. Then in the php, you can use the $_REQUEST variable to get the data that you wanted. ◼ An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$_GET, $_POST, and $_REQUEST ◼ $_GET: ◼ The $_GET variable is used to get data from a form that is written in HTML. Also in the url $_GET variable will display the data that was tak ◼ The $_GET syntax is ◼ ($_GET['name of the form field goes here']).en by the $_GET variable. ◼ ?php ◼ //Displays the data that was received from the input box named name in the form ◼ ($_GET['form name goes here']) ◼ ?>
HTML form with $_GET <?php // It will display the data that it was received from the form called name echo ($_GET['name']); ?> <form action="name of the php file that has the ($_GET[]) variable in it" method="GET"> Name:<input type="text" name="name"> <input type="submit" value="Submit"> </form>
$_ post : ◼ Submits data to be processed to a specified resource. ◼ How to use it? ◼ Before you can use the the $_POST variable you have to have a form in html that has the method equal to POST. Then in the php, you can use the $_POST variable to get the data that you wanted. ◼ The $_POST syntax is ◼ ($_POST['name of the form field goes here']). ◼ Examples ◼ <?php ◼ //The $_POST gets the data from the form ◼ ($_POST['form name goes here']) ◼ ?>
The html form with $_POST <?php //Displays the data that was received from the input box named name in the form echo ($_POST['name']); ?> //This is the html form that creates the input box and submit button //The method for the form is in the line below <form action="test.php" method=POST> Name:<br><input type="text" name="name"><br> <input type="submit" value="Submit"> </form>
Using GET for the method ?php //Displays the data that was received from the input box named name in the form echo ($_REQUEST['name']); ?> //This is the html form that creates the input box and submit button //The method for the form is in the line below <form action="test.php" method=GET> Name:<br><input type="text" name="name"><br> <input type="submit" value="Submit"> </form>
Using POST for the method ?php //Displays the data that was received from the input box named name in the form echo ($_REQUEST['name']); ?> //This is the html form that creates the input box and submit button //The method for the form is in the line below <form action="test.php" method=POST> Name:<br><input type="text" name="name"><br> <input type="submit" value="Submit"> </form>
Constants ◼ Constants are automatically global across the entire script. ◼ To set a constant, use the define() function <?php define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?>
PHP String ◼ A string can be any text inside quotes. You can use single or double quotes: ◼ Ex: <?php $x = "Hello world!"; $y = ”Hello world!'; echo $x; echo "<br>"; echo $y; ?> ◼ You can use either quotation mark type to create the string. ◼ To use a variable within another string, you must use double quotation marks. ◼ Ex: $first_name= 'Tobias'; $today='August 2, 2011'; $var="Define "platitude", please."; $var='Define "platitude", please.'; echo $first_name; echo"Hello, $first_name";
String functions ◼ strlen(<string>) - returns the length of a string, in characters echo strlen("Hello world!"); ◼ strpos()- used to search for a specified character or text within a string echo strpos("Hello world!","world"); ◼ chr() - Return characters from different ASCII values echo chr(52) . "<br>"; ◼ strcmp() - Compare two strings (case-sensitive)
String operators Operator Name Example Result . Concatenation $txt1 = "Hello" $txt2 = $txt1 . " world!" Now $txt2 contains "Hello world!" .= Concatenation assignment $txt1 = "Hello" $txt1 .= " world!" Now $txt1 contains "Hello world!"
Concatenation ◼ Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello 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””; Print $heading; ?> “Computer Science”
PHP Integer ◼ An integer must have at least one digit ◼ An integer must not have a decimal point ◼ An integer can be either positive or negative ◼ Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based ◼ - prefixed with 0x) or octal (8-based - prefixed with 0) ◼ In the following example $x is an integer. The PHP var_dump() function retur ◼ Ex: <?php $x = 5985; var_dump($x); ?> ns the data type and value
PHP Float float (floating point number) is a number with a decimal point or a number in exponential form. In the following example $x is a float. The PHP var_dump() function returns the data type and value: Ex: <?php $x = 10.365; var_dump($x); ?>
PHP Boolean ◼ A Boolean represents two possible states: TRUE or FALSE. ◼ Ex: ◼ $x = true; ◼ $y = false;
PHP Array ◼ In the following example $cars is an array. The PHP var_dump() function returns the data type and value: ◼ Ex: ◼ <?php ◼ $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ◼ ?>
PHP Operators ◼ Operators are used to perform operations on variables and values. ◼ PHP divides the operators in the following groups: ◼ Arithmetic operators ◼ Assignment operators ◼ Comparison operators ◼ Increment/Decrement operators ◼ Logical operators ◼ String operators ◼ Array operators ◼ Conditional assignment operators
Arithmetic Operations ◼ $a - $b // subtraction ◼ $a * $b // multiplication ◼ $a / $b // division ◼ $a += 5 // $a = $a+5 Also works for *= and /= ◼ Refer Link : W3school.com <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h1>$total</h1>”; // total is 45 ?>
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). ▪ Example if/else if/else statement: 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; }
If ... Else... ◼ If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> No THEN in 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.
Date() function ◼ Formats • d - Represents the day of the month (01 to 31) • m - Represents a month (01 to 12) • Y - Represents a year (in four digits) • 1 - Represents the day of the week • h - 12-hour format of an hour with leading zeros (01 to 12) • i - Minutes with leading zeros (00 to 59) • s - Seconds with leading zeros (00 to 59) • a - Lowercase Ante meridiem and Post meridiem (am or pm)
Date Display $datedisplay=date(“yyyy/m/d”); Print $datedisplay; # If the date is April 25, 2025 # It would display as 2025/25/3 2025/25/3 $datedisplay=date(“l, F J, Y”); Print $datedisplay; # If the date is March 25th , 2025 # Tuesday, March 25, 2025 Tuesday, March 25, 2025
Month, Day & Date Format Symbols M Jan F January m 01 n 1 Day of Month d 01 Day of Month J 1 Day of Week l Monday Day of Week D Mon
Arrays ◼ In PHP, there are three kind of arrays: > Numeric array - An array with a numeric index > Associative array - An array where each ID key is associated with a value > Multidimensional array - An array containing one or more arrays
Numeric Arrays ◼ A numeric array stores each array element with a numeric index. ◼ There are two methods to create a numeric array.
Numeric Arrays ◼In the following example the index is automatically assigned (the index starts at 0): ◼In the following example we assign the index manually:
Numeric Arrays ◼In the following example you access the variable values by referring to the array name and index: ◼The code above will output:
Associative Arrays ◼ With an associative array, each ID key is associated with a value. ◼ When storing data about specific named values, a numerical array is not always the best way to do it. ◼ With associative arrays we can use the values as keys and assign values to them.
Associative Arrays ◼In this example we use an array to assign ages to the different persons: ◼This example is the same as the one above, but shows a different way of creating the array:
Associative Arrays
Multidimensional Arrays ▪ Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. ▪ We can define multi-dimensional arrays as an array of arrays. ▪ Every element in this array can be an array and they can also hold other sub- arrays . ▪ Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions. Ex: $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); The two-dimensional $cars array contains four arrays, and it has two indices: row and column.
Multidimensional Arrays
Multidimensional Arrays
Multidimensional Arrays
Add array item: To add items to an existing array, you can use the bracket [] syntax. <pre> <?php $fruits = array("Apple", "Banana", "Cherry"); $fruits[] = "Orange"; var_dump($fruits); ?> </pre> array(4) { [0]=> string(5) "Apple" [1]=> string(6) "Banana" [2]=> string(6) "Cherry" [3]=> string(6) "Orange" }
Update Array Item 1. In Numeric Array : To update an existing array item, you can refer to the index number for indexed arrays, and the key name for associative arrays. <?php $cars = array("Volvo", "BMW", "Toyota"); $cars[1] = "santro"; var_dump($cars); ?> //OUTPUT: array(3) { [0]=> string(5) "Volvo" [1]=> string(6) "santro" [2]=> string(6) "Toyota" }
Update Array Item conti.. In Associative Array :To update items from an associative array, use the key name. Prog: <body> <pre> <?php $cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964); $cars["year"] = 2024; var_dump($cars); ?> </pre> </body>
Foreach loop to update array Items Iterating over arrays is done with the foreach loop. Syntax: foreach($array as $value) { // Statements to be executed } Program : <?php $colors = array("Red", "Green", "Blue","Yellow","Pink"); // Loop through count array foreach($colors as $value){ echo $value . "<br>"; } ?>
Remove Array Item • To remove an existing item from an array, you can use the array_splice() function. • With the array_splice() function you specify the index (where to start) and how many items you want to delete. • We can also use the unset() function to delete existing array items. • The unset() function does not re-arrange the indexes, meaning that after deletion the array will no longer contain the missing indexes. <pre> <?php $cars = array("Volvo", "BMW", "Toyota"); unset($cars[1]); var_dump($cars); ?> </pre> array(2) { [0]=> string(5) "Volvo" [2]=> string(6) "Toyota" }
Function PHP functions are blocks of reusable code that perform specific tasks. Functions help organize code and make it easier to maintain and debug PHP Web applications. Syntax: function function_name() { //Statement to be executed } Ex: <?php functionwelcMsg() { echo "Hello welcome!"; } welcMsg(); ?>
Function Arguments In PHP Function, arguments may be used to transfer information to functions. A variable is the same as an argument. Arguments are listed within parentheses after the function name. You can add as many arguments as you want; just use a comma to divide them. <?php functionStudentsName($firstname) { echo "$firstname<br>"; } StudentsName("Janani"); StudentsName("Helen"); StudentsName("Stella"); StudentsName("Kamal"); StudentsName("Babu"); ?>
Passing Arguments By Reference Arguments are generally passed by value in PHP, which ensures that the function uses a copy of the value and the variable passed into the function cannot be modified. Changes to the argument modify the variable passed in when a function argument is passed by reference. The & operator is used to convert a function argument into a reference. <?php function addition(&$val) { $val += 10; } $number =5; addition($number); echo $number; ?> Output : 15
PHP Functions - Returning Value This means the PHP Function can be called by its name, and when executing the function, it will return some value. <?php function circle($r){ return 3.14*$r*$r; } echo "Area of circle is: ".circle(3); ?>
Class • A class is a definition of the properties and methods of a particular type of object • It includes the properties and functions that process the properties. • An object is the instance of its class. It is characterized by the properties and functions defined in the class. • Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. • A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. • A class may contain its own constants, variables (called "properties"), and functions (called "methods"). • Ex: <?php class SimpleClass { // property declaration public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; }} ?>
PHP - The $this Keyword The $this keyword refers to the current object, and is only available inside methods. There are two ways: 1. Inside the class (by adding a set_name() method and use $this): 2. Outside the class (by directly changing the property value): Ex for Inside the class (by adding a set_name() method and use $this): <?php class Fruit { public $name; function set_name($name) { $this->name = $name; } } $apple = new Fruit(); $apple->set_name("Apple"); echo $apple->name; ?> Apple
Outside the class (by directly changing the property value): <?php class Fruit { public $name; } $apple = new Fruit(); $apple->name = "Apple"; echo $apple->name; ?> Apple
Defining an Object in PHP : new To create an instance of a class, the new keyword must be used <?php class SimpleClass { } $instance = new SimpleClass(); var_dump($instance); // This can also be done with a variable: $className = 'SimpleClass'; $instance = new $className(); // new SimpleClass() var_dump($instance); ?> object(SimpleClass)#1 (0) { } object(SimpleClass)#2 (0) { }
PHP - Forms •Access to the HTTP POST and GET data is simple in PHP •The global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form>
PHP Form Handling BY superglobals $_GET and $_POST
PHP Forms - $_GET Function ◼ The built-in $_GET function is used to collect values from a form sent with method="get". ◼ Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max. 100 characters).
PHP Forms - $_GET Function ◼The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array)
PHP Forms - $_GET Function > When using method="get" in HTML forms, all variable names and values are displayed in the URL. > This method should not be used when sending passwords or other sensitive information! > However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. > The get method is not suitable for large variable values; the value cannot exceed 100 chars.
PHP Forms - $_GET Function <html> <body> <form action="welcome_get.php" method="GET"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
PHP Forms - $_POST Function > The built-in $_POST function is used to collect values from a form sent with method="post". > Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. > Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
PHP Forms - $_POST Function And here is what the code of action.php might look like:
2.Form Validation It will show how to process PHP forms with security Proper validation of form data is important to protect your form from hackers and spammers Validation: Validate each input according to the specified rules: • Name: Make the field as required. It must contain only letters and whitespace. • E-mail: Make the field as required, It must contain a valid email address. • Gender: Make the field as required, It must select one option. • Mobile Number: Make the field as required, It must contain a valid mobile number format (e.g., 10 digits).
Example
1.Text Fields Name: <input type="text" name="name"> E-mail: <input type="text" name="email"> Website: <input type="text" name="website"> Comment: <textarea name="comment" rows="5" cols="40"></textarea> 2.Radio Buttons : Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other 3.The Form Element <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Here the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page The htmlspecialchars() function converts special characters into HTML entities. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page.
Conti… <h2>PHP Form Validation Example</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website"> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <br><br> <input type="submit" name="submit" value="Submit"> </form>
Conti.. <?php echo "<h2>Your Input:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
Output:
How to validate a form data with PHP <?php // define variables and set to empty values $name = $email = $gender = $comment = $website = “ "; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
<h2>PHP Form Validation Example</h2> <form method="post" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?> "> Name: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website"> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <br><br> <input type="submit" name="submit" value="Submit"> </form>
<?php echo "<h2>Your Input:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
Conti.. To check whether the form has been submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been submitted - and it should be validated.
Content Mgmt System(CMS) : A content management system (CMS) is software that helps users create, manage, store, and modify their digital content. This system is a one-stop-shop to store content—such as apps, images, and websites—in a user-friendly interface that is customizable to an organization’s needs and their employees. CMS builds and manages the content for a brand’s website
How does a CMS work? • To understand how a content management system works, let’s take a step back. A website that is manually run would require the individual or organization to code or write a static HTML file from scratch and upload it to the server for each web page. This requires significant time and energy and periodic updating that takes away precious resources from already busy organizations. • A way to avoid this complex work is to use a CMS platform. The system is already created on the back-end and front-end, while all the creator sees is a user-friendly interface that allows them to make necessary changes in a simplified manner. The CMS is built to enhance the customer experience for web content that is viewed online or on a mobile app.
Examples of a CMS • WordPress: Originally was a web content management system that was built to publish blogs, but has extended into many other areas. The open source management system can be used for websites, professional portfolios, e-commerce stores and more. • Drupal: The open source CMS is used by many companies around the globe to build and maintain their websites. The user interface is easily accessible and allows you to create and publish unlimited content. • Squarespace: Square space is an all-in-one content management system, meaning with a single subscription the owner can do it all without needing third-party integrations. This is a popular CMS for small businesses online and in-store. • Joomla: This CMS is another open source system to build websites and online applications. It is SEO-friendly and features unlimited designs and built-in multilingual capabilities.
WordPress • Many people choose WordPress because it’s free, which is a huge advantage. • WordPress is easy to learn for nontechnical folks but also allows developers to customize code. You can start by setting up a simple website to publish content quickly and learn more as you go along. • Users of WordPress can select from two basic versions of the service. The first of these is the “hosted” version of WordPress, which is accessible at WordPress.com. This version allows users to launch a website that is hosted on WordPress’s own servers. it is often favored by non-technical users, who may wish to avoid the complexity of hosting a website on their own private server. As an additional benefit, the hosted version of WordPress is automatically updated to the latest version of the WordPress software, • For more advanced users, it is also possible to simply download the latest version of WordPress from WordPress.org. By selecting this option, the user must make their own arrangements to host the software either on their own private server or from a third-party hosting provider
DRUPAL • Drupal (/ˈdruːpəl/) is a free and open-source web content management system (CMS) written in PHP • Drupal is content management software. It's used to make many of the websites and applications you use every day. • Written in PHP programming language, Drupal CMS is widely used for creating and managing websites and web applications. • Drupal is primarily a backend system (CMS) that manages content and workflows, but it can also be used with front-end frameworks for dynamic user experiences through decoupled or headless approaches. • Drupal is primarily a backend system (CMS) that manages content and workflows, but it can also be used with front-end frameworks for dynamic user experiences through decoupled or headless approaches.
Include Files Include “opendb.php”; Include “closedb.php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: <hr SIZE=11 NOSHADE WIDTH=“100%”> <i>Copyright © 2008-2010 KSU </i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL: http://www.kent.edu</i></font><br>

PHP in Web development and Applications.pdf

  • 1.
  • 2.
    ◼ PHP ==‘Hypertext Preprocessor’ ◼ Open-source, server-side scripting language ◼ Used to generate dynamic web-pages ◼ PHP scripts reside between reserved PHP tags ❑ This allows the programmer to embed PHP scripts within HTML pages. ◼ PHP is an 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. What is PHP?
  • 3.
    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
  • 4.
    PHP Overview ◼ Easylearning ◼ Perl- and C-like syntax. Relatively easy to learn. ◼ Large function library ◼ Embedded directly into HTML ◼ Interpreted, no need to compile ◼ Open Source server-side scripting language designed specifically for the web.
  • 5.
    PHP Overview (cont.) ◼Conceived in 1994, now used on +10 million web sites. ◼ Outputs not only HTML but can output XML, images (JPG & PNG), PDF files and even Flash movies all generated on the fly. Can write these files to the file system ◼ Supports a wide-range of databases (20+ODBC)
  • 6.
    What is aPHP 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". ◼ 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.
  • 7.
    Why PHP • PHPruns 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. Download it from the official PHP resource: www.php.net • PHP is easy to learn and runs efficiently on the server side. • PHP is widely-used.
  • 8.
    How Does PHPWork? ◼ PHP is a server-side programming language which means it runs in the server. PHP plays an intermediate role between a client and the date stored in the server and other servers.
  • 10.
    ◼ Client Request: Auser requests a web page (that includes PHP code) from a web browser. ◼ Server Processing: The web server (like Apache or Nginx) receives the request and identifies any PHP code within the requested page. ◼ PHP Interpreter: The web server then passes the PHP code to a PHP interpreter, which processes the code. ◼ Dynamic Content Generation: The PHP interpreter executes the script, potentially interacting with databases or other resources to generate dynamic content. ◼ HTML Output: The PHP interpreter generates HTML output (or other content types) based on the script's execution. ◼ Server Response: The web server receives the HTML output from the PHP interpreter and sends it back to the client's browser. ◼ Browser Rendering: The browser receives the HTML and renders it, displaying the web page to the user.
  • 11.
    What Do YouNeed to Start Using PHP? • Install a web server • Install PHP • Install a database, such as MySQL ◼ You can install a server on your personal computer such as XAMPP server from the link below: ◼ https://www.apachefriends.org/index.html ◼A PHP version and MySQL come out of the box when you install XAMPP server. You can use other development server instead of XAMPP such as WAMPSERVER that you can download from here (http://www.wampserver.com/en/).
  • 12.
    What does PHPcode 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 … ?>
  • 13.
    PHP Syntax: ◼ APHP 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 ?> Ex: <!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html>
  • 14.
    Comments in PHP ◼Standard C, C++, and shell comment symbols // C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */ Ex: // 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 */
  • 15.
    PHP Case Sensitivity ◼In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. ◼ In the example below, all three echo statements below are legal (and equal) ◼ Ex: <!DOCTYPE html> <html> <body> <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> </body> </html>
  • 16.
    ◼ Ex: <?php $color ="red"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?> BUT In the example above only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables)
  • 17.
    ECHO/Print ◼ In PHP,there are two basic ways to get output: echo and print. ◼ 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 echo "Hello World”; ◼ Echo and echo( ) : 1. echo has no return value. 2. echo can take multiple parameters. 3. Ex: <?php echo "Hello"; echo("Hello"); ?>
  • 18.
    print ◼ print hasa return value of 1 so it can be used in expressions. ◼ print can take one argument. ◼ The print statement can be used with or without parentheses: print or print(). ◼ Ex: print "Hello"; print("Hello");
  • 19.
    Variables in PHP ◼PHP variables must begin with a “$” sign. ◼ Syntax: $variable_name = "value"; ◼ $a; ◼ 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.
  • 20.
    Rules for PHPvariables : ◼ 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 alpha-numeric characters and underscores (A-z, 0-9, and _ ) ◼ Variable names are case-sensitive ($age and $AGE are two different variables)
  • 21.
    Variable usage <?php $foo =25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?> Ex: <?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?> or
  • 22.
    PHP $$ Signs ◼A reference variable called $$x (double dollar) has a value that may be accessed by placing the $ sign before the $x value. ◼ In PHP, they are referred to as variable variables. ◼ Variables whose names are dynamically generated by the value of another variable are known as variable variables. <?php $a = 'hello'; $$a="word"; echo "$a {$$a}"; ?> Output : helloWord
  • 23.
    Local variable ◼ Avariable declared within a function has a LOCAL SCOPE. ◼ It cannot be accessed outside that function. ◼ Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. ◼ Ex: <?php function text () { $name = “Students"; //local variable echo "Hello ". $name; } text(); ?> OUTPUT: Hello Students
  • 24.
    Static variable ◼ Whena function is completed/executed, all of its variables are deleted. ◼ Sometimes we want a local variable NOT to be deleted. ◼ It completes its execution and the memory is free. But sometimes we need to store the variables even after the completion of function execution. ◼ To do this, use the static keyword when you first declare the variable. ◼ Example : ◼ <?php function myFunction() { static $count = 0; $count++; echo $count; } myFunction(); myFunction(); myFunction(); ?> //Output : 123
  • 25.
    Global Variable ◼ Avariable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. ◼ These variables can be accessed directly outside a function. ◼ To get access within a function, we need to use the “global” keyword before the variable to refer to the global variable. ◼ We can access global variables anywhere in our code, including inside functions and classes. Since global variables are available globally, we can use the variable name wherever needed. Also, we can modify global variables by directly assigning a new value to them. ◼ Ex: <?php $number = 1; function fun1() { global $number; $number++; } function fun2() { global $number; $number++; } fun1(); fun2(); echo $number; ?> //OUTPUT : 3
  • 26.
    PHP Global Variables:Superglobal ◼ Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope ◼ Always accessible 1. $GLOBALS 2. $_SERVER 3. $_REQUEST 4. $_POST 5. $_GET 6. $_FILES 7. $_ENV 8. $_COOKIE 9. $_SESSION
  • 27.
    PHP $GLOBALS ◼ $GLOBALSis an array that contains all global variables. ◼ $GLOBALS is a superglobal variable used to access global variables from anywhere in the PHP program ◼ Ex: <?php $x=5; $y=10; function myTest() { $GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y']; } myTest(); echo $y; ?> // outputs 15
  • 28.
    $_REQUEST ◼ The $_REQUESTvariable is a variable with the contents of $_GET and $_POST and $_COOKIE variables. ◼ Before you can use the the $_REQUEST variable you have to have a form in html that has the method equal to GET and POST. Then in the php, you can use the $_REQUEST variable to get the data that you wanted. ◼ An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
  • 29.
    $_GET, $_POST, and$_REQUEST ◼ $_GET: ◼ The $_GET variable is used to get data from a form that is written in HTML. Also in the url $_GET variable will display the data that was tak ◼ The $_GET syntax is ◼ ($_GET['name of the form field goes here']).en by the $_GET variable. ◼ ?php ◼ //Displays the data that was received from the input box named name in the form ◼ ($_GET['form name goes here']) ◼ ?>
  • 30.
    HTML form with$_GET <?php // It will display the data that it was received from the form called name echo ($_GET['name']); ?> <form action="name of the php file that has the ($_GET[]) variable in it" method="GET"> Name:<input type="text" name="name"> <input type="submit" value="Submit"> </form>
  • 31.
    $_ post : ◼Submits data to be processed to a specified resource. ◼ How to use it? ◼ Before you can use the the $_POST variable you have to have a form in html that has the method equal to POST. Then in the php, you can use the $_POST variable to get the data that you wanted. ◼ The $_POST syntax is ◼ ($_POST['name of the form field goes here']). ◼ Examples ◼ <?php ◼ //The $_POST gets the data from the form ◼ ($_POST['form name goes here']) ◼ ?>
  • 32.
    The html formwith $_POST <?php //Displays the data that was received from the input box named name in the form echo ($_POST['name']); ?> //This is the html form that creates the input box and submit button //The method for the form is in the line below <form action="test.php" method=POST> Name:<br><input type="text" name="name"><br> <input type="submit" value="Submit"> </form>
  • 33.
    Using GET forthe method ?php //Displays the data that was received from the input box named name in the form echo ($_REQUEST['name']); ?> //This is the html form that creates the input box and submit button //The method for the form is in the line below <form action="test.php" method=GET> Name:<br><input type="text" name="name"><br> <input type="submit" value="Submit"> </form>
  • 34.
    Using POST forthe method ?php //Displays the data that was received from the input box named name in the form echo ($_REQUEST['name']); ?> //This is the html form that creates the input box and submit button //The method for the form is in the line below <form action="test.php" method=POST> Name:<br><input type="text" name="name"><br> <input type="submit" value="Submit"> </form>
  • 35.
    Constants ◼ Constants areautomatically global across the entire script. ◼ To set a constant, use the define() function <?php define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?>
  • 36.
    PHP String ◼ Astring can be any text inside quotes. You can use single or double quotes: ◼ Ex: <?php $x = "Hello world!"; $y = ”Hello world!'; echo $x; echo "<br>"; echo $y; ?> ◼ You can use either quotation mark type to create the string. ◼ To use a variable within another string, you must use double quotation marks. ◼ Ex: $first_name= 'Tobias'; $today='August 2, 2011'; $var="Define "platitude", please."; $var='Define "platitude", please.'; echo $first_name; echo"Hello, $first_name";
  • 37.
    String functions ◼ strlen(<string>)- returns the length of a string, in characters echo strlen("Hello world!"); ◼ strpos()- used to search for a specified character or text within a string echo strpos("Hello world!","world"); ◼ chr() - Return characters from different ASCII values echo chr(52) . "<br>"; ◼ strcmp() - Compare two strings (case-sensitive)
  • 38.
    String operators Operator NameExample Result . Concatenation $txt1 = "Hello" $txt2 = $txt1 . " world!" Now $txt2 contains "Hello world!" .= Concatenation assignment $txt1 = "Hello" $txt1 .= " world!" Now $txt1 contains "Hello world!"
  • 39.
    Concatenation ◼ Use aperiod to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP
  • 40.
    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””; Print $heading; ?> “Computer Science”
  • 41.
    PHP Integer ◼ Aninteger must have at least one digit ◼ An integer must not have a decimal point ◼ An integer can be either positive or negative ◼ Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based ◼ - prefixed with 0x) or octal (8-based - prefixed with 0) ◼ In the following example $x is an integer. The PHP var_dump() function retur ◼ Ex: <?php $x = 5985; var_dump($x); ?> ns the data type and value
  • 42.
    PHP Float float (floatingpoint number) is a number with a decimal point or a number in exponential form. In the following example $x is a float. The PHP var_dump() function returns the data type and value: Ex: <?php $x = 10.365; var_dump($x); ?>
  • 43.
    PHP Boolean ◼ ABoolean represents two possible states: TRUE or FALSE. ◼ Ex: ◼ $x = true; ◼ $y = false;
  • 44.
    PHP Array ◼ Inthe following example $cars is an array. The PHP var_dump() function returns the data type and value: ◼ Ex: ◼ <?php ◼ $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ◼ ?>
  • 45.
    PHP Operators ◼ Operatorsare used to perform operations on variables and values. ◼ PHP divides the operators in the following groups: ◼ Arithmetic operators ◼ Assignment operators ◼ Comparison operators ◼ Increment/Decrement operators ◼ Logical operators ◼ String operators ◼ Array operators ◼ Conditional assignment operators
  • 46.
    Arithmetic Operations ◼ $a- $b // subtraction ◼ $a * $b // multiplication ◼ $a / $b // division ◼ $a += 5 // $a = $a+5 Also works for *= and /= ◼ Refer Link : W3school.com <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h1>$total</h1>”; // total is 45 ?>
  • 47.
    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). ▪ Example if/else if/else statement: 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; }
  • 48.
    If ... Else... ◼If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> No THEN in PHP
  • 49.
    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.
  • 50.
    Date() function ◼ Formats •d - Represents the day of the month (01 to 31) • m - Represents a month (01 to 12) • Y - Represents a year (in four digits) • 1 - Represents the day of the week • h - 12-hour format of an hour with leading zeros (01 to 12) • i - Minutes with leading zeros (00 to 59) • s - Seconds with leading zeros (00 to 59) • a - Lowercase Ante meridiem and Post meridiem (am or pm)
  • 51.
    Date Display $datedisplay=date(“yyyy/m/d”); Print $datedisplay; #If the date is April 25, 2025 # It would display as 2025/25/3 2025/25/3 $datedisplay=date(“l, F J, Y”); Print $datedisplay; # If the date is March 25th , 2025 # Tuesday, March 25, 2025 Tuesday, March 25, 2025
  • 52.
    Month, Day &Date Format Symbols M Jan F January m 01 n 1 Day of Month d 01 Day of Month J 1 Day of Week l Monday Day of Week D Mon
  • 53.
    Arrays ◼ In PHP,there are three kind of arrays: > Numeric array - An array with a numeric index > Associative array - An array where each ID key is associated with a value > Multidimensional array - An array containing one or more arrays
  • 54.
    Numeric Arrays ◼ Anumeric array stores each array element with a numeric index. ◼ There are two methods to create a numeric array.
  • 55.
    Numeric Arrays ◼In thefollowing example the index is automatically assigned (the index starts at 0): ◼In the following example we assign the index manually:
  • 56.
    Numeric Arrays ◼In thefollowing example you access the variable values by referring to the array name and index: ◼The code above will output:
  • 57.
    Associative Arrays ◼ Withan associative array, each ID key is associated with a value. ◼ When storing data about specific named values, a numerical array is not always the best way to do it. ◼ With associative arrays we can use the values as keys and assign values to them.
  • 58.
    Associative Arrays ◼In thisexample we use an array to assign ages to the different persons: ◼This example is the same as the one above, but shows a different way of creating the array:
  • 59.
  • 60.
    Multidimensional Arrays ▪ Multi-dimensionalarrays are such arrays that store another array at each index instead of a single element. ▪ We can define multi-dimensional arrays as an array of arrays. ▪ Every element in this array can be an array and they can also hold other sub- arrays . ▪ Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions. Ex: $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); The two-dimensional $cars array contains four arrays, and it has two indices: row and column.
  • 61.
  • 62.
  • 63.
  • 64.
    Add array item: Toadd items to an existing array, you can use the bracket [] syntax. <pre> <?php $fruits = array("Apple", "Banana", "Cherry"); $fruits[] = "Orange"; var_dump($fruits); ?> </pre> array(4) { [0]=> string(5) "Apple" [1]=> string(6) "Banana" [2]=> string(6) "Cherry" [3]=> string(6) "Orange" }
  • 65.
    Update Array Item 1.In Numeric Array : To update an existing array item, you can refer to the index number for indexed arrays, and the key name for associative arrays. <?php $cars = array("Volvo", "BMW", "Toyota"); $cars[1] = "santro"; var_dump($cars); ?> //OUTPUT: array(3) { [0]=> string(5) "Volvo" [1]=> string(6) "santro" [2]=> string(6) "Toyota" }
  • 66.
    Update Array Itemconti.. In Associative Array :To update items from an associative array, use the key name. Prog: <body> <pre> <?php $cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964); $cars["year"] = 2024; var_dump($cars); ?> </pre> </body>
  • 67.
    Foreach loop toupdate array Items Iterating over arrays is done with the foreach loop. Syntax: foreach($array as $value) { // Statements to be executed } Program : <?php $colors = array("Red", "Green", "Blue","Yellow","Pink"); // Loop through count array foreach($colors as $value){ echo $value . "<br>"; } ?>
  • 68.
    Remove Array Item •To remove an existing item from an array, you can use the array_splice() function. • With the array_splice() function you specify the index (where to start) and how many items you want to delete. • We can also use the unset() function to delete existing array items. • The unset() function does not re-arrange the indexes, meaning that after deletion the array will no longer contain the missing indexes. <pre> <?php $cars = array("Volvo", "BMW", "Toyota"); unset($cars[1]); var_dump($cars); ?> </pre> array(2) { [0]=> string(5) "Volvo" [2]=> string(6) "Toyota" }
  • 69.
    Function PHP functions areblocks of reusable code that perform specific tasks. Functions help organize code and make it easier to maintain and debug PHP Web applications. Syntax: function function_name() { //Statement to be executed } Ex: <?php functionwelcMsg() { echo "Hello welcome!"; } welcMsg(); ?>
  • 70.
    Function Arguments In PHPFunction, arguments may be used to transfer information to functions. A variable is the same as an argument. Arguments are listed within parentheses after the function name. You can add as many arguments as you want; just use a comma to divide them. <?php functionStudentsName($firstname) { echo "$firstname<br>"; } StudentsName("Janani"); StudentsName("Helen"); StudentsName("Stella"); StudentsName("Kamal"); StudentsName("Babu"); ?>
  • 71.
    Passing Arguments ByReference Arguments are generally passed by value in PHP, which ensures that the function uses a copy of the value and the variable passed into the function cannot be modified. Changes to the argument modify the variable passed in when a function argument is passed by reference. The & operator is used to convert a function argument into a reference. <?php function addition(&$val) { $val += 10; } $number =5; addition($number); echo $number; ?> Output : 15
  • 72.
    PHP Functions -Returning Value This means the PHP Function can be called by its name, and when executing the function, it will return some value. <?php function circle($r){ return 3.14*$r*$r; } echo "Area of circle is: ".circle(3); ?>
  • 73.
    Class • A classis a definition of the properties and methods of a particular type of object • It includes the properties and functions that process the properties. • An object is the instance of its class. It is characterized by the properties and functions defined in the class. • Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. • A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. • A class may contain its own constants, variables (called "properties"), and functions (called "methods"). • Ex: <?php class SimpleClass { // property declaration public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; }} ?>
  • 74.
    PHP - The$this Keyword The $this keyword refers to the current object, and is only available inside methods. There are two ways: 1. Inside the class (by adding a set_name() method and use $this): 2. Outside the class (by directly changing the property value): Ex for Inside the class (by adding a set_name() method and use $this): <?php class Fruit { public $name; function set_name($name) { $this->name = $name; } } $apple = new Fruit(); $apple->set_name("Apple"); echo $apple->name; ?> Apple
  • 75.
    Outside the class(by directly changing the property value): <?php class Fruit { public $name; } $apple = new Fruit(); $apple->name = "Apple"; echo $apple->name; ?> Apple
  • 76.
    Defining an Objectin PHP : new To create an instance of a class, the new keyword must be used <?php class SimpleClass { } $instance = new SimpleClass(); var_dump($instance); // This can also be done with a variable: $className = 'SimpleClass'; $instance = new $className(); // new SimpleClass() var_dump($instance); ?> object(SimpleClass)#1 (0) { } object(SimpleClass)#2 (0) { }
  • 77.
    PHP - Forms •Accessto the HTTP POST and GET data is simple in PHP •The global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form>
  • 78.
    PHP Form Handling BYsuperglobals $_GET and $_POST
  • 79.
    PHP Forms -$_GET Function ◼ The built-in $_GET function is used to collect values from a form sent with method="get". ◼ Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max. 100 characters).
  • 80.
    PHP Forms -$_GET Function ◼The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array)
  • 81.
    PHP Forms -$_GET Function > When using method="get" in HTML forms, all variable names and values are displayed in the URL. > This method should not be used when sending passwords or other sensitive information! > However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. > The get method is not suitable for large variable values; the value cannot exceed 100 chars.
  • 82.
    PHP Forms -$_GET Function <html> <body> <form action="welcome_get.php" method="GET"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
  • 83.
    PHP Forms -$_POST Function > The built-in $_POST function is used to collect values from a form sent with method="post". > Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. > Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
  • 84.
    PHP Forms -$_POST Function And here is what the code of action.php might look like:
  • 85.
    2.Form Validation It willshow how to process PHP forms with security Proper validation of form data is important to protect your form from hackers and spammers Validation: Validate each input according to the specified rules: • Name: Make the field as required. It must contain only letters and whitespace. • E-mail: Make the field as required, It must contain a valid email address. • Gender: Make the field as required, It must select one option. • Mobile Number: Make the field as required, It must contain a valid mobile number format (e.g., 10 digits).
  • 86.
  • 87.
    1.Text Fields Name: <inputtype="text" name="name"> E-mail: <input type="text" name="email"> Website: <input type="text" name="website"> Comment: <textarea name="comment" rows="5" cols="40"></textarea> 2.Radio Buttons : Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other 3.The Form Element <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Here the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page The htmlspecialchars() function converts special characters into HTML entities. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page.
  • 88.
    Conti… <h2>PHP FormValidation Example</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website"> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <br><br> <input type="submit" name="submit" value="Submit"> </form>
  • 89.
    Conti.. <?php echo "<h2>Your Input:</h2>"; echo$name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
  • 90.
  • 91.
    How to validatea form data with PHP <?php // define variables and set to empty values $name = $email = $gender = $comment = $website = “ "; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
  • 92.
    <h2>PHP Form ValidationExample</h2> <form method="post" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?> "> Name: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website"> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <br><br> <input type="submit" name="submit" value="Submit"> </form>
  • 93.
    <?php echo "<h2>Your Input:</h2>"; echo$name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
  • 94.
    Conti.. To check whetherthe form has been submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been submitted - and it should be validated.
  • 95.
    Content Mgmt System(CMS): A content management system (CMS) is software that helps users create, manage, store, and modify their digital content. This system is a one-stop-shop to store content—such as apps, images, and websites—in a user-friendly interface that is customizable to an organization’s needs and their employees. CMS builds and manages the content for a brand’s website
  • 96.
    How does aCMS work? • To understand how a content management system works, let’s take a step back. A website that is manually run would require the individual or organization to code or write a static HTML file from scratch and upload it to the server for each web page. This requires significant time and energy and periodic updating that takes away precious resources from already busy organizations. • A way to avoid this complex work is to use a CMS platform. The system is already created on the back-end and front-end, while all the creator sees is a user-friendly interface that allows them to make necessary changes in a simplified manner. The CMS is built to enhance the customer experience for web content that is viewed online or on a mobile app.
  • 97.
    Examples of aCMS • WordPress: Originally was a web content management system that was built to publish blogs, but has extended into many other areas. The open source management system can be used for websites, professional portfolios, e-commerce stores and more. • Drupal: The open source CMS is used by many companies around the globe to build and maintain their websites. The user interface is easily accessible and allows you to create and publish unlimited content. • Squarespace: Square space is an all-in-one content management system, meaning with a single subscription the owner can do it all without needing third-party integrations. This is a popular CMS for small businesses online and in-store. • Joomla: This CMS is another open source system to build websites and online applications. It is SEO-friendly and features unlimited designs and built-in multilingual capabilities.
  • 98.
    WordPress • Many peoplechoose WordPress because it’s free, which is a huge advantage. • WordPress is easy to learn for nontechnical folks but also allows developers to customize code. You can start by setting up a simple website to publish content quickly and learn more as you go along. • Users of WordPress can select from two basic versions of the service. The first of these is the “hosted” version of WordPress, which is accessible at WordPress.com. This version allows users to launch a website that is hosted on WordPress’s own servers. it is often favored by non-technical users, who may wish to avoid the complexity of hosting a website on their own private server. As an additional benefit, the hosted version of WordPress is automatically updated to the latest version of the WordPress software, • For more advanced users, it is also possible to simply download the latest version of WordPress from WordPress.org. By selecting this option, the user must make their own arrangements to host the software either on their own private server or from a third-party hosting provider
  • 99.
    DRUPAL • Drupal (/ˈdruːpəl/)is a free and open-source web content management system (CMS) written in PHP • Drupal is content management software. It's used to make many of the websites and applications you use every day. • Written in PHP programming language, Drupal CMS is widely used for creating and managing websites and web applications. • Drupal is primarily a backend system (CMS) that manages content and workflows, but it can also be used with front-end frameworks for dynamic user experiences through decoupled or headless approaches. • Drupal is primarily a backend system (CMS) that manages content and workflows, but it can also be used with front-end frameworks for dynamic user experiences through decoupled or headless approaches.
  • 100.
    Include Files Include “opendb.php”; Include“closedb.php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: <hr SIZE=11 NOSHADE WIDTH=“100%”> <i>Copyright © 2008-2010 KSU </i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL: http://www.kent.edu</i></font><br>