PHP is a high-level scripting language used primarily as a backend language for servers. High-level languages have engines that interpret what you write (code) into actual machine code.
PHP handles all the processing and logic between server and client data. Examples include sanitising user data, authentication, database communication, error handling, etc.
Primarily, PHP is embedded in an HTML document. The PHP parser will read all the PHP code and output the result on the page as text, HTML, CSS, or whatever data presentation you choose.
Getting Started With PHP
For starters, you can use PHP by creating a file and saving it with a .php extension.
You can write regular HTML in these files.
PHP Syntax
All PHP code is contained inside angled brackets with a question mark like this:
<!DOCTYPE html>
<html>
<head>
<title>PHP Sample</title>
</head>
<body>
<h1>Today is <?php echo date('M d'); ?></h1>
</body>
</html>
The parser will read the code and output the results.
The echo function prints the value onto the page. More on functions below.
PHP Variables
Variables in programming are ways of storing temporary data. The data is temporary because when the computer turns off it won’t be saved.
Variables can contain anything from strings (words), numbers, arrays, booleans, or functions. PHP variables start with a $ followed by the variable name.
<?php
//stroing number
$num = 138;
//string
$name = 'Peter';
//date function
$day = date('D');
//array
$arr = [12, 23, 67];
?>
Variable names:
- Cannot start with a number
- Cannot contain special characters like *#;:) etc
- Cannot contain spaces. Use underscores (_) to join words.
PHP is dynamically typed, i.e. the type of data a variable hold is determined at runtime not at compile (writing) time.
Printing Output in PHP
echo
echo is the standard PHP keyword to print outputs. echo is used to print strings.
<?php
$num = 138;
//Output: 138
echo $num;
$name = 'Peter';
//Output: Peter
echo $name;
$day = date('D');
// Output: Wed
echo $day
$arr = [12, 23, 67];
//Output: Error cannot print arrays
echo $arr;
?>
You can use the print alias as well.
print_r
print_r is used to output arrays and objects. You’ll learn about arrays below.
<?php $arr = [12, 23, 67]; //Expected Output: Array ( [0] => 12 [1] => 23 [2] => 67 ) print_r($arr); ?>
Block level printing
Block-level printing works when using block statements like if...else, for, while, functions etc. You’ll learn about these below.
<!DOCTYPE html>
<html>
<head>
<title>jQuery sample</title>
</head>
<body>
<?php if(is_logged_in()): ?>
<h1>Welcome <?php echo $username; ?></h1>
<?php endif; ?>
</body>
</html>
Data Types in PHP
Strings
Strings represent the text of any character or symbol. Strings are mainly used to write human-readable text. Here are examples of strings:
<?php
$date = date('D, M d');
echo 'PHP is cool!';
//Output: Today is Wed, Nov 27
echo "Today is $date";
?>
As you can see, strings are enclosed inside quotes (single or double).
You can join variables and strings using the dot (.) notation. This is called string concatenation.
If you’re using double quotes you can just embed the variable inside the string like so:
Int
Integers represent whole numbers. For example, 23, 456 etc
<?php $num = 34; ?>
Floats
Floats are numbers with a decimal point. For example, 1.45, 0.5.
<?php $num = 5.44; ?>
Booleans
A Boolean only represents a true (1) or false (0). They are used in logical operations.
<?php $is_logged = true; ?>
Null
Null means no value.
<?php $user = null; ?>
Arithmetic Operators
<?php echo 23+ 4; ?>
- +: Addition
- -: Subtracting
- *: Multiplication
- /: Division
- %: Modulo
- **: Exponent (to the power of)
<?php
//Assignment
$num1 = 3;
//Re-assigning variable
//Addition. Output: 4
$num1 = $num1 + 1;
//Subtraction. Output: 3
$num1 = $num1 - 1;
//Multiplication. Output: 9
$num1 = $num1 * 3;
//Division. Output: 3
$num1 = $num1 / 3;
//Exponent. 3 to the power 2. Output: 9
$num1 = $num1 ** 2;
//Modulo. Remainder of Output: 1
$num1 = $num1 % 2;
//expected output: 1
echo $num1;
?>
Assignment Operators
- = Assign a value
- +=: Addition assignment
- -=: Subtraction assignment
- *=: Multiplication assignment
- **=: Exponent assignment. The power of
- %=: Modulo or remainder assignment
The above code can be shortened with assignment operators like so:
<?php
//Assignment
$num1 = 3;
//Re-assigning variable
//Addition. Output: 4
$num1 += 1;
//Subtraction. Output: 3
$num1 -= 1;
//Multiplication. Output: 9
$num1 *= 3;
//Division. Output: 3
$num1 /= 3;
//Exponent. 3 to the power 2. Output: 9
$num1 **= 2;
//Modulo. Remainder of Output: 1
$num1 %= 2;
//expected output: 1
echo $num1;
?>
Arrays
Arrays are robust data types that store a collection of data. The data can be anything from strings, numbers, functions, or other arrays. Here are examples of arrays.
<?php $colors = ['green', 'blue', 'red']; //using array function $grades = array(50, 70, 30); // Output: Array ( [0] => 50 [1] => 70 [2] => 30 ) print_r( $grades ); ?>
There are two ways to create functions; bracket [] notation and the array() function. The print_r function is used to print arrays to the screen.
PHP has two types of arrays: index and associative arrays.
Indexed arrays use numbers (indexes) to access an array value. Take a look below:
<?php $colors = ['green', 'blue', 'red']; // Output: blue echo $colors[1]; ?>
If we want to access the 2rd array value, we use an index of 1.
Unlike regular counting, counting in programming starts at 0. If we want to access the first array value we use an index of 0.
Associative arrays
Associative arrays use predefined keys to access an array value. Here’s an example of an associative array. To access the second value we do this:
<?php
$user = array(
'name'=>'Peter',
'email'=>'peter@somesite.com',
'age'=>30,
'isStudent'=>true,
'subjects'=>['English','Maths', 'Chemistry']
);
//Output: 30
echo $user['age'];
?>
Functions
A function is a container of a block of code that processes something and returns a value (or not). Think of them as factories that do the processing of raw materials and produce a product. Here’s how to create a function in PHP.
<?php
function total( $num1, $num2){
return $num1 + $num2;
}
// Output: 123
echo total( 55, 68 );
?>
Functions have 3 parts: function name, parameters, and function block/definition.
You first write the function keyword followed by the function name. The function name can only contain letters and numbers and underscores. They cannot start with a number.
After the function name, you put two brackets, opening and closing. These brackets can contain what are known as parameters ($num1, $num2). Parameters are optional.
After the parentheses, the function block (definition) comes contained in curly brackets. The function definition is the actual code that is processed (executed).
Calling a function
You call or invoke a function like this.
The function will process whatever is put in it and returns a value if specified. If you don’t return something nothing is outputted. The code gets executed but nothing is returned.
return
Functions typically return a value. When the return keyword is encountered, the function terminates/exits and returns whatever value is declared.
<>php
function total( $num1, $num2){
return $num1 + $num2;
}
echo total( 55, 68 );
The function above returns the total of the two numbers. If return is specified without any value, the function exits without any value.
Function Parameters
Parameters are ways of passing external data into the function for processing. You specify parameters inside the function brackets. Using the function above, $num1 & $num2 are parameters.
You call this function with arguments (external data) attached. The arguments will be passed to the function for processing.
<>php echo total( 23,88 );
Parameters can be made optional or required. You can set default parameter values. The function will run whether a value (argument) is passed or not.
<>php
function total( $num1 = 0, $num2 = 0){
return $num1 + $num2;
}
//Output: 0
echo total();
In the above, 0 is the default value for all parameters.
However, if no default parameter value is set and the function is called without the argument an error will be thrown.
PHP Scopes
Scopes determine the accessibility of variables. A variable inside a function can only be used inside that function. We call it locally scoped. Variables outside are globally scoped and can be used anywhere, even inside functions.
However, PHP takes variable accessibility seriously. You need to use the global keyword to access outside variables inside functions.
<>php
function my_funct(){
//locally scoped
$month = date('M');
echo "The month is $month";
}
// Output: $month is not defined
echo $month;
The reason for this is to prevent overwriting global variables without knowing.
Conditional Logic
Logic enables you to process a piece of code based on whether the condition is true or false.
if…else
The if statement executes some code if a specified condition is true. The program continues to the else block if the condition is false. Here’s an example:
<?php
$number = 5;
if( $number > 0 ){
//do some operations here
echo "$number is greater than 0";
}
else{
echo "$number is less than 0";
}
?>
elseif
If you want to do further conditional checks, you can use the else if statement.
<?php
$number = -2;
if( $number > 0 ){
//do some operations here
echo "$number is greater than 0";
}
elseif( $number < 0){
//do some operations here if condition is true
echo "$number is less than 0";
}
else{
//run this when all above is not true (false)
echo "$number is less than 0";
}
?>
PHP Loops
Looping allows us to run a repetitive task (code) several times.
for loop
The for loop is used to loop array entries. It loops through all entries unil a condition is false.
<>php
$fruits = ['orange','apple','banana'];
for ($i=0; $i < count( $fruits ) ; $i++) {
//the $i stores the current index
echo $fruits[$i];
}
A for loop has 3 parts:
- Initialize – $i = 0 – where to start counting from. 0 is the first entry in an array
- Condition – keep running the loop as long as this condition is true; terminate if false.
- Increment – increments the initialiser (
$i) and proceeds to the next array entry if the condition is still true.
The $i inside the loop block {} stores the current index as it increments. It is used for the array index.
while loop
while loops run until a condition is false.
<>php
$num = 0;
while ( $num < 10 ) {
echo $num;
//increment the $num
$num++;
}
In the code above, the loops keep running until $num is less than 10. $num gets incremented every time the loop runs. while loops are typically useful when you don’t have an explicit length to test against.
do…while
The do...while loop runs a block of code at least once and continues to execute the code as long as a specified condition is true.
<>php
$i = 1;
do {
echo "Value of i: $i\n";
$i++;
} while ($i <= 5);
- The loop will print “Value of i: 1” the first time.
- Then,
$iis incremented and the condition ($i <= 5) is checked. - If the condition is true, it repeats the loop. If false, the loop stops.
Note: Explanation is aided by AI
Including Files
PHP enables you to include external files in your code. These files can be anything from plain text files (.txt), .html files, or other PHP files. There are two expressions for file inclusions: include and require.
<?php include 'src/header.php'; include_once 'src/body.php'; require 'src/sidebar.php'; require_once 'src/footer.php'; ?>
After the expression, you write the file path to be included. The file path can be relative to your current directory or absolute (server path).
The difference between include and require is the type of error they throw. include continues the script if a file is not found, while require will terminate the script.
The expressions with _once only include the file one time; the file will not be included again if another include is encountered.
File inclusions help to use one source code in multiple files. You only change one file, and all others will reflect the changes
Form Processing with PHP
When you submit a form, e.g. a signup or login form, it is sent to the server for processing. PHP is one of the languages that can process form data.
There are two http methods of sending data from client (browser) to server: GET and POST
GET
The GET method is mainly used to retrieve data from a server. Assume we have the following form to get some user data from the server.
<form action="https://webdesyn.com/samples/user.php" method="GET"> <input type="text" name="username" placeholder="Your name"> <button type="submit">Get my data</button> </form>
The <form> has two attributes:
- action – url to the processing page
- method:- the type of http request method
When you click Get my data the form redirects you to the processing page. Note the ?username=Peter in the URL of the processing page. These are called query parameters and hold the inputted data.

