QuickStart with PHP
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 |
|
PHP Output and Variables
- To get output, we can use
echo
andprint
. - Variable names must start with the
$
- PHP automatically associates a data type to the variable, depending on its value
echo
andThe differences are small:
echo
has no return value whileecho
can take multiple parameters (although such usage is rare) whileecho
is marginally faster than
Example
1 |
|
PHP Comments
1 |
|
PHP Type Conversion
1 | $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 stringstr_word_count(var)
- counts the number of words in a stringstrrev(var)
- reverses a stringstrpos(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!
- example:
PHP Array
The array functions allow you to access and manipulate arrays.
array()
- creates an arraycount()
- returns the number of elements in an arraysizeof()
- returns the number of elements in an arrayarray_count_values()
- counts all the values of an arrayarray_keys()
- returns an array containing the keysarray_key_exists()
- checks an array for a specified key, and see if the key exists
The sorting functions:
sort()
- sort arrays in ascending orderrsort()
- sort arrays in descending orderasort()
- sort associative arrays in ascending order, according to the valuearsort()
- sort associative arrays in descending order, according to the valueksort()
- sort associative arrays in ascending order, according to the keykrsort()
- sort associative arrays in descending order, according to the key
1 | $numbers = array(4, 6, 2, 22, 11); |
To create different types of arrays:
Indexed Arrays
1 | //Two ways to create an indexed array |
Loop through an indexed array
1 | $fruits = array("apple", "orange", "pear"); |
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them (store key-value pairs).
1 | //Two ways to create an associative array |
Loop through an Associative array
1 | $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); |
Multidimensional Arrays
1 | $fruits = array ( |
PHP Loops
- while loop
- do…while loop
- for loop
- foreach loop
Foreach loop Example
1 | $colors = array("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 PImin()
- find the lowest value in a list of arugmentsmax()
- find the highest value in a list of arugmentsabs()
- return absolute value of a numbersqrt()
- return square root of a numberround()
- 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 |
|
An Example of PHP Inheritance:
1 |
|
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 | <h2>Welcome to My Website</h2> |
footer.html
1 | <hr> |
website.html
1 | <!DOCTYPE html> |
Example - Include PHP files
post.php
1 |
|
tool.php
1 |
|
blog.html
1 | <!DOCTYPE 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 |
|
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 |
|
1 |
|
feof($myfile)
- return true if end of file (EOF) has been reachedfgets($myfile)
- read a single line- After a call to the
fgets()
function, the file pointer has moved to the next line.
- After a call to the
fgetc($myfile)
- read a single character- After a call to the
fgetc()
function, the file pointer moves to the next character.
- After a call to the
PHP Files - Write
1 |
|
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 |
|
trip.php
1 | <!DOCTYPE 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!