PHP-2
PHP-2
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.)
<?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
<?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):
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
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
$_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 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.
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
+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