Unit - 4 PHP

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

Unit-IV

PHP and AJAX


Contents
An introduction to PHP: PHP- Using PHP- Variables-
Program control- Built-in functions- Form Validation-
Regular Expressions - Cookies - Connecting to
Database.
Ajax Client Server Architecture-XML Http Request
Object
What is PHP?
PHP is an open-source, interpreted, and object-oriented scripting
language that can be executed at the server-side.

PHP is well suited for web development.


PHP
•PHP stands for Hypertext Preprocessor.
•PHP is an interpreted language, i.e., there is no need for compilation.
•PHP is faster than other scripting languages, for example, ASP and JSP.
•PHP is a server-side scripting language, which is used to manage the
dynamic content of the website.
•PHP can be embedded into HTML.
•PHP is an object-oriented language.
•PHP is an open-source scripting language.
•PHP is simple and easy to learn language.
Why use PHP
PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.
• It handles dynamic content, database as well as session tracking for the website.
• You can create sessions in PHP.
• It can access cookies variable and also set cookies.
• It helps to encrypt the data and apply validation.
• 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.
• As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn.
• 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.
Installing PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software
stack. It is available for all operating systems. 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
•FAMP for FreeBSD
•XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some
other components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.
PHP Syntax
A PHP script can be placed anywhere in the document. <!DOCTYPE html>
<html>
A PHP script starts with <?php and ends with ?> <body>

<?php <h1>My first PHP page</h1>


// PHP code goes here
?> <?php
echo "Hello World!";
?>
The default file extension for PHP files is ".php".
</body>
A PHP file normally contains HTML tags, and </html>
some PHP scripting code
PHP Comments
Single-line comments
<?php
// This is a single-line comment

# This is also a single-line comment


?>

Multiple line comment


<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable

<?php Rules for PHP variables


$txt = "Hello world!"; • A variable starts with the $ sign, followed by the name
$x = 5; of the variable
$y = 10.5; • 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)
<!DOCTYPE html>
Displaying Variables <html>
<!DOCTYPE html> <body>
<html>
<body> <?php
$txt = "PHP";
<?php echo "Let's Learn " . $txt . "!";
$txt = "PHP"; ?>
echo "Let's learn $txt!";
?> </body>
</html>
</body>
<?php
</html>
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP Variables Scope
PHP has three different variable scopes:
•local
•global Global Scope
•static A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function

<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
PHP The global Keyword PHP also stores all global variables in an
The global keyword is used to access a global array called $GLOBALS[index]. The index
variable from within a function. holds the name of the variable.

<?php <?php
$x = 5; $x = 5;
$y = 10; $y = 10;

function myTest() { function myTest() {


global $x, $y; $GLOBALS['y'] = $GLOBALS['x']
$y = $x + $y; + $GLOBALS['y'];
} }

myTest(); myTest();
echo $y; // outputs 15 echo $y; // outputs 15
?> ?>
Local Scope Variables

A variable declared within a function has a LOCAL SCOPE and can


only be accessed within that function

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted.
To do this, use the static keyword when you first declare the variable:

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it
can be used in expressions. echo can take multiple parameters (although such usage is
rare) while print can take one argument. echo is marginally faster than print
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
PHP Data Types
Variables can store data of different types, and different data types can
do different things.

PHP supports the following data types:


•String
•Integer
•Float (floating point numbers - also called double)
•Boolean
•Array $x = "Hello world!";//PHP String
•Object $x = 5985;//PHP Integer
•NULL $x = 10.365;//PHP float
•Resource $x = true;//PHP Boolean
$cars = array("Volvo","BMW","Toyota");//PHP arrays
$x = null;
PHP Object

• Classes and objects are the two main aspects of object-oriented


programming.
• A class is a template for objects, and an object is an instance of a
class.
• When the individual objects are created, they inherit all the properties
and behaviors from the class, but each object will have different
values for the properties.
• If you create a __construct() function, PHP will automatically call this
function when you create an object from a class.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
Output:
$myCar = new Car("black", "Volvo"); My car is a black Volvo!
echo $myCar -> message(); My car is a red Toyota!
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>
PHP Conditional Statements
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither
red, blue, nor green!";
}
?>
while (condition is true) { do {
code to be executed; code to be executed;
} } while (condition is true);

<?php <?php
$x = 1; $x = 1;

