PHP Programming Language

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.

  • Used extensively world-wide
  • Easy to learn
  • Can be combined with HTML to provide a Web-based graphical user interface
  • A PHP file can contain HTML code and any number of PHP sections containing PHP code

PHP 7 is the latest stable release.

Note

You can’t open a PHP file in VS Code Live Server. You will need XAMPP for a PHP file.

Features of Client/Server Design

  • HTML files are static (always the same content)
  • PHP files are dynamic (content is generated at the time the file is processed, and may be different each time depending on the program instructions).

PHP Syntax

https://www.w3schools.com/php/php_syntax.asp

Basic PHP Syntax

  • A PHP script starts with <?php and ends with ?>.
  • PHP variables are case-sensitive
  • keywords, classes, functions and user-defined functions are not case-sensitive.

a Helloworld example of PHP, show casing keywords, classes, functions and user-defined functions are not case-sensitive.

1
2
3
4
5
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

PHP Output and Variables

  • To get output, we can use echo and print.
  • Variable names must start with the $
    • PHP automatically associates a data type to the variable, depending on its value

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.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
echo ("Hello World!<br>");
echo "Hello World!<br>";
echo "Hello" . "World!<br>";
$x = 5;
$y = 4;
echo "x= " . $x . "y= " . $y;

echo "x=$xy=$y"; // <---- error
echo "x={$x}y={$y}";

echo $x + $y;
echo  "The sum is " . ($x + $y);
?>

PHP Comments

1
2
3
4
5
6
7
8
9
10
<?php
// This is a single-line comment
# This is also a single-line comment

/*
This is a multiple-lines comment block
This is a multiple-lines comment block
This is a multiple-lines comment block
*/
?>

PHP Type Conversion

1
2
3
4
5
6
$var  = 2.29;

$var2 = strval($var); // '2.29'
$var3 = intval($var); // 2
$var4 = boolval($var); // 1
$var5 = floatval($var);// 2.29

Be careful - PHP allows you to mix data types:

  • If you convert a String into Number, it will become 0.

PHP Number

PHP has the following functions to check if the type of a variable is integer:(return true if it is an integer)

An integer is a number without any decimal part.

  • is_int(var)
  • is_integer(var)
  • is_long(var)

PHP String

Some commonly used functions to manipulate strings

  • strlen(var) - returns the length of a string
  • str_word_count(var) - counts the number of words in a string
  • strrev(var) - reverses a string
  • strpos(var, str) - searches position for a specific text within a string (if no match return false)
  • str_replace() - replace some characters with some other characters in a string
    • example: str_replace("world", "Dolly", "Hello World!"); // Hello Dolly!

PHP Array

The array functions allow you to access and manipulate arrays.

  • array() - creates an array
  • count() - returns the number of elements in an array
  • sizeof() - returns the number of elements in an array
  • array_count_values() - counts all the values of an array
  • array_keys() - returns an array containing the keys
  • array_key_exists() - checks an array for a specified key, and see if the key exists

The sorting functions:

  • sort() - sort arrays in ascending order
  • rsort() - sort arrays in descending order
  • asort() - sort associative arrays in ascending order, according to the value
  • arsort() - sort associative arrays in descending order, according to the value
  • ksort() - sort associative arrays in ascending order, according to the key
  • krsort() - sort associative arrays in descending order, according to the key
1
2
3
4
5
6
7
8
9
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);

for($x = 0; $x < count($numbers); $x++){
echo $numbers[$x] . " ";
}

// 2 4 6 11 22

To create different types of arrays:

Indexed Arrays

1
2
3
4
5
6
7
8
9
10
//Two ways to create an indexed array
$fruits = array("apple", "orange", "pear");
echo "I like " . $fruits[0];

$fruits[0] = "apple";
$fruits[1] = "orange";
$fruits[2] = "pear";
echo "I like " . $fruits[0];

//I like apple

Loop through an indexed array

1
2
3
4
5
6
7
8
9
10
$fruits = array("apple", "orange", "pear");
$arrlength = count($fruits);
for($x = 0; $x < $arrlength; $x++){
echo $fruits[$x];
echo "<br>";
}

// apple
// orange
// pear

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them (store key-value pairs).

1
2
3
4
5
6
7
8
9
10
//Two ways to create an associative array
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

echo "Peter is " . $age['Peter'] . " years old.";
//Peter is 35 years old.

