0% found this document useful (0 votes)
6 views

PHP-2

Uploaded by

Abadullah Hamidi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PHP-2

Uploaded by

Abadullah Hamidi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

PHP

PHP
7 Introduction
PHP code is executed on the server.
What You Should Already Know
Before you continue you should have a basic understanding of the following:
• HTML
• CSS
• JavaScript
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
PHP is an amazing and popular language!
It is powerful enough to be at the core of the biggest blogging system on the web
(WordPress)!
It is deep enough to run the largest social network (Facebook)!
It is also easy enough to be a beginner's first server side language!
PHP
7 Introduction
What is a PHP File? Why PHP?
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 runs on various
PHP files have extension ".php“ platforms (Windows, Linux, Unix,
Mac OS X, etc.)

What Can PHP Do? • PHP is compatible with almost


all servers used today (Apache,
PHP can generate dynamic page content IIS, etc.)
PHP can create, open, read, write, delete, and close files on the• PHP supports a wide range of
server databases
PHP can collect form data • PHP is free. Download it from
PHP can send and receive cookies the official PHP
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
How To use PHP

Use a Web Host With PHP Set Up PHP on Your Own


What Do you
Support PC
Need?
If your server has activated support for PHP • However, if your server does
To start using PHP, you can: you do not need to do anything. not support PHP, you must:
• Find a web host with PHP and
MySQL support Just create some .php files, place them in • install a web server
• your web directory, and the server will • install PHP
Install a web server on your
own PC, and then install PHP automatically parse them for you. • install a database, such as
and MySQL You do not need to compile anything or install MySQL
any extra tools.
Because PHP is free, most web hosts offer
PHP support
PHP 7 Syntax
A PHP script is executed on the server, and the plain HTML
result is sent back to the browser.
<!DOCTYPE html>
<html>
Basic PHP Syntax <body>
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
<h1>My first PHP page</h1
<?php
// PHP code goes here <?php
?> echo "Hello World!";
?>
The default file extension for PHP files is " .php".
A PHP file normally contains HTML tags, and some PHP scripting
code. </body>
Below, we have an example of a simple PHP file, with a PHP </html>
script that uses a built-in PHP function " echo" to output the text
"Hello World!" on a web page:
Note: PHP statements end with a semicolon (;).
PHP 7 Syntax
PHP Case Sensitivity However; all variable names are case-sensitive.
In the example below, only the first statement
In PHP, NO keywords (e.g. if, else, while, echo, will display the value of the $color variable
etc.), classes, functions, and user-defined functions are (this is because $color, $COLOR,
case-sensitive. and $coLOR are treated as three different
In the example below, all three echo statements below variables)
are legal (and equal)
<!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <body>
<body>
<?php
<?php $color = "red";
ECHO "Hello World!<br>"; echo "My car is " .
echo "Hello World!<br>"; $color . "<br>";
EcHo "Hello World!<br>"; echo "My house is " .
?> $COLOR . "<br>";
echo "My boat is " .
</body> $coLOR . "<br>";
</html> ?>
PHP 7 Variables
Variables are "containers" for storing information. Output Variables
Creating (Declaring) PHP Variables The PHP echo statement is often used to output
In PHP, a variable starts with the $ sign, followed by the data to the screen.
The following example will show how to output
name of the variable: text and a variable:\
Example
<?php
<?php
$txt = "W3Schools.com";
$txt = "Hello world!";
echo "I love $txt!";
$x = 5;
?>
$y = 10.5;
?>
The following example will produce the
After the execution of the statements above, the variable $txt will hold same output as the example above:
the value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around <?php
the value. $txt = “W3Schools.com";
Note: Unlike other programming languages, PHP has no command for
echo "I love " . $txt . "!";
declaring a variable. It is created the moment you first assign a value to it.
Think of variables as containers for storing data. ?>
PHP 7 Variables
PHP is a Loosely Typed Language Global and Local Scope
In the example above, notice that we did not have to tell PHP A variable declared outside a function has a
which data type the variable is. GLOBAL SCOPE and can only be accessed
PHP automatically associates a data type to the variable, outside a function:
depending on its value. Since the data types are not set in a
strict sense, you can do things like adding a string to an <?php
integer without causing an error. $x = 5; // global scope

