Module 3A PHP
Module 3A PHP
Module 3A PHP
School of Engineering
Module III - Syllabus
MODULE III: PHP [L-10hrs.,P- 10hrs.]
• PHP: Introduction to server-side Development with PHP,
Arrays, and Superglobals Arrays, $GET and $ POST, Super
global Arrays, $_SERVER Array, $_Files Array, Reading/Writing
Files, PHP Classes and Objects, Object, Classes and Objects in
PHP, Object Oriented Design, Working with Databases, SQL,
Database APIs, Managing a MySQL Database. Accessing
MySQL in PHP
•
PHP Introduction
• PHP is a acronym for “PHP: Hypertext Preprocessor”
• PHP is a server-side scripting language and executed on the
server
• PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
• PHP is open source software and free to download.
• PHP was created by Rasmus Lerdorf in 1994 but appeared
in the market in 1995.
PHP Introduction
• PHP runs on different platforms (Windows, Linux, Unix,
etc.)
• PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
• PHP is FREE to download from the official PHP resource:
www.php.net
• PHP is easy to learn and runs efficiently on the server
side
PHP Introduction
Some info on MySQL which we will cover in the next...
•> MySQL is a database server
•> MySQL is ideal for both small and large applications
•> MySQL supports standard SQL
•> MySQL compiles on a number of platforms
•> MySQL is free to download and use
Why use PHP
• PHP is a server-side scripting language, which is used to design
the dynamic web applications with MySQL database.
• PHP supports several protocols such as HTTP, POP3, SNMP,
LDAP, IMAP, and many more.
• Using PHP language, you can control the user to access some
pages of your website.
• PHP can handle the forms, such as - collect the data from users
using forms, save it into the database, and return useful
information to the user. For example - Registration form
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 data through forms
• 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
PHP Syntax
Basic PHP Syntax
• PHP pages contain HTML with embedded code that does
"something”.
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>
<?php // Start
// PHP code goes here
?> //End
PHP Introduction
PHP Introduction
PHP code is executed on the server, and the result is returned to the
browser as plain HTML
PHP Getting Started
• To install PHP, we will suggest you to install AMP
(Apache, MySQL, PHP) software stack. There are
many AMP options available in the market that are
given below:
• WAMP for Windows
• LAMP for Linux
• MAMP for Mac
• SAMP for Solaris
• XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross
Platform: It includes some other components too such
as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.
PHP Hello World
Executing first PHP script
• First Install the Xampp software.
• Start Apache and MysQL modules.
• Go to Xampp htdocs
• Create the PHP script and save it using .php extension.
• Open the browser and type: localhost/first.php
PHP Hello World
// PHP files have extension ".php“ (first.php)
// Write the following code inside a notepad file and save it in
htdocs folder
PHP echo and print Statements
• Echo • Print
<?php <?php
$name="John"; $name="John";
echo $name; print $name;
//or //or
echo ($name); print ($name);
?> ?>
PHP Comments
RULES
• A variable name must start with a letter or an underscore "_“
not a number
• A variable name can only contain alpha-numeric characters,
underscores (a-z, A-Z, 0-9, and _ )
• A variable name should not contain spaces. If a variable name
is more than one word, it should be separated with an
underscore ($my_string) or with capitalization ($myString)
PHP Variables
// Defining new variables and printing their values
<html>
<body>
<?php
$txt = "Hello world!"; // defining variable
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x; Hello world!
5
echo "<br>";
10.5
echo $y;
?>
</body>
</html>
PHP Variables
PHP variables: local and global
<html>
<body> Notice: Undefined variable: x in C:\xampp\htdocs\
<? php first.php on line 9
$x = 5; // global scope Variable x inside function is:
Variable x outside function is: 5
function Test() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
Test();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
PHP Variables
PHP variables: local and global
<html>
<body> print('Variable x inside
<? php function is:'.$x);
$x=10;
function Test() {
$x=5;
echo "<p>Variable x inside function is: $x</p>";
}
Test();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html> Variable x inside function is: 5
Variable x outside function is: 10
PHP Variables
PHP variables: local and global
<html>
<body>
<? php
$x=5;
$y=6;
function Test() {
global $x,$y; //Access global variable
$x=$y+$x;
}
Test();
echo "<p>Sum of Number: $x</p>";
?>
</body>
</html> Sum of 2 numbers: 11
PHP Variables
PHP variables: static
Normally, when a function is completed/executed, all of its variables
are deleted. However, sometimes we want a local variable NOT to be
deleted. We need it for a further job.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
012
myTest();
myTest();
myTest();
?>
PHP Concatenation
<?php
int(5985)
$x = 5985;
var_dump($x);
?>
PHP float
A float (floating point number) is a number with a decimal point or
a number in exponential form.
Example
<?php
$x = 10.365;
var_dump($x);
?>
Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
PHP Array
An array stores multiple values in one single variable.
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars); array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW"
?> [2]=> string(6) "Toyota" }
NULL Value
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value
assigned to it. Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x); ?>
PHP Operators
•Arithmetic Operators
•Logical or Relational Operators
•Comparison Operators
•Conditional or Ternary Operators
•Assignment Operators
•Array Operators
•Increment/Decrement Operators
•String Operators
PHP Operators
8. string Operator
. = concatenation operator
.= =concatenating assignment operator
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
•if
•if-else
•if-else-if
•nested if
PHP Conditional statements
PHP If Statement
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
12 is less than 100
PHP Conditional statements
PHP If else Statement
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}
else{
echo "$num is odd number";
}
?>
12 is even number
PHP Conditional statements
PHP If-else-if Statement
<?php
$marks=69; else if ($marks>=80 && $mar
if ($marks<33){ ks<90) {
echo "fail"; echo "A grade";
} }
else if ($marks>=34 && $m else if ($marks>=90 && $mar
arks<50) { echo "D grad ks<100) { echo "A+ grade
e"; ";
} }
else if ($marks>=50 && $m else {
arks<65) { echo "C grade echo "Invalid input";
"; }
} ?>
else if ($marks>=65 && $m
B Grade
arks<80) { echo "B grad
e";
}
PHP Conditional statements
PHP Switch Statement
<?php
$favcolor = "red";
switch ($favcolor) {
case "red": echo "Your favourite color is red!"; break;
case "blue": echo "Your favourite color is blue!"; break;
default: echo “Wrong Choice ";
}
?>
PHP Loop
In PHP, we have the following loop types:
<?php <?php
$x = 1; $x = 1;
while($x <= 5)
do {
{
echo "The number is: $x echo "The number is: $x <br>";
<br>";
$x++;
$x++;
} } while ($x <= 5);
?>
?>
PHP Loop
PHP for Loop
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
PHP foreach Loop
?>
<?php
$colors = array("red", "green", "blue", "yellow");
Syntax Example
function functionname(){ <?php
//code to be executed function sayHello(){
echo "Hello PHP Functio
} n";
}
sayHello();//
calling function
?>
PHP Function Arguments
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old
<br/>";
}
sayHello("Sai",27); Hello Sai, you are 27 years old
sayHello("Vimal",29); Hello Vimal, you are 29 years old
Hello John, you are 23 years old
sayHello("John",23);
?>
PHP Function Arguments
}
$str = 'Hello ';
adder($str); Hello Call By Reference
echo $str;
?>
PHP Function Arguments
<?php
function cube($n){
return $n*$n*$n;
}
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
PHP Array
or
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
PHP Array
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
Two-dimensional Arrays
A two-dimensional array is an array of arrays
Two-dimensional Arrays
for ($row = 0; $row < 4; $row++)
Example
{
<?php echo "<p><b>Row number $row</b></p>";
$cars = array ( echo "<ul>";
array("Volvo",22,18), for ($col = 0; $col < 3; $col++)
array("BMW",15,13), {
array("Saab",5,2), echo "<li>".$cars[$row][$col]."</li>";
array("Land Rover",17,15) }
); echo "</ul>";
}
?>
Row number 0
•Volvo
•22
•18
CSE-367 Data Visualization 63
PHP Array
Sorting Arrays
• The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.
Example
<?php
echo $_SERVER['PHP_SELF’];/*Returns the filename of the currently executing script
echo "<br>";
echo $_SERVER['SERVER_NAME’];/*Returns the name of the host server (such as www.w3schools.com)
echo "<br>";
echo $_SERVER['HTTP_HOST’]; /*Host header from the current request
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>"; complete URL of the
current page
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>the path of the current script
PHP $_GET
The GET method is used to submit the
HTML form data. This data is collected by the
predefined $_GET variable for processing.
Example
<form method="POST" action="action.php" enctype="multipart/form-
data">
<input type="text" name="name"/>
<input type="file" name="file" id="file" />
<input type="submit" value="Send"/>
</form>
<?php
echo "<pre>";
print_r($_FILES); echo "</pre>"; //prints uploaded File's information
echo $_POST['name'];
?>
PHP File Handling
• File handling is an important part of any web application. You
often need to open and process a file for different tasks.
Manipulating Files
• PHP has several functions for creating, reading, uploading, and
editing files.
readfile() Function
• The readfile() function reads a file and writes it to the output
buffer.
PHP File Handling
<?php
echo readfile("Hai.txt");
?>
PHP File Handling
Open File - fopen()
• A better method to open files is with the fopen() function.
• This function gives you more options than the readfile() function.
$myfile = fopen(“Hai.txt", "r") or die("Unable to open file!");
x+ Creates a new file for read/write. Returns FALSE and an error if file already
exists
PHP Write to File - fwrite()
• The fwrite() function is used to write to a file.
• The first parameter of fwrite() contains the name of the
file to write to and the second parameter is the string to
be written.
<?php
$myfile = fopen("Haii.txt", "w") or
die(“Error!");
$txt = "Prabhu\n";
fwrite($myfile, $txt);
$txt = "Shankar\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
CSE-367 Data Visualization 79