Loop through an Associative array

1
2
3
4
5
6
7
8
9
10
11
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $key => $value) {
echo "Key=" . $key . ", Value=" . $value;
echo "<br>";
}

/*
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
*/

Multidimensional Arrays

1
2
3
4
5
6
7
8
9
$fruits = array ( 
array("apple", 22, 18),
array("orange", 15, 13),
array("pear", 5, 2),
array("banana", 17, 15)
);

echo $fruits[2][0]." in stock: " . $fruits[2][1];
// outputs: pear in stock: 5

PHP Loops

  • while loop
  • do…while loop
  • for loop
  • foreach loop

Foreach loop Example

1
2
3
4
5
6
7
8
9
10
11
$colors = array("red", "green", "blue", "yellow"); 
foreach ($colors as $value) {
echo "$value <br>";
}

/*
red
green
blue
yellow
*/

PHP Math

PHP has a set of math functions that allows you to perform mathematical tasks on numbers.

  • pi() - reutrns value of PI
  • min() - find the lowest value in a list of arugments
  • max() - find the highest value in a list of arugments
  • abs() - return absolute value of a number
  • sqrt() - return square root of a number
  • round() - rounds a floating-point number to its nearest integer.
  • rand(x,y) - generates a random number between x and y (inclusive)

PHP Object-Oriented Programming

You can write PHP code in an object-oriented style.

Object-oriented programming is about creating objects that contain both data and functions.

Advantages:

  • OOP provides a clear structure for the programs.
  • OOP helps to make the code easier to maintain, modify and debug.
  • OOP makes it possible to create full reusable applications with less code and shorter development time.

An example of PHP OOP.

OOP consists of : Class, Object, Property, Methods, Constructor, Access Modifiers (public, private, protected)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
class Employee{
private $name;
private $hourly;

function __construct($name, $wage, $hours){ // Constructor, reserved naming
$this->name = $name;
$this->hourlyWage = $wage;
$this->hoursworked = $hours;
}

function greeting(){
echo "Hello!<br>";
}

function getName(){
return $this->name;
}

function calculateWeeklyWage(){
return $this->hourlyWage * $this->hoursworked;
}
}

$person1 = new Employee('Tom', 80, 20);
$person1->greeting();

$person2 = new Employee('Mike', 60, 15);
$person2->greeting();

echo $person2->getName();

/*
Hello!
Hello!
Mike
*/

?>

An Example of PHP Inheritance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
class Employee{
private $name;
private $hourly;

function __construct($name, $wage, $hours){ // Constructor, reserved naming
$this->name = $name;
$this->hourlyWage = $wage;
$this->hoursworked = $hours;
}

function greeting(){
echo "Hello!<br>";
}

function getName(){ return $this->name; }

protected function calculateWeeklyWage(){
return $this->hourlyWage * $this->hoursworked;
}
}

class Secretary extends Employee{
private $boss;

function __construct($boss){
parent::__construct("Mike", 100, 20);
$this->boss = $boss;
}

function sendMessage(){
echo "I am sending some message. <br>";
}

function greeting(){ //Overrides the same function in Employee
echo "Hello! I am a secretary.<br>";
echo $this->calculateWeeklyWage() . "<br>";
}
}

$employee1 = new Employee("Tom", 80, 20);
echo $employee1->getName() . "<br>";
$secretary1 = new Secretary("Sally");
$secretary1->sendMessage();
echo "My name: " . $secretary1->getName() . "<br>";
$secretary1->greeting();

/*
Tom
I am sending some message.
My name: Mike
Hello! I am a secretary.
2000
*/
?>

PHP Include Files / Require Statement

Consider a case:

  • A website should have the same header and footer.
  • If you want to modify the header or footer of this website, you need to rewrite the code of each page.

There is an an easier way in PHP:

  • Write an HTML file for header and an HTML file for footer
  • Include the content of these files into each pages in PHP
  • Modify the header or footer files to update the header or footer of this website

Example - Insert the content of one PHP file into another PHP file (before the server executes it):

header.html

1
2
<h2>Welcome to My Website</h2>
<hr>

footer.html

1
2
<hr>
<h3>Thanks for your visit!</h3>

website.html

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php include "header.html" ?>
<p> Hello world! </p>
<?php include "footer.html" ?>
</body>

</html>

Example - Include PHP files

post.php