PHP Variables Scope function myTest() {


In PHP, variables can be declared anywhere in the // using x inside this function
script. will generate an error
The scope of a variable is the part of the script where echo "<p>Variable x inside
the variable can be referenced/used. function is: $x</p>";
PHP has three different variable scopes: }
• local myTest();
• global
• static echo "<p>Variable x outside
function is: $x</p>";
?>
PHP 7 Variables
A variable declared within a function has a PHP The global Keyword
LOCAL SCOPE and can only be accessed The global keyword is used to access a global
within that function: variable from within a function.
To do this, use the global keyword before the
<?php variables (inside the function):
function myTest() {
$x = 5; // local scope <?php
echo "<p>Variable x inside $x = 5;
function is: $x</p>"; $y = 10;
}
myTest(); function myTest() {
global $x, $y;
// using x outside the function
will generate an error $y = $x + $y;
echo "<p>Variable x outside }
function is: $x</p>";
?> myTest();
echo $y; // outputs 15
?>
PHP 7 Variables

<?php
PHP also stores all global variables in an $x = 5;
array called $GLOBALS[index]. $y = 10;
The index holds the name of the
variable. This array is also accessible function myTest() {
$GLOBALS['y']
from within functions and can be used to
= $GLOBALS['x']
update global variables directly. + $GLOBALS['y'];
The example above can be rewritten like }
this:
myTest();
echo $y; // outputs 15
?>
PHP 7 echo and print
Statements
The PHP echo Statement
In PHP there are two basic ways to get The echo statement can be used with or without
output: echo and print. parentheses: echo or echo().
Display Text
In this chapter we use echo (and print) in The following example shows how to output text with
almost every example. So, this chapter contains the echo command (notice that the text can contain
a little more info about those two output HTML markup):
statements <?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
PHP echo and print Statements echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made
echo and print are more or less the same. ", "with multiple parameters.";
They are both used to output data to the ?> <?php
screen. $txt1 = "Learn PHP";
The differences are small: echo has no return $txt2 = "W3Schools.com";
value while print has a return value of 1 so it $x = 5;
$y = 4;
can be used in expressions. echo can take
multiple parameters (although such usage is echo "<h2>" . $txt1 . "</h2>";
rare) while print can take one echo "Study PHP at " .
$txt2 . "<br>";
argument. echo is marginally faster than print. echo $x + $y;
PHP 7 echo and print
Statements

The PHP print Statement Display Variables


The following example shows how to output
The print statement can be used with or text and variables with the print statement:
without parentheses: print or print().
Display Text
<?php
The following example shows how to output text
with the print command (notice that the text $txt1 = "Learn PHP";
can contain HTML markup): $txt2 = "W3Schools.com";
$x = 5;
$y = 4;
<?php
print "<h2>PHP is Fun!</h2>"; print "<h2>" . $txt1
print "Hello world!<br>"; . "</h2>";
print "I'm about to learn print "Study PHP at " .
PHP!"; $txt2 . "<br>";
?> print $x + $y;
?>
PHP 7 Data
Types

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
• Object
• NULL
• Resource
PHP 7 STRINGS
A string is a sequence of characters, like "Hello 2-Count The Number of Words in a
world!". String

The PHP str_word_count() function counts the number of


PHP String Functions words in a string:
In this chapter we will look at some commonly
used functions to manipulate strings. <?php
1-Get The Length of a String echo str_word_count("Hello
world!"); // outputs 2
The PHP strlen() function returns the length of a string.
?>
The example below returns the length of the string "Hello world!“
Exmaple 3-Reverse a String
The PHP strrev() function reverses a string:
<?php
echo strlen("Hello world!"); // <?php
outputs 12 echo strrev("Hello
?> world!"); // outputs !dlrow
olleH
?>
PHP 7 STRINGS
4-Search For a Specific Text Within a 5-Replace Text Within a String
String
The PHP str_replace() function replaces some
The PHP strpos() function searches for a specific text characters with some other characters in a string.
within a string. The example below replaces the text "world" with
If a match is found, the function returns the character “Ahmad":
position of the first match. If no match is found, it will return
FALSE.
The example below searches for the text "world" in the <?php
string "Hello world!":
echo str_replace("world", "Ahmad", "H
ello world!"); // outputs Hello
<?php
Ahmad!
echo strpos("Hello
?>
world!", "world"); // outputs 6
?>
PHP 7
CONSTANTS
Constants are like variables except that once they are
defined they cannot be changed or undefined. Examples
PHP Constants <?php
A constant is an identifier (name) for a simple value. The define("GREETING", "Welcome to
value cannot be changed during the script. W3Schools.com!");
A valid constant name starts with a letter or underscore
echo GREETING;
(no $ sign before the constant name).
Note: Unlike variables, constants are automatically global ?>
across the entire script.
Create a PHP Constant Examples of case-sensitive
To create a constant, use the define() function.
Syntax <?php
define(name, value, case-insensitive) define("GREETING", "Welcome to
Parameters: W3Schools.com!");
•name: Specifies the name of the constant
•value: Specifies the value of the constant
echo GREETING;
•case-insensitive: Specifies whether the constant name should ?>
be case-insensitive. Default is false
The example below creates a constant with a case-
sensitive name:
PHP 7
CONSTANTS
Constants are Global
PHP7 Constant Arrays Constants are automatically global and can
In PHP7, you can create a Array constant using be used across the entire script.
the define() function. The example below uses a constant inside
The example below creates an Array constant: a function, even if it is defined outside
the function:

<?php
<?php define("GREETING", "Welcome to
define("cars", [ W3Schools.com!");
"Alfa Romeo",
"BMW", function myTest() {
"Toyota" echo GREETING;
]); }
echo cars[0];
?> myTest();
?>
PHP 7 Data Operators
PHP Operators
String operators
Operators are used to perform
operations on variables and
values. Operator Name Example Result
PHP divides the operators in the
following groups: . Concatenatio
n
$txt1 . $txt2 Concatenatio
n of $txt1 and
• Arithmetic operators $txt2
• Assignment operators
• Comparison operators .= Concatenatio $txt1 .= $txt2 Appends
n assignment $txt2 to $txt1
• Increment/Decrement
operators
• Logical operators
• String operators
• Array operators
• Conditional assignment
operators
PHP 7 Data
Operators..
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result


== Equal $x == $y Returns true if $x is equal to
$y

=== Identical $x === $y Returns true if $x is equal


to $y, and they are of the
same type
!= Not equal $x != $y Returns true if $x is not
equal to $y
<> Not equal $x <> $y Returns true if $x is not
equal to $y
!== Not identical $x !== $y Returns true if $x is not
equal to $y, or they are
not of the same type
PHP 7 Data
Types

Operator Name Example Result

> Greater than $x > $y Returns true if $x is greater


than $y

< Less than $x < $y Returns true if $x is less than


$y

>= Greater than or equal to $x >= $y Returns true if $x is greater


than or equal to $y

<= Less than or equal to $x <= $y Returns true if $x is less than


or equal to $y

<=> Spaceship $x <=> $y Returns an integer less than,


equal to, or greater than zero,
depending on if $x is less
than, equal to, or greater than
$y. Introduced in PHP 7.
PHP 7 if...else...elseif Statements
Conditional statements are used to perform different PHP - The if
actions based on different conditions.
Statement
The if statement executes some code if one
condition is true.
PHP Conditional Statements
Very often when you write code, you want to perform different Syntax
actions for different conditions. You can use conditional statements if (condition) {
in your code to do this. code to be executed if condition
In PHP we have the following conditional statements: is true;
•if statement - executes some code if one condition is true }
The example below will output "Have a good
•if...else statement - executes some code if a condition is day!" if the current time (HOUR) is less than
true and another code if that condition is false 20:
•if...elseif...else statement - executes different codes
for more than two conditions
•switch statement - selects one of many blocks of code to be Example
executed <?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>
PHP 7 if...else...elseif Statements
PHP - The if...else Statement PHP - The if...elseif...else Statement
The if...else statement executes some code if a condition The if...elseif...else statement executes different codes for more
is true and another code if that condition is false. than two conditions.

Syntax Syntax
if (condition) { if (condition) {
code to be executed if condition is true; code to be executed if this condition is true;
} else { } elseif (condition) {
code to be executed if condition is false; code to be executed if first condition is false and this
} condition is true;
} else {
The example below will output "Have a good day!" if the code to be executed if all conditions are false;
current time is less than 20, and "Have a good night!" }
otherwise:
Example
<?php
Example
$t = date("H");
<?php
$t = date("H");
if ($t < "10") {
if ($t < "20") { echo "Have a good morning!";
echo "Have a good day!"; } elseif ($t < "20") {
} else { echo "Have a good day!";
echo "Have a good night!"; } else {
} echo "Have a good night!";
?> } ?>
PHP 7 switch Statement
The switch statement is used to perform This is how it works: First we have a single expression n (most
different actions based on different often a variable), that is evaluated once. The value of the
expression is then compared with the values for each case in
conditions. the structure. If there is a match, the block of code associated
with that case is executed. Use break to prevent the code
from running into the next case automatically.
The PHP switch Statement The default statement is used if no match is found.
Use the switch statement to select one of many blocks
of code to be executed. Example
Syntax <?php
switch (n) { $favcolor = "red";
case label1:
code to be executed if n=label1; switch ($favcolor) {
case "red":
break;
echo "Your favorite color is red!";
case label2:
break;
code to be executed if n=label2;
case "blue":
break; echo "Your favorite color is blue!";
case label3: break;
code to be executed if n=label3; case "green":
break; echo "Your favorite color is green!";
... break;
default: default:
code to be executed if n is different from all labels; echo "Your favorite color is neither red, blue,
} green!";
} ?>
PHP Loops
PHP while loops execute a block of code The PHP while Loop
while the specified condition is true. The while loop executes a block of code as long as the

PHP Loops specified condition is true.


Syntax
Often when you write code, you want the same while (condition is true) {
block of code to run over and over again in a row. code to be executed;
Instead of adding several almost equal code-lines }
in a script, we can use loops to perform a task like
this. The example below first sets a variable $x to 1 ($x =
In PHP, we have the following looping statements: 1). Then, the while loop will continue to run as long as
•while - loops through a block of code as long as $x is less than, or equal to 5 ($x <= 5). $x will increase
by 1 each time the loop runs ($x++):
the specified condition is true
•do...while - loops through a block of code once,
and then repeats the loop as long as the specified Example
condition is true <?php
•for - loops through a block of code a specified $x = 1;
number of times
•foreach - loops through a block of code for each while($x <= 5) {
element in an array echo "The number is: $x <br>";
$x++;
}
?>
PHP Loops…
PHP for loops execute a block of code a specified
number of times.
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.
The PHP for Loop
The for loop is used when you know in advance how many times Syntax
the script should run. foreach ($array as $value) {
code to be executed;
Syntax }
for (init counter; test counter; increment counter) {
For every loop iteration, the value of the current array
code to be executed;
element is assigned to $value and the array pointer is
}
moved by one, until it reaches the last array element.
Parameters: The following example demonstrates a loop that will output
•init counter: Initialize the loop counter value the values of the given array ($colors):
•test counter: Evaluated for each loop iteration. If it evaluates
to TRUE, the loop continues. If it evaluates to FALSE, the loop
ends.
•increment counter: Increases the loop counter value
Example
The example below displays the numbers from 0 to 10:
<?php
$colors
= array("red", "green", "blue", "yellow");
Example
<?php
for ($x = 0; $x <= 10; $x++) { foreach ($colors as $value) {
echo "The number is: $x <br>"; echo "$value <br>";
} }
?>
PHP Function
The real power of PHP comes from its functions; it has
more than 1000 built-in functions.

PHP User Defined Functions In the example below, we create a function


Besides the built-in PHP functions, we can create our named "writeMsg()". The opening curly brace
own functions.
A function is a block of statements that can be used
( { ) indicates the beginning of the function
repeatedly in a program. code and the closing curly brace ( } ) indicates
A function will not execute immediately when a page the end of the function. The function outputs
loads. "Hello world!". To call the function, just write its
A function will be executed by a call to the function. name:
Create a User Defined Function in PHP
A user-defined function declaration starts with the
Example
word function:
<?php
Syntax function writeMsg() {
function functionName() {
echo "Hello world!";
code to be executed;
} }
Note: A function name can start with a letter or
underscore (not a number). writeMsg(); // call the function
Tip: Give the function a name that reflects what the
function does!
?>
Function names are NOT case-sensitive.
PHP Function..
The following example has a function with two argument
PHP Function Arguments
Information can be passed to functions through arguments. An
($fname and $year):
argument is just like a variable.
Example
Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just <?php
separate them with a comma. function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
The following example has a function with one argument }
($fname). When the familyName() function is called, we also
pass along a name (e.g. Jani), and the name is used inside the familyName("Hege", "1975");
function, which outputs several different first names, but an familyName("Stale", "1978");
equal last name: familyName("Kai Jim", "1983"); ?>

Example
In the following example we try to add a number and a string
<?php with without the strict requirement:
function familyName($fname) {
echo "$fname Refsnes.<br>"; Example
} <?php
function addNumbers(int $a, int $b) {
familyName("Jani"); return $a + $b;
familyName("Hege");
familyName("Stale");
}
familyName("Kai Jim"); echo addNumbers(5, "5 days");
familyName("Borge"); ?> // since strict is NOT enabled "5 days" is
changed to int(5), and it will return 10
?>
PHP Function..
In the following example we try to add a number and a
string with with the strict requirement: The following example has a function with two argument

($fname and $year):


Example
Example <?php
<?php declare(strict_types=1); // strict function familyName($fname, $year) {
requirement echo "$fname Refsnes. Born in $year <br>";
}
function addNumbers(int $a, int $b) {
familyName("Hege", "1975");
return $a + $b;
familyName("Stale", "1978");
} familyName("Kai Jim", "1983"); ?>
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not
an integer, an error will be thrown In the following example we try to add a number and a string
?> with without the strict requirement:
To specify strict we need to Example
set declare(strict_types=1);. This must be the on the <?php
very first line of the PHP file. Declaring strict specifies that function addNumbers(int $a, int $b) {
function calls made in that file must strictly adhere to the return $a + $b;
specified data types
}
The strict declaration can make code easier to read, and
echo addNumbers(5, "5 days");
it forces things to be used in the intended way.
Going forward in this tutorial, we will use
// since strict is NOT enabled "5 days" is
the strict requirement. changed to int(5), and it will return 10
?>
PHP Array
What is an Array?
An array is a special variable, which can hold more
than one value at a time.
If you have a list of items (a list of car names, for
example), storing the cars in single variables could
look like this: Create an Array in
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
PHP
However, what if you want to loop through the cars In PHP, the array() function is used to
and find a specific one? And what if you had not 3 create an array:
cars, but 300?
The solution is to create an array! array();
An array can hold many values under a single name, In PHP, there are three types of arrays:
and you can access the values by referring to an 1. Indexed arrays - Arrays with a numeric index
index number. 2. Associative arrays - Arrays with named keys
An array stores multiple values in one single 3. Multidimensional arrays - Arrays containing
variable: one or more arrays
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " .
$cars[1] . " and " . $cars[2] . "."; ?>
PHP Array…
PHP Indexed Arrays Get The Length of an Array - The count()
There are two ways to create indexed arrays: Function
The index can be assigned automatically The count() function is used to return the length (the number
(index always starts at 0), like this: of elements) of an array:
$cars = array("Volvo", "BMW",
"Toyota"); Example
or the index can be assigned manually: <?php
$cars = array("Volvo", "BMW", "Toyota");
$cars[0] = "Volvo"; echo count($cars);
$cars[1] = "BMW"; ?>
$cars[2] = "Toyota";
The following example creates an indexed
array named $cars, assigns three elements to Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could
it, and then prints a text containing the array use a for loop, like this:
values:
Example Example
<?php <?php
$cars $cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
= array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . for($x = 0; $x < $arrlength; $x++) {
$cars[1] . " and " . $cars[2] . "."; echo $cars[$x];
echo "<br>";
?> }
PHP Array…
PHP Associative Arrays
Associative arrays are arrays that use named
keys that you assign to them. Loop Through an Associative
There are two ways to create an associative
array: Array
To loop through and print all the values of an associative
$age = array("Peter"=>"35", array, you could use a foreach loop, like this:
"Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35"; Example
$age['Ben'] = "37"; <?php
$age['Joe'] = "43"; $age
The named keys can then be used in a script: = array("Peter"=>"35", "Ben"=>"37", "Joe"=
>"43");
Example
<?php foreach($age as $x => $x_value) {
$age echo "Key=" . $x . ", Value=" .
= array("Peter"=>"35", "Ben"=>"37", "J $x_value;
oe"=>"43"); echo "<br>";
echo "Peter is " . $age['Peter'] . " }
years old."; ?>
?>
PHP Sorting Array
The elements in an array can be sorted in
alphabetical or numerical order, descending or
ascending. Sort Array in Descending
PHP - Sort Functions Order - rsort()
For Arrays
The following example sorts the elements of the $cars array in
descending alphabetical order:
In this chapter, we will go through the following PHP
array sort functions:
•sort() - sort arrays in ascending order
Example
<?php
•rsort() - sort arrays in descending order $cars = array("Volvo", "BMW", "Toyota");
•asort() - sort associative arrays in ascending rsort($cars);
order, according to the value ?>
•ksort() - sort associative arrays in ascending
order, according to the key The following example sorts the elements of the $numbers
array in descending numerical order:
•arsort() - sort associative arrays in descending
order, according to the value
•krsort() - sort associative arrays in descending Example
order, according to the key <?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
PHP Sorting Array…
Sort Array (Ascending Order), According to
Sort Array in Ascending Key - ksort()
Order - sort() The following example sorts an associative array in ascending
order, according to the key:
The following example sorts the elements of the $cars
array in ascending alphabetical order:
Example
<?php
Example $age
<?php = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$cars = array("Volvo", "BMW", "Toyota"); ksort($age);
sort($cars); ?>
?>
ort Array (Ascending Order),
The following example sorts the elements of the
$numbers array in ascending numerical order: According to Value - asort()
The following example sorts an associative array in ascending
order, according to the value:
Example
<?php
$numbers = array(4, 6, 2, 22, 11); Example
sort($numbers); <?php
?> $age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
PHP Sorting Array…

Sort Array Sort Array (Descending


(Descending Order), Order), According to
According to Key - Value - arsort()
The following example sorts an associative array in
krsort() descending order, according to the value:
The following example sorts an associative array in
descending order, according to the key:
Example
<?php
Example $age
<?php = array("Peter"=>"35", "Ben"=>"37", "Joe"=
$age >"43");
= array("Peter"=>"35", "Ben"=>"37", "J arsort($age);
oe"=>"43"); ?>
Try it Yourself »
krsort($age);
?>
PHP 7 Global Variables - Superglobals
Superglobals were introduced in PHP 4.1.0, and are built-in PHP $_SERVER
variables that are always available in all scopes. $_SERVER is a PHP super global variable
PHP Global Variables - which holds information about headers, paths,
and script locations.
Superglobals The example below shows how to use some of
Several predefined variables in PHP are the elements in $_SERVER:
"superglobals", which means that they are always
accessible, regardless of scope - and you can <?php
access them from any function, class or file echo $_SERVER['PHP_SELF'];
without having to do anything special. echo "<br>";
The PHP superglobal variables are: echo $_SERVER['SERVER_NAME'];
$_GLOBALS echo "<br>";
$_SERVER echo $_SERVER['HTTP_HOST'];
$_REQUEST echo "<br>";
$_POST echo $_SERVER['HTTP_REFERER'];
$_GET echo "<br>";
$_FILES echo $_SERVER['HTTP_USER_AGENT'];
$_ENV echo "<br>";
$_COOKIE echo $_SERVER['SCRIPT_NAME'];
$_SESSION
This chapter will explain some of the superglobals, ?>
and the rest will be explained in later chapters
PHP 7 Global Variables - Superglobals
$_Server

Operator Name Example Result

$_SERVER['PHP_SELF'] Returns the filename of the $_SERVER['PHP_SELF'] Returns the filename of the
currently executing script currently executing script

$_SERVER['SERVER_NAME'] Returns the name of the host $_SERVER['SERVER_NAME'] Returns the name of the host
server (such as server (such as
www.w3schools.com) www.w3schools.com)

$_SERVER['HTTP_HOST'] Returns the Host header from the $_SERVER['HTTP_HOST'] Returns the Host header from the
current request current request

$_SERVER['HTTP_REFERER'] Returns the complete URL of the $_SERVER['HTTP_REFERER'] Returns the complete URL of the
current page (not reliable current page (not reliable
because not all user-agents because not all user-agents
support it) support it)

$_SERVER['SCRIPT_NAME'] Returns the path of the current $_SERVER['SCRIPT_NAME'] Returns the path of the current
script script
PHP 7 Global Variables - Superglobals
File 1.php
<form action="file2.php"
PHP $_REQUEST method="post">
PHP $_REQUEST is used to collect data after Name : <input type="text"
submitting an HTML form. name="firstname"><br><br>
The example below shows a form with an age : <input type="text"
input field and a submit button. When a user name="age"><br><br>
<input type="submit"
submits the data by clicking on "Submit",
value="submit">
the form data is sent to the file specified in </form>
the action attribute of the <form> tag. In
this example, we point to this file itself for
processing form data. If you wish to use File 2.php
another PHP file to process form data, <?php
replace that with the filename of your echo "<pre>";
print_r($_REQUEST);
choice. Then, we can use the super global
echo "</pre>";
variable $_REQUEST to collect the value of echo $_REQUEST["firstname"];
the input field:
?>
PHP 7 Global Variables - Superglobals
File 1.php
PHP $_POST
<form action="file2.php"
PHP $_POST is widely used to collect form method="post">
data after submitting an HTML form with Name : <input type="text"
method="post". $_POST is also widely name="firstname"><br><br>
used to pass variables. age : <input type="text"
The example below shows a form with an name="age"><br><br>
input field and a submit button. When a <input type="submit"
value="submit">
user submits the data by clicking on
</form>
"Submit", the form data is sent to the file
specified in the action attribute of the
<form> tag. In this example, we point to File 2.php
the file itself for processing form data. If <?php
you wish to use another PHP file to process echo "<pre>";
form data, replace that with the filename print_r($_POST);
echo "</pre>";
of your choice. Then, we can use the super
echo $_POST["firstname"];
global variable $_POST to collect the value
of the input field: ?>
PHP 7 Global Variables - Superglobals
File 1.php
<form action="file2.php"
method="get">
Name : <input type="text"
PHP $_GET name="firstname"><br><br>
PHP $_GET can also be used to age : <input type="text"
name="age"><br><br>
collect form data after submitting <input type="submit"
an HTML form with value="submit">
method="get". </form>

$_GET can also collect data sent


in the URL. File 2.php
<?php
Assume we have an HTML page echo "<pre>";
that contains a hyperlink with print_r($_GET);
echo "</pre>";
parameters: echo $_GET["firstname"];

?>
GET vs. POST

Both GET and POST create an array (e.g. array( key => value, key2 =>
value2, key3 => value3, ...)). This array holds key/value pairs, where
keys are the names of the form controls and values are the input data
from the user.
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.
PHP 7 Global Variables - Superglobals
When to use GET? When to use POST?
Information sent from a form with the Information sent from a form with the POST
GET method is visible to everyone (all method is invisible to others (all
variable names and values are displayed names/values are embedded within the
in the URL). GET also has limits on the body of the HTTP request) and has no
amount of information to send. The limits on the amount of information to
limitation is about 2000 characters. send.
However, because the variables are Moreover POST supports advanced
displayed in the URL, it is possible to functionality such as support for multi-part
bookmark the page. This can be useful in binary input while uploading files to server.
some cases. However, because the variables are not
GET may be used for sending non- displayed in the URL, it is not possible to
sensitive data. bookmark the page.
Note: GET should NEVER be used for Developers prefer POST for sending
sending passwords or other sensitive form data.
information!
PHP 7 Include Files
The include (or require) statement takes all the text/code/markup that
exists in the specified file and copies it into the file that uses the include
statement.
Including files is very useful when you want to include the same PHP, HTML, Syntax
or text on multiple pages of a website. include 'filename';
PHP include and require Statements or
require 'filename’;
It is possible to insert the content of one PHP file into
another PHP file (before the server executes it), with the
include or require statement.
The include and require statements are identical,
except upon failure:
•require will produce a fatal error (E_COMPILE_ERROR)
and stop the script
•include will only produce a warning (E_WARNING) and
the script will continue
So, if you want the execution to go on and show users
the output, even if the include file is missing, use the
include statement. Otherwise, in case of FrameWork,
CMS, or a complex PHP application coding, always use
PHP 7 File Handling
PHP 7 File Handling
File handling is an important part of any web
application. You often need to open and process a file
for different tasks.
<?php
echo readfile("webdictionary.txt");
PHP Manipulating Files ?>
PHP has several functions for creating,
reading, uploading, and editing files.
The readfile() function is useful if all you
Be careful when manipulating files!
want to do is open up a file and read its
When you are manipulating files you must be
contents.
very careful.You can do a lot of damage if you
The next chapters will teach you more about
do something wrong. Common errors are:
file handling.
editing the wrong file, filling a hard-drive with
garbage data, and deleting the content of a
file by accident.

PHP readfile() Function


The readfile() function reads a file and writes it
to the output buffer.
PHP 7 File Handling…
PHP Open File - fopen() PHP Read File - fread()
A better method to open files is with The fread() function reads from an open file.
the fopen() function. This function gives you more The first parameter of fread() contains the name of the
options than the readfile() function. file to read from and the second parameter specifies the
The first parameter of fopen() contains the maximum number of bytes to read.
name of the file to be opened and the second The following PHP code reads the "webdictionary.txt" file to
the end:
parameter specifies in which mode the file
fread($myfile,filesize("webdictionary.txt"
should be opened. The following example
));
also generates a message if the fopen()
function is unable to open the specified file:
PHP Close File - fclose()
<?php The fclose() function is used to close an open file.
$myfile = It's a good programming practice to close all files after you
fopen("webdictionary.txt", "r") have finished with them. You don't want an open file
running around on your server taking up resources!
or die("Unable to open file!"); The fclose() requires the name of the file (or a variable
echo that holds the filename) we want to close:
fread($myfile,filesize(“test.txt"
<?php
)); $myfile = fopen(“test.txt", "r");
fclose($myfile); // some code to be executed....
?> fclose($myfile);
?>
PHP 7 File Handling…

Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a new
file if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already
exists
r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new
file if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
PHP 7 File Handling…
PHP Read Single Line - fgets() <?php
The fgets() function is used to read a single line from a $myfile = fopen("webdictionary.txt", "r") or die("Unable to
file. open file!");
The example below outputs the first line of the // Output one line until end-of-file
"webdictionary.txt" file: while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
Example fclose($myfile);
<?php ?>
$myfile = PHP Read Single Character - fgetc()
fopen("webdictionary.txt", "r") or die("Unable to The fgetc() function is used to read a single character from a file.
open file!"); The example below reads the "webdictionary.txt" file character by
echo fgets($myfile); character, until end-of-file is reached:
fclose($myfile);
?> Example
Note: After a call to the fgets() function, the file pointer <?php
has moved to the next line. $myfile = fopen("webdictionary.txt", "r") or die("Unable to
open file!");
PHP Check End-Of-File - feof() // Output one character until end-of-file
The feof() function checks if the "end-of-file" (EOF) has while(!feof($myfile)) {
been reached. echo fgetc($myfile);
The feof() function is useful for looping through data of }
unknown length. fclose($myfile);
The example below reads the "webdictionary.txt" file ?>
line by line, until end-of-file is reached: Note: After a call to the fgetc() function, the file pointer moves to the
next character.
PHP 7 File Handling…
PHP Create File - fopen()
The fopen() function is also used to create a file. Maybe a
little confusing, but in PHP, a file is created using the same PHP Write to File - fwrite()
function used to open files. The fwrite() function is used to write to a file.
If you use fopen() on a file that does not exist, it will create
it, given that the file is opened for writing (w) or appending The first parameter of fwrite() contains the name of the
(a). file to write to and the second parameter is the string to be
The example below creates a new file called "testfile.txt". written.
The file will be created in the same directory where the PHP The example below writes a couple of names into a new file
code resides: called "newfile.txt":

Example <?php
$myfile = fopen("testfile.txt", "w") $myfile =
fopen("newfile.txt", "w") or die("Unable to
PHP File Permissions open file!");
If you are having errors when trying to $txt = "John Doe\n";
get this code to run, check that you fwrite($myfile, $txt);
$txt = "Jane Doe\n";
have granted your PHP file access to
fwrite($myfile, $txt);
write information to the hard drive fclose($myfile);
?>
PHP 7 Upload File

Configure The "php.ini" File Some rules to follow for the HTML form above:
First, ensure that PHP is configured to allow file Make sure that the form uses method="post"
uploads.
In your "php.ini" file, search for The form also needs the following attribute:
the file_uploads directive, and set it to On: enctype="multipart/form-data". It specifies
Create The HTML Form which content-type to use when submitting
Next, create an HTML form that allow users the form
to choose the image file they want to Without the requirements above, the file
upload
upload will not work.
<form action="upload.php" method="pos
Other things to notice:
t" enctype="multipart/form-data"> The type="file" attribute of the <input> tag
Select image to upload: shows the input field as a file-select control,
<input type="file" name="fileToUp with a "Browse" button next to the input
load" id="fileToUpload"> control
<input type="submit" value="Uploa The form above sends data to a file called
d Image" name="submit">
"upload.php", which we will create next
</form>
PHP 7 Date and Time
A timestamp is a sequence of characters, denoting the date
The PHP date() function is used to format a date and/or time at which a certain event occurred.
and/or a time. Get a Simple Date
The required format parameter of the date() function
The PHP Date() Function specifies how to format the date (or time).
The PHP date() function formats a timestamp to a Here are some characters that are commonly used for dates:
more readable date and time. d - Represents the day of the month (01 to 31)
Syntax m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
date(format,timestamp)
l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted
Parameter Description between the characters to add additional formatting.
The example below formats today's date in three different
ways:
format Required. Specifies the
format of the timestamp <?php
echo "Today is " . date("Y/m/d") . "<br>";
timestamp Optional. Specifies a
timestamp. Default is the
echo "Today is " . date("Y.m.d") . "<br>";
current date and time echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
PHP 7 Date time..
Get a Simple Time
Here are some characters that are
commonly used for times:
H - 24-hour format of an hour (00 to 23) Get Your Time Zone
h - 12-hour format of an hour with leading If the time you got back from the code is not the
zeros (01 to 12) right time, it's probably because your server is in
i - Minutes with leading zeros (00 to 59) another country or set up for a different timezone.
s - Seconds with leading zeros (00 to 59) So, if you need the time to be correct according to a
a - Lowercase Ante meridiem and Post specific location, you can set a timezone to use.
meridiem (am or pm) The example below sets the timezone to
The example below outputs the current time "America/New_York", then outputs the current time
in the specified format: in the specified format:

Example
<?php Example
echo "The time is " . date("h:i:sa"); <?php
?> date_default_timezone_set("America/
New_York");
Note that the PHP date() function will return echo "The time is " . date("h:i:sa");
the current date/time of the server! ?
PHP 7 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 Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use
the isset() function to find out if the cookie is set:
PHP 7 Cookie

Example Note: The setcookie() function must


If(isset($_POST["username"])){
appear BEFORE the <html> tag.
Note: The value of the cookie is
$username =$_POST["username"];
automatically URLencoded when sending
$password =$_POST["password"];
the cookie, and automatically decoded
when received (to prevent URLencoding,
if($username =="ali" && $password =="123"){
if($_POST["rem"] =="on"){ use setrawcookie() instead).

+260020);
setcookie("password",$password,time()
Delete a Cookie
}else{ To delete a cookie, use
setcookie("password",$password,time() -1 ); the setcookie() function with an
} expiration date in the past

header("Location: home1.php"); setcookie(name,value,time() -1


)
}else{
echo "Inccrect password or username";
}
}

You might also like