while($x <= 5) do {
{ echo "The number is: $x <br>";
echo "The number is: $x $x++;
<br>"; } while ($x <= 5);
$x++; ?>
}
?>
for (init counter; test counter;
increment counter) { foreach ($array as $value) {
code to be executed for each code to be executed;
iteration; }
}

<?php
<?php
$colors
for ($x = 0; $x <= 10; $x++) {
= array("red","green","blue",
echo "The number is: $x
"yellow");
<br>";
}
foreach ($colors as $value) {
?>
echo "$value <br>";
}
?>
PHP Functions
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from
within a script, to perform a specific task.

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own
functions.
•A function is a block of statements that can be used repeatedly in a
program.
•A function will not execute automatically when a page loads.
•A function will be executed by a call to the function.
Syntax: <?php
function functionName() { function birthyear($fname, $year) {
code to be executed; echo "$fname born in $year <br>";
} }

birthyear("Hege","1975");
<?php birthyear("Stale","1978");
function writeMsg() { birthyear("Kai Jim","1983");
echo "Hello world!"; ?>
}

writeMsg();
// call the function
?>
PHP is a Loosely Typed Language
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when
declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type
mismatches.

<?php <?php declare(strict_types=1);


function addNumbers(int $a, int // strict requirement
$b) {
return $a + $b; function addNumbers(int $a, int
} $b) {
echo addNumbers(5, "5 days"); return $a + $b;
// since strict is NOT enabled }
"5 days" is changed to int(5), echo addNumbers(5, "5 days");
and it will return 10 // since strict is enabled and "5
?> days" is not an integer, an error
will be thrown
?>
PHP Default Argument Value PHP Functions - Returning values
<?php declare(strict_types=1); <?php declare(strict_types=1);
// strict requirement // strict requirement
function setHeight(int $minheight = 50) function sum(int $x, int $y)
{ {
echo "The height is : $minheight <br>"; $z = $x + $y;
} return $z;
}
setHeight(350);
setHeight(); echo "5 + 10 = " . sum(5, 10) . "<br>";
// will use the default value of 50 echo "7 + 13 = " . sum(7, 13) . "<br>";
setHeight(135); echo "2 + 4 = " . sum(2, 4);
setHeight(80); ?>
?>
PHP Return Type Declarations

<?php declare(strict_types=1);
// strict requirement
function addNumbers(float $a, float $b) : float
{
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
PHP Arrays
In PHP, the array() function is used to create an array:

In PHP, there are three types of arrays:


• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays

The count() Function


The count() function is used to return the length (the number of elements) of an
array
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
PHP Indexed Arrays
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>

<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to
them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
PHP - Two-dimensional Arrays

Creating arrays <?php


$cars = array ( for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
array("Volvo",22,18), echo "<ul>";
array("BMW",15,13), for ($col = 0; $col < 3; $col++) {
array("Saab",5,2), echo "<li>".$cars[$row][$col]."</li>";
array("Land Rover",17,15) }
); echo "</ul>";
}
?>
PHP Sorting Arrays

sort() - sort arrays in ascending order


rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key

<?php <?php
$cars $age
= array("Volvo", "BMW", "Toyota"); = array("Ben"=>"37", "Peter"=
sort($cars); >"35", "Joe"=>"43");
?> asort($age);
?>
PHP Strings
implode(separator,array) $arr = array('Hello','World!','Beautiful','Day!');
Returns a string from elements of an echo implode(" ",$arr);
array //Hello World! Beautiful Day!
str_split(string,length) $arr=str_split("Hello");
//length-optional for($x = 0; $x <count($arr); $x++) {
splits a string into an array. echo $arr[$x];
echo "<br>";
}

str_word_count(string,return,char) echo str_word_count("Hello world!");//2


counts the number of words in a string.
strcmp(string1,string2) echo strcmp("Hello world!","Hello world!");//0
compares two strings.
This function returns:0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
strlen(string) echo strlen("Hello");//5
returns the length of a string.
strpos(string,find,start) echo strpos("I know php, I like php
finds the position of the first occurrence of too!","php");//7
a string inside another string.
strrev(string) echo strrev("Hello World!");
reverses a string. //!dlroW olleH
substr(string,start,length) echo substr("Hello world",6);
Returns the extracted part of a string, or //world
FALSE on failure, or an empty string
strtolower(string) echo strtolower("HELLO WORLD.");
Returns the the lowercased string //hello world.
explode(separator,string,limit) $str = "Hello world. It's a beautiful day.";
breaks a string into an array. print_r (explode(" ",$str));
//Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4]
=> beautiful [5] => day. )
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2
=> value2, key3 => value3, ...)).

Both GET and POST are treated as $_GET and $_POST. These are
superglobals, which means that they are always accessible, regardless
of scope - and you can access them from any function, class or file
without having to do anything special.