1
2
3
4
5
<?php
echo"<h2>$title</h2>";
echo"<h2>$author</h2>";
echo"<hr>"
?>

tool.php

1
2
3
4
5
6
<?php
$str = "This is a string";
function greeting($name){
echo "Hi, $name";
}
?>

blog.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
$title = "Building a webpage";
$author = "Mike";
include "post.php";

include "tools.php";
echo "$str <br>";
greeting("Mike");
?>
</body>
</html>

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.

  • PHP has several functions for creating, reading, uploading, and editing files.

PHP Files - Read

1
2
3
4
5
<?php
$myfile = fopen("info.txt""r");
echo fread($myfile,filesize("info.txt"));
fclose($myfile);
?>
  • fopen("<filename>", "<r/w/a/r+>") - open / create a file
    • filename : the name of the file
    • r : read only
    • w : write only (erase the content of the file)
    • a : append (writing only)
    • a+ : append (both read/write)
    • r+ : read/write
  • fread($myfile, filesize("<filename>")) - read a file
    • The first parameter contains the name of the file to read from.
    • The second parameter specifies the maximum number of bytes to read.
  • fclose($myfile) - close a file
1
2
3
4
5
6
7
<?php 
$myfile = fopen("info.txt""r");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
1
2
3
4
5
6
7
<?php 
$myfile = fopen("info.txt""r");
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
  • feof($myfile) - return true if end of file (EOF) has been reached
  • fgets($myfile) - read a single line
    • After a call to the fgets() function, the file pointer has moved to the next line.
  • fgetc($myfile) - read a single character
    • After a call to the fgetc() function, the file pointer moves to the next character.

PHP Files - Write

1
2
3
4
5
6
<?php
$myfile = fopen("info.txt""w");
$txt"Mike\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
  • fwrite($myfile, $txt) - write a file
    • The first parameter contains the name of the file to write to.
    • The second parameter is the string to be written.

PHP Global Variables

PHP has some super global variables:

  • _POST
  • _GET
  • _COOKIE
  • _SESSION
  • GLOBALS
  • _SERVER
  • _REQUEST

Super global variables are built-in variables that are always available in all scopes (any function, class or file).

HTML Forms and PHP

https://www.w3schools.com/html/html_form_input_types.asp

PHP $_GET is used to collect form data after submitting an HTML form with method=“post”.

Example:

trip.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
<head>
<title>City Trip</title>
</head>
<body>
<h1>Fuel Cost from NYC</h1>
<form action="trip.php" method="post" id="formid">
<table>
<tr>
<td align="left">Author MPG</td>
<td align="left"><input type="text" name="carMileage" id="mpg"></td>
</tr>
<tr>
<td align="left">Average Cost of a Gallon of Fuel:</td>
<td align="left"><input type="text" name="avgCost" id="avgCost"></td>
</tr>
<tr>
<td align="left">Which city are you visiting?</td>
<td align="left">
<select id="city" name="city">
<option value="blank"></option>
<option value="Atlanta">Atlanta</option>
<option value="Boston">Boston</option>
<option value="Chicago">Chicago</option>
<option value="Detroit">Detroit</option>
<option value="Miami">Miami</option>
</select>
</td>
</tr>
<tr>
</table>
<input type="submit" value="My Fuel Costs"/>
</form>

</body>
</html>

trip.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>

<html>
<body>

<?php
$carMileage = $_POST['carMileage'];
$avgCost = $_POST['avgCost'];
$city = $_POST['city'];

$cities = array(
"Atlanta"=>880,
"Boston"=>225,
"Chicago"=>788,
"Detroit"=>614,
"Miami"=>1275
);

$distance = $cities[$city];

$totalCost = $distance / $carMileage * $avgCost;

print("<h1>Fuel Cost to ". $city. " from NYC </h1>");

print("The distance is " . $distance . " miles and your fuel cost will be
approximately $" . sprintf('%0.2f', $totalCost) . ".");
?>

</body>
</html>

GET vs. POST

For above example, We can use method = "get" instead of method = "post" in html and use $_GET instead of $_POST in php.

Visibility

  • GET: Data is visible to everyone (all variable names and values are displayed in the URL).
  • POST: Data is invisible to others (all names/values are embedded within the body of the HTTP request).

Security

GET is less secure compared to POST because data sent is part of the URL.

Never use GET when sending passwords or other sensitive information!