PHP (Hypertext Preprocessor)
Reference:
https://www.youtube.com/watch?v=pWG7ajC_OVo&list=PL4cUxeGkcC9gksOX3Kd9KPo-O68nc
T05o
Introduction to PHP
Why PHP?
● Huge & active community for support
● Very popular (WordPress, Drupal, Magento)
PHP Hypertext Preprocessor
● PHP is a server-side scripting language
● Output dynamic content to the HTML templates
Figure 1.0
What You’ll Learn
● PHP basics & creating PHP files
● Rendering dynamic content to HTML templates
● How to communicate with MySQL databases
● Cookies & Sessions
● PHP objects & classes
Install PHP & Database through XAMPP
● Install XAMPP (https://www.apachefriends.org/index.html)
● Start Apache and MySQL to develop locally
First PHP File
● Create new folder under htdocs folder on xampp where you’ll put your php file/s
● Embed php code within php tags
● Always end php statements with a semicolon
Figure 1.0 - Sample Php Statement
Figure 1.0 - Embedded Php Code on HTML Template
Variables & Constants
● Variables store values or data which can be recalled and used later on in the
program (Ex.: Have a variable to store email address and call upon it later on)
● Define function is used to create a constant.
Syntax: define(‘name’, ‘value’)
● It is not allowed to overwrite a constant.
Figure 1.0 - Sample Use of Variable Called $name
Figure 1.1 - Define Function to Create Constant
Data Type: Strings
● A data type which contains special characters
● Strings are contained inside single or double quotes
● String concatenation is when two strings are joined together through a dot
● Variable Interpolation is the process of outputting variables within a single string
which is enclosed by double quotes and recalled through placeholders
● A backslash is used to escape characters that are enclosed within quotes
● The strlen() is a built-in PHP function which returns the number of characters in
a string including the space. Syntax: str_replace(find,replace,string,count)
● The str_replace() function replaces some characters with some other characters
in a string. Syntax: str_replace(find,replace,string,count)
● Use double quotes in a string when utilizing variable interpolation
Figure 1.0 - Concatenation on Variables and String
Figure 1.1 - Sample of Variable Interpolation
Figure 1.2 - Escaping Characters through Backslash and Single Quotes
Figure 1.3 - Call an Individual Letter through Index of 1
Figure 1.4 - PHP Strlen() Function
Figure 1.5 - PHP Str_replace() Function
Data Type: Numbers
● Double asterisk is used to execute exponents
● Use ++ for increment and -- for decrement
● Use floor() function to round down to nearest integer
● Use ceil() function to round up to nearest integer
Data Type: Arrays (Part 1)
● Three (3) types of arrays: indexed arrays, associative arrays, and
multidimensional arrays
● Square brackets indicate an array
● Another way to create an array is to use the array() function.
● To output a whole readable array, use, print_r() function.
● To add a value into an array use array_push() method. Syntax:
array_push(array, value)
● To count the length in an array use count() function.
● To combine two arrays, use array_merge() method.
● Associative arrays are composed of key value pairs.
● The double arrow operator, =>, is used as an access mechanism for arrays.
This means that what is on the left side of it will have a corresponding value of
what is on the right side of it in array context. This can be used to set values of
any acceptable type into a corresponding index of an array. The index can be
associative (string based) or numeric.
Figure 1.0 - Indexed and Associative Arrays
Data Type: Arrays (Part 2)
● A multidimensional array is an array containing one or more arrays.
● PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to manage for
most people.
● Use array_pop() method to remove the last element inside the array.
Figure 1.0 - Multidimensional Array
Loops
● Use loops to iterate over array data.
● Syntax for the for loop:
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
● Syntax for the foreach loop: foreach ($array as $value) {
code to be executed;
}
Figure 1.0 - For Loop #1
Figure 1.1 - For Loop #2
Figure 1.2 - Foreach Loop
Figure 1.3 - Foreach Loop Sample with Output on Right Panel
Figure 1.4 - For Loop Sample
Figure 1.5 - Foreach Loop with Multidimensional Array (Input)
Figure 1.6 - Foreach Loop with Multidimensional Array (Output)
Figure 1.7 - While Loop with Multidimensional Array (Input)
Figure 1.8 - While Loop with Multidimensional Array (Output)
Figure 1.9 - Foreach Loop Used as Template in HTML (Input)
Figure 1.9 - Foreach Loop Used as Template in HTML (Output)
Data Type: Booleans & Comparisons
● Booleans represent two values - true and false.
Conditional Statements
● Conditional statements (if, else if etc); The conditionals are used to branch our
code depending on whether a certain condition is true or false.
Figure 1.0 - If Condition (Input)
Figure 1.1 - If Condition (Output)
Figure 1.2 - If Condition HTML Template (Input)
Figure 1.3 - If Condition HTML Template (Output)
Continue & Break
● Continue and break are two important keywords in PHP. It can also be used to
break out of the normal loop cycle.
Functions
● Functions are an important part of pretty much every programming language,
and allow us to create callable blocks of code that can be reused.
Figure 1.0 - Functions Diagram
Figure 1.1 - FormatProduct() Function
Figure 1.2 - SayHello Function
Figure 1.3 - SayHello Function with Default Value
Figure 1.4 -Sample of Function
Variable Scope
● Local variables are declared within a function and have its scope only in that
particular function.
● In PHP global variables must be declared global inside a function if they are
going to be used in that function.
● Global variables refer to any variable that is defined outside of the function.
Include & Require
● Two (2) functions: include & require - used to import other PHP files
● Include function continues with the code even if there is an error while the
require function does not continue with the code when it encounters an error.
Figure 1.0 - Include Function (Input #1)
Figure 1.1 - Include Function (Input #2)
Figure 1.2 - Include Function (Output)
Figure 1.3 - Another Way of Writing Require and Include Function
Figure 1.4 - Include Function Inside HTML Body (Input)
Figure 1.5 - Content.php
Figure 1.6 - Include Function Inside HTML Body (Output)
Project Header & Footer Template
● https://materializecss.com/getting-started.html - CSS / mobile responsiveness
Figure 1.0 - Header & Footer Template (index.php)
Figure 1.1 - Header & Footer Template (header.php)
Figure 1.2 - Header & Footer Template (footer.php)
Figure 1.3 - Header & Footer Template (Output)
Forms in PHP
● Capture data, send POST & GET requests, and requests on the server
● GET & POST - both methods can be used to send data to the server
● GET sends the data in the URL
● POST sends the data in the request header (hidden)
● The isset() function checks whether a variable is set, which means that it has to
be declared and is not NULL.
● When making a get request using a form, all of the different parameters or data
that we send is going to be stored on the server in the $_GET global variable
and, likewise, if the request is via post method, it gets stored in the $_POST
global variable.
Figure 1.0 - Diagram of Browser to Server
Figure 1.1 - Form with Post Method
Figure 1.2 - Form with Get Method (Output)
Figure 1.3 - Form with Post Method (Output)
XSS Attacks
● XSS Attacks (Cross Site Scripting) - injects malicious and harmful code which
can occur anywhere a website gets data from an end user such as a form
wherein a javascript code is inputted into the form.
● The htmlspecialchars() function converts some predefined characters to HTML
entities.
● HTML entities - safe string version codes for special characters.
● Always use htmlspecialchars() function so that the data to be outputted will be
surrounded by that function and prevent XSS attacks.
Figure 1.0 - Sample of XSS (Input)
Figure 1.1 - Post Method with Htmlspecialchars() Function
Figure 1.2 - Sample of XSS (Output)
Basic Form Validation (Part 1)
● First step of some very basic form validation to check our input fields have not
been left empty
● The empty() function checks whether a variable is empty or not.
● The following values evaluates to empty: 0, 0.0, "0", "", NULL, FALSE, array()
Figure 1.0 - Form Validation Check with Empty() Function (Input)
Figure 1.1 - Form Validation Check with Empty() Function (Output)
Filters & More Validation
● Add some more validation for the form by using PHP filters and some Regex.
● Regex - A regular expression is a sequence of characters that specifies a search
pattern. Usually such patterns are used by string-searching algorithms for "find"
or "find and replace" operations on strings, or for input validation. It
● The filter_var() function filters a variable with the specified filter. Syntax:
filter_var(variable, filtername, options)
● PHP Predefined Filter Constants:
https://www.w3schools.com/php/php_ref_filter.asp
● The preg_match() function returns whether a match was found in a string.
Syntax: preg_match(pattern, input, matches, flags, offset)
● Reference:
https://github.com/iamshaunjp/php-mysql-tutorial/blob/lesson-20/add.php
Figure 1.0 - Form Validation with PHP Filter and Regex (Input)
Figure 1.1 - Form Validation with PHP Filter and Regex(Output #1)
Figure 1.2 - Form Validation with PHP Filter and Regex(Output #2)
Showing Errors
● To display errors on a web form, as well as persist data that a user has
previously entered.
● Reference:
https://github.com/iamshaunjp/php-mysql-tutorial/blob/lesson-21/add.php
Figure 1.0 - Form Validation (Input)
Figure 1.1 - Form Validation (Output)
Checking for Errors & Redirecting
● Redirect a user to another page after checking there are no errors in the form
submission.
● At the bottom of PHP code for the form, we need to check if there are any errors
using array_filter() method.
● The array_filter() function filters the values of an array using a callback function.
Syntax: array_filter(array, callback function, flag)
● The header() function sends a raw HTTP header to a client. Syntax:
header(header, replace, http_response_code)
● It is important to notice that the header() function must be called before any
actual output is sent!
● Use header() function to redirect to another page.
● Note: We only want to send data to the database if it’s valid.
Figure 1.0 - Checking for Error with Array_filter() Function (Input #1)
Figure 1.1 - Checking for Error with Array_filter() Function (Output #1)
Figure 1.2 - Passed Validation and Redirecting to index.php using Header() Function
MySQL Introduction
● MySQL is used to store data in.
● Relational database management system
● We use SQL to communicate with the database from PHP
● SQL = Structured Query Language
● Foreign Key is used to link the tables together
● Can contain several tables
● Each table stores a particular model of data (ex. Pizzas, Users)
● Each row represents a single record (ex. a Single Pizza)
● Each column represents a property of that record
● We use SQL to communicate with the database from PHP code
Figure 1.0 - MySQL Tables
Figure 1.1 - MySQL Tables with Data in Rows and Columns
Figure 1.2 - MySQL Foreign Keys Diagram
Figure 1.3 - MySQL Pizzas Database Diagram
Setting Up a MySQL Database
● Set up a MySQL database using phpMyAdmin.
● In phpMyAdmin, in the Tables section, the A_I should be checked. A_I stands for
auto-increment, it is especially useful for ID property.
● Max length for varchar is 255, (according to the tutorial).
● Use the timestamp for the created_at property.
Figure 1.0 - List of Databases
Figure 1.1 - List of Tables in Database
Figure 1.2 - Character Sets Table
Figure 1.3 - Users Associated with our Different Tables and Databases
Figure 1.4 - Create Database
Figure 1.5 - Create Table
Figure 1.6 - Create Properties for the Table
Figure 1.7 - Table Structure
Figure 1.8 - Insert New Data
Figure 1.9 - Added to the Database Table
Figure 1.10 - First Record in the Database Table
Connecting to a Database
● Connect to our new database from the PHP code.
● Two options: MySQLi or PDO
● MySQLi (MySQL improved) - allows us to code in a more procedural manner.
● PDO (PHP Data Objects) - uses objects
● In connecting to a database, the first step is to store connection references in a
variable.
● The mysqli_connect() function opens a new connection to the MySQL server.
Syntax: mysqli_connect(host, username, password, dbname, port, socket)
● The mysqli_connect_error() function returns the error description from the last
connection error, if any.
Figure 1.0 - Add New User Account
Figure 1.1 - New User Account Created
Figure 1.2 - Connecting to Database with PHP code
Figure 1.3 - Error when Something Wrong with the Input in Mysqli_connect() Function
Getting Data From a Database
● Use SQL to select (get) some data from a database.
● Process: (1) construct the MySQL query, and then (2) make the query, and then
(3) fetch the results from that query, and then (4) free result from memory, and
then (5) close the connection
● The mysqli_query() function performs a query against a database.
Syntax: mysqli_query(connection, query, resultmode)
● The mysqli_fetch_all() function fetches all result rows and returns the result-set
as an associative array, a numeric array, or both.
Syntax: mysqli_fetch_all(result, resulttype)
● Optional. Specifies what type of array that should be produced. Can be one of
the following values:
○ MYSQLI_ASSOC
○ MYSQLI_NUM (this is default)
○ MYSQLI_BOTH
● The print_r() function prints the information about a variable in a more
human-readable way.
● The mysqli_free_result() function frees the memory associated with the result.
● The mysqli_close() function closes a previously opened database connection.
Figure 1.0 - Getting Data from a Database with PHP
Figure 1.1 - Output from Getting Data from Database with Displayed Data on Browser
Figure 1.2 - Getting Data from a Database Process
Figure 1.3 - MySQL Query with ORDER BY command
Rendering Data to the Browser
● Take the data we get from the database and render it to the browser inside our
HTML template.
● Cycle through the variable with mysqli_fetch_all() function containing the
associative array of some data and output the data.
Figure 1.0 - Cycle Through the Variable with Mysqli_fetch_all() Function
Figure 1.1 - Output on the Browser
-/he Explode Function
● Use explode function to turn comma separated list of data into an array of data
instead.
● The explode() function breaks a string into an array.
Syntax: explode(separator,string,limit)
Figure 1.0 - PHP Explode Function
Figure 1.1 - PHP Explode Function (Output)
Figure 1.2 - PHP Explode Function used in Foreach Loop
Figure 1.3 - PHP Explode Function used in Foreach Loop (Output)
Control Flow Alt Syntax
● A cleaner way to write control flow statements in our HTML templates.
● The endforeach keyword is used to close the code block of a foreach loop which
was started using the foreach(...): syntax.
● Exclude curly braces in php foreach loop.
● PHP offers an alternative syntax for some of its control structures; namely, if,
while, for, foreach, and switch. In each case, the basic form of the alternate
syntax is to change the opening brace to a colon (:) and the closing brace to
endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
Figure 1.0 - Endforeach Keyword Used and Excluded Curly Braces
Saving Data to the Database
● Save data to MySQL database with a SQL command called INSERT.
● The mysqli_real_escape_string() function escapes special characters in a
string for use in an SQL query, taking into account the current character set of
the connection. It protects data going into the database or from MySQL
injection attacks.
Syntax: mysqli_real_escape_string(connection, escapestring)
● Reference:
https://github.com/iamshaunjp/php-mysql-tutorial/blob/lesson-30/add.php
Figure 1.0 - Add.php
Figure 1.1 - Index.php
Figure 1.2 - Externalized Connecting to Database
Figure 1.3 - Saving Data to Database (Output #1)
Figure 1.4 - Saving Data to Database (Output #2)
Getting a Single Record
● Retrieve a single record from the database and show it on the web page.
● 1st is to check the GET request id parameter with the isset() function.
● Use mysqli_real_escape_string() function with the GET ID request to protect
sensitive information in the database.
● 2nd is to make SQL query
● 3rd is to get the query result through the mysqli_query() function.
● 4th is to fetch the result in array format with mysqli_fetch_all() function.
● 5th is to free result from memory with mysqli_free_result() function.
● 6th is to close the database connection with mysqli_close() function.
Figure 1.0 - Getting the ID for each Pizza Value on Index.php
Figure 1.1 - Details.php #1
Figure 1.2 - Output with Getting ID
Figure 1.3 - Use Print_r Function to Output Result
Figure 1.4 - Use Print_r Function to Output Result (Output)
Figure 1.5 - Getting a Single Record on Details.php
Figure 1.6 - Getting a Single Record on Details.php (Output)
Deleting a Record
● Delete a record from the MySQL database.
● Use a form for delete which is going to contain one hidden input containing the ID
of the data (or in this case the pizza) that we would like to delete so that will be
the value of the import.
● Then we're going to have a submit button which will say delete which is going to
make a post request, take that value the ID from the hidden input field.
● When we run PHP we're going to detect if the submit button was pressed by
using the isset() function with POST method.
● Use SQL DELETE statement to delete existing records in a table.
● Use mysqli_real_escape_string() function when deleting data from user to host to
take out harmful code the user might inject.
Figure 1.0 - Deleting a Record
Figure 1.1 - Deleting a Record (Output)
Finishing Touches on the Design
● Improve CSS code, add images, and edit text style
Figure 1.0 - Add Image (Input)
Figure 1.1 - Adjustments on CSS
Figure 1.2 - Finishing Touches on the Design (Output)
Ternary Operators
● Alternative to using if statement.
● A condition followed by a question mark ( ? ), then an expression to execute if
the condition is truthy followed by a colon ( : ), and finally the expression to
execute if the condition is falsy.
Super Globals
● The concept of superglobals in PHP and SERVER superglobal.
● Super global variables are built-in variables that are always available in all
scopes.
● $_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
● $_SERVER['SERVER_NAME'] - Returns the name of the host server (such as
www.w3schools.com)
● $_SERVER['REQUEST_METHOD'] - Returns the request method used to
access the page (such as POST)
● $_SERVER['SCRIPT_FILENAME'] - Returns the absolute pathname of the
currently executing script
● $_SERVER['PHP_SELF'] - Returns the filename of the currently executing script
● Reference: https://www.w3schools.com/php/php_superglobals_server.asp
Figure 1.0 - Super Globals
Figure 1.1 - Super Globals (Output)
Sessions
● Use Sessions to persist data from one page to another.
● A session is a way to store information (in variables) to be used across multiple
pages.
● A session is started with the session_start() function.
● Session variables are set with the PHP global variable: $_SESSION.
● To remove all global session variables and destroy the session, use
session_unset() and session_destroy().
● $_SERVER['QUERY_STRING'] - Returns the query string if the page is
accessed via a query string.
● Note: The session_start() function must be the very first thing in your document.
Before any HTML tags.
Figure 1.1 - Session_start() Function
Null Coalescing
● Returns the value of $x. The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2. Operator: ??
● Use Null Coalescing if we don’t know if the value exists or to avoid errors.
Figure 1.0 - Null Coalescing (Input)
Figure 1.1 - Null Coalescing (Output)
Figure 1.1 - Session_unset() Function
Figure 1.2 - Session Output #1
Figure 1.3 - Session Output #2
Figure 1.4 - Session Output #3