$_GET is an array of variables passed to the current script via the URL
parameters.
$_POST is an array of variables passed to the current script via the
HTTP POST method.
GET POST
Can be bookmarked Cannot be bookmarked
Parameters remain in browser history Parameters are not saved in browser history
When sending data, the GET method adds No restrictions
the data to the URL; and the length of a URL
is limited
GET is less secure compared to POST POST is a little safer than GET because the
because data sent is part of the URL parameters are not stored in browser
history or in web server logs
Never use GET when sending passwords or
other sensitive information!
Data is visible to everyone in the URL Data is not displayed in the URL
<html> welcome_get.php
<body>
<html>
<form action="welcome_get.php <body>
" method="get">
Name: <input type="text" name Welcome <?php echo $_GET["name"]; ?
="name"><br> ><br>
E- Your email address is: <?php echo
mail: <input type="text" name $_GET["email"]; ?>
="email"><br>
<input type="submit"> </body>
</form> </html>
</body>
</html>
PHP Regular Expressions
What is a Regular Expression?
• A regular expression is a sequence of characters that forms a search
pattern. When you search for data in a text, you can use this search
pattern to describe what you are searching for.
• A regular expression can be a single character, or a more complicated
pattern.
• Regular expressions can be used to perform all types of text search
and text replace operations.

Syntax
In PHP, regular expressions are strings composed of delimiters, a
pattern and optional modifiers.
$exp = "/welcome/i";
Regular Expression Functions
Function Description

preg_match() Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() Returns the number of times the pattern was found in the string,
which may also be 0

preg_replace() Returns a new string where matched patterns have been


replaced with another string
<?php <?php
$str = "Welcome to PHP World"; $str = "Welcome to Java World";
$pattern = "/PHP/i"; $pattern = "/Java/i";
echo preg_match($pattern, $str); echo preg_replace($pattern, "PHP", $str);
?> ?>
Output: 1 Output: Welcome to PHP World

<?php
$str = "The rain in SPAIN falls mainly on the
plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
?>
Output: 4
Regular Expression Modifiers-Modifiers can change how a search is performed.
Modifier Description
i Performs a case-insensitive search
m Performs a multiline search
u Enables correct matching of UTF-8 encoded patterns

Regular Expression Patterns - Brackets are used to find a range of characters

Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find one character from the range 0 to 9
Metacharacters
Metacharacters are characters with a special meaning

Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|
fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or at the end
of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers Quantifiers define quantities

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{x} Matches any string that contains a sequence of X n's

n{x,y} Matches any string that contains a sequence of X to Y n's

n{x,} Matches any string that contains a sequence of at least X n's


Form Validation
The first thing we will do is to pass all variables through PHP's
htmlspecialchars() function.
1. When we use the htmlspecialchars() function; then if a user tries to
submit the following in a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as
HTML escaped code, like this:
&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;
2. Strip unnecessary characters (extra space, tab, newline) from the
user input data (with the PHP trim() function)
3. Remove backslashes (\) from the user input data (with the PHP
stripslashes() function)
function cleaninput($input)
{
foreach($input as $key=>$value)
{
$data=trim($value);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $input;
} }

if(isset($_POST["submit-btn"]))
{
$cleandata=cleaninput($_POST);
$errormsg=validateinput($cleandata);
}
<form action="sample1.php" method="post">

<div>
<label> Enter name:</label>
<input type="text" name="usr">
<div style="color:red;"><?php echo $errormsg["usr"]; ?></div>
</div>

<div>
<label>Enter Email:</label>
<input type="text" name="email">
<div style="color:red;"><?php echo $errormsg["email"]; ?></div>
</div>

<div>
<label>Enter password:</label>
<input type="password" name="pwd">
<div style="color:red;"><?php echo $errormsg["pwd"]; ?></div>
</div>

<input type="submit" value="Register" name="submit-btn">

</form>
function validateinput($cleandata)
{
$error=array();
foreach($cleandata as $key=>$value){
switch($key){
case "usr":
if(empty($value))
$error["usr"]="*Name cannot be empty";
break;
case "email":
if(!filter_var($value,FILTER_VALIDATE_EMAIL))
$error["email"]="*email is not valid";
break;
case "pwd":
$pattern="/\d+$/i";
if(preg_match($value,$pattern)==0)
$error["pwd"]="*Password should have atleast one number";
break;}}
return $error;
}
PHP- MYSQL database Connectivity
PHP 5 and later can work with a MySQL database using:
•MySQLi extension (the "i" stands for improved)
•PDO (PHP Data Objects)

To Connect With the Database


<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Connecting with Database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

Creating Table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
Inserting data in the table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Selecting data
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";}
Where clause

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not
set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>
Modify a Cookie Value
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>
Delete a Cookie

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

You might also like