The data sent in the query parameters is accessed by PHP using $_GET. The $_GET is a global variable that stores all query parameter data in an array. For example, in the form above, the username in the input name attribute is the identifier for holding the User Name. The identifier is used in PHP to get the value: $_GET['username']
<!DOCTYPE html>
<html>
<head>
<title>User Dashboard</title>
</head>
<body>
<?php
//terminate if no parameter supplied
if( !isset($_GET['username']) || empty($_GET['username'])) exit('Error!, No name supplied');
$username = $_GET['username'];
//get data from database
//$data =get_data_from_db( $username );
//assume array of data is returned
$data = array(
'name'=>$username,
'email'=>'user@somesitel.com',
'is_student'=>true,
'dob'=>'25 April 1999',
'age'=> 30,
);
?>
<p>Name: <?php echo $data['name']; ?></p>
<p>Email: <?php echo $data['email']; ?></p>
<p>Student: <?php echo $data['is_student'] ? 'yes':'no'; ?></p>
<p>Date of Birth: <?php echo $data['dob']; ?></p>
<p>Age: <?php echo $data['age']; ?></p>
</body>
</html>
The form processing page
You can change data in the query parameters without the form. Try changing the parameter username=Peter to username=Brian and see the name changing on the page.
Typically, GET is the most used method for retrieving HTML documents, images, scripts, CSS files etc. When you open a web page you are generally using GET.
POST
The HTTP POST method is typically used to send data to the server. This data is usually stored on the server or used for deleting and updating.
POST is also used for sending sensitive data like passwords as it is more secure. In addition, POST can handle huge data and, therefore can be used for uploading images
Here is a basic signup form:
<form method="POST" action="https://webdesyn.com/samples/post.php">
<input type="text" name="username" placeholder="Your username">
<input type="pawssowrd" name="password" placeholder="Your pawssowrd">
<button type="submit">Create account</button>
</form>
Here is the PHP processing page
<!DOCTYPE html>
<html>
<head>
<title>POST</title>
</head>
<body>
<?php
//terminate if no parameter supplied
if( !isset($_POST['username']) || empty($_POST['username'])) exit('Error!, Fields cannot be empty');
$username = $_POST['username'];
$pawssowrd = $_POST['password'];
//insert user in databse
//----Code goes here----
?>
<h1>Details supplied</h1>
<p>Name: <?php echo $username; ?></p>
<p>Password: <?php echo $pawssowrd; ?></p>
</body>
</html>
Working with Files in PHP
PHP has lots of functions for reading and writing files.
file_put_contents()
file_put_contents() is the easiest function for writing to a file. Here’s an example:
<?php
file_put_contents('path/to/file.txt', 'I love PHP');
?>
file_put_contents() generally has two important arguments: the file path and the data to write. The function creates a new file if it doesn’t exist.
file_get_contents()
Reads a file to a string
<?php
$contents = file_get_contents('path/to/file.txt');
echo $contents;
?>
This function works well for reading small files. Don’t use it to read large files. For larger files, you may need additional functionalities which are beyond the scope of this guide
fopen(), fwrite(), fread(), & fclose()
These functions are a bit involved but may offer additional control.
<?php
$file = fopen('path/to/file.txt', 'w');
fwrite($file, 'Hello PHP!');
fclose($file);
?>
fopen() opens a file for reading or writing. It returns a resource that other functions can use. The two basic parameters required are the file path and the operation mode. The mode can be any of the following:
- r – opens the file for reading
w– opens the file for writing at the start. Overwrites existing data. Creates a new file if it doesn’t exists.a– Writes(append) data at the end. Creates a new file if it doesn’t exists.- r+ – opens the file for both reading and writing at the beginning of the file
- w+ – opens the file for both reading and writing at the beginning of the file. Creates a new file if none exists.
- x – opens the file for writing at the beginning. It fails if the file already exists. Creates a new file if none exists.
- x+ – Same as
xbut for reading as well
fwrite()
fwrite() writes data to a file. The basic parameters are resource supplied by fopen(), data to write, length of data to write. It returns false on failure or the number of bytes written
<?php
$file = fopen('path/to/file.txt', 'w');
//write only 6 bytes
//will ouput "PHP is"
fwrite($file, 'PHP is cool', 6);
fclose($file);
?>
fread()
<?php
$file = fopen('path/to/file.txt', 'w');
fclose($file);
?>
PHP best practices
- Avoid global variables as they can clash with other codes. Create functions and classes to encapsulate variables.
- Namespace where necessary. You can create prefixes for variable and function names; e.g
$wd_[variable name],wd_[funtcion name] - Avoid reading large files as a whole, instead read small chunks at a time.
