<?php
echo "Hello, World!";
?>
Explanation:
<?php ... ?>
is used to write PHP code.echo
outputs text to the browser.- When you run this, it will display Hello, World!.
<?php
echo "Hello, World!";
?>
Explanation:
<?php ... ?>
is used to write PHP code.echo
outputs text to the browser.This PHP cheatsheet provides a quick overview and revision of all concepts of PHP programming and is helpful for students and developers as well. If you are preparing for any exam or an interview, we recommend going through this cheatsheet to learn and enhance your PHP skills.
Use the below syntax to write a PHP script −
<?php // Your PHP code here ?>
You can also use its short echo tag, which is −
<?= "Hello, World!" ?>
You can print “Hello, World!” in PHP using the PHP echo statement.
Open Compiler
<?php echo "Hello, World!"; ?>
PHP provides single and multiline comments. Where a single-line comment starts with # or // and a multiline comment is enclosed within /* and */.
// Write single-line comment here# Write single-line comment here
/* You can write multi-line comment like this*/
PHP variables store data and information. A variable can be declared using the dollar ($) sign followed by the variable name.
<?php $age = 21; $name = "Kelly Hu"; ?>
You can use the PHP echo statement to print variables.
Open Compiler
<?php $age = 21; $name = "Kelly Hu"; echo "My name is $name"; echo "<br>"; echo "I am $age years old."; ?>
You can print a newline using the echo statement by using the “\n” to print a newline in PHP. And, to display a newline in the browser, use the “<br />” tag.
Open Compiler
<?php echo "Hello, World!\n"; echo "This is on a new line.\n"; ?>
Open Compiler
<?php echo "Hello, World!<br>"; echo "This is on a new line.<br>"; ?>
You can print text by using the following functions −
Use echo to print one or more strings.
Open Compiler
<?php echo "Hello, World!", " Hello PHP"; $a = 10; $b = "Okay"; echo "\nValue of a is $a and value of b is $b"; ?>
Use print to print one single string.
Open Compiler
<?php print "Hello, World!"; ?>
Use printf to print formatted string.
Open Compiler
<?php printf("Hello, %s!", "World"); ?>
Use print_r for debugging and displays human-readable information about variables, particularly arrays or objects.
Open Compiler
<?php $arr = array('Hyderabad', 'Bangalore', 'Mangalore'); print_r($arr); ?>
You can embed HTML elements with text using the echo and print function.
Open Compiler
<?php echo "<h1>Hello, World!</h1>"; echo "<p>This is a paragraph.</p>"; ?>
You can also embed PHP inside HTML elements.
Open Compiler
<html><body><h1><?php echo "Welcome to My Website!"; ?></h1><p><?php echo "This is a dynamic paragraph."; ?></p></body></html>
You can include PHP variables within HTML elements as follows −
Open Compiler
<?php $name = "Kelly Hu"; echo "<p>Hello, <em>$name</em>! Welcome to TutorialsPoint.</p>"; ?>
String data type represents a sequence of characters.
$str1="Hello, World!";$str2='PHP Data Types';
Integer data type represents non-decimal numbers between -2,147,483,648 and 2,147,483,647 (on 32-bit systems).
$int=42;
Float (double) data type represents numbers with a fractional part.
$float=3.14;
Boolean data type represents two possible values: TRUE or FALSE.
$is_admin=true;$is_guest=false;
PHP array type stores multiple values in a single variable.
// Indexed array$cities=array("Hyderabad","Bangalore","Mangalore");// Associative array$person=array("name"=>"Kelly Hu","age"=>22);
An array type is an instance of a class.
Open Compiler
<?php class Person {} $p = new Person("Kelly Hu"); echo $p->getName(); // Outputs: Kelly Hu ?>public $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; }
The NULL type represents a variable with no value.
$var=null;
PHP strings are sequences of characters enclosed with either single quotes (‘Hello’) or double quotes (“Hello”).
You can create a string variable by assigning a string to a variable and print it by using the echo statement.
Open Compiler
<?php $str = "Kelly Hu"; echo "Hello, $str!"; ?>
The dot (.) operator can be used to concatenate two strings.
Open Compiler
<?php $str = "Hello" . " " . "World!"; echo $str; ?>
You can use the strlen() method to get the string length.
$len=strlen("Hello");// Output: 5
Some of the commonly used string functions that are used for various string operations are as follows −
Function Name | Use | Example |
---|---|---|
strlen() | Returns the length of a string. | $str=”Hello World!”;echostrlen($str); |
str_word_count() | Returns the number of words in a string. | $str=”Hello World!”;echostr_word_count($str); |
strrev() | Returns the reversed string. | $str=”Hello”;echostrrev($str); |
strpos() | Returns the position of the first occurrence of a substring. | $str=”Hello World!”;echostrpos($str,”World”); |
str_replace() | Replaces some characters with others in a string. | $str=”Hello World!”;echostr_replace(“World”,”Harry”,$str); |
strtolower() | Returns the lowercase converted string. | $str=”HELLO WORLD!”;echostrtolower($str); |
strtoupper() | Returns the uppercase converted string. | $str=”hello world!”;echostrtoupper($str); |
trim() | Removes whitespace or predefined characters from both ends. | $str=” Hello World! “;echotrim($str); |
ltrim() | Removes whitespace or predefined characters from the left side. | $str=” Hello World! “;echoltrim($str); |
rtrim() | Removes whitespace or predefined characters from the right side. | $str=” Hello World! “;echortrim($str); |
str_repeat() | Repeats a string a specified number of times. | $str=”Hi! “;echostr_repeat($str,3); |
substr() | Returns a part of a string. | $str=”Hello World!”;echosubstr($str,6,5); |
ucfirst() | Returns the string having the first character of a string to uppercase. | $str=”hello world!”;echoucfirst($str); |
ucwords() | Returns the string having the first character of each word in a string to uppercase. | $str=”hello world!”;echoucwords($str); |
strcmp() | Compares two strings (case-sensitive). | $str1=”Hello”;$str2=”hello”;echostrcmp($str1,$str2); |
strcasecmp() | Compares two strings (case-insensitive). | $str1=”Hello”;$str2=”hello”;echostrcasecmp($str1,$str2); |
str_shuffle() | Randomly shuffles the characters of a string. | $str=”Hello”;echostr_shuffle($str); |
number_format() | Formats a number with grouped thousands. | $num=1234567.89;echonumber_format($num,2); |
You can go through our reference page to read more about these methods: PHP String Functions Reference.
PHP supports the following escape characters −
Escape Character | Description |
---|---|
\\ | Backslash |
\’ | Single quote |
\” | Double quote |
\n | New line |
\r | Carriage return |
\t | Horizontal tab |
\b | Backspace |
\f | Form feed |
\v | Vertical tab |
\0 | Null character |
\xHH | Hexadecimal value (HH is the hex code) |
\u{HHHH} | Unicode character (PHP 7.2+) |
Open Compiler
<?php echo "Hello\nWorld"; echo "Hello\tWorld.\n"; echo "This is single quote: It\'s Me.\n"; echo "This is double quote: \"Hello, World!\"\n"; echo "This is a backslash: \\\n"; ?>
PHP operators are the symbols used to perform operations on variables and values. The following are the different types of operators −
Operator Type | Operator | Description | Example |
---|---|---|---|
Arithmetic | + | Addition | 5 + 3 (outputs 8) |
– | Subtraction | 5 – 3 (outputs 2) | |
* | Multiplication | 5 * 3 (outputs 15) | |
/ | Division | 5 / 2 (outputs 2.5) | |
% | Modulus (remainder) | 5 % 2 (outputs 1) | |
Assignment | = | Assigns value | $x = 5; |
+= | Adds and assigns | $x += 3; (same as $x = $x + 3;) | |
-= | Subtracts and assigns | $x -= 2; (same as $x = $x – 2;) | |
*= | Multiplies and assigns | $x *= 2; (same as $x = $x * 2;) | |
/= | Divides and assigns | $x /= 2; (same as $x = $x / 2;) | |
%= | Modulus and assigns | $x %= 3; (same as $x = $x % 3;) | |
Comparison | == | Equal (value) | ($x == $y) |
=== | Identical (value and type) | ($x === $y) | |
!= | Not equal | ($x != $y) | |
!== | Not identical (value or type) | ($x !== $y) | |
< | Less than | ($x < $y) | |
> | Greater than | ($x > $y) | |
<= | Less than or equal | ($x <= $y) | |
>= | Greater than or equal | ($x >= $y) | |
Logical | && | Logical AND | ($x && $y) |
|| | Logical OR | ($x || $y) | |
! | Logical NOT | !$x | |
String | . | Concatenation (combines two strings) | $str = “Hello” . ” World”; |
Increment/Decrement | ++ | Increment (adds one) | ++$x or $x++ |
— | Decrement (subtracts one) | –$x or $x– |
Open Compiler
<?php // Arithmetic Operators $a = 10; $b = 3; echo $a + $b; echo $a % $b; // Assignment Operators $x = 5; $x += 2; echo $x; // Comparison Operators var_dump($x == 7); // Logical Operators if ($x > 5 && $x < 10) {} // String Operator $greeting = "Hello, " . "World!"; echo $greeting; // Increment/Decrement Operators echo ++$x; echo $x--; ?>echo "x is between 5 and 10.";
PHP conditional statements are used to execute code based on conditions. The conditional statements are −
Open Compiler
<?php $x = 10; if ($x > 5) {} ?>echo "x is greater than 5";
Open Compiler
<?php $x = 3; if ($x > 5) {} else {echo "x is greater than 5";
} ?>echo "x is not greater than 5";
Open Compiler
<?php $x = 10; if ($x > 10) {} elseif ($x == 10) {echo "x is greater than 10";
} else {echo "x is equal to 10";
} ?>echo "x is less than 10";
Open Compiler
<?php $x = 10; if ($x > 10) {} elseif ($x == 10) {echo "x is greater than 10";
} else {echo "x is equal to 10";
} ?>echo "x is less than 10";
Open Compiler
<?php $day = 3; switch ($day) {} ?>case 1: echo "Monday"; break; case 2: echo "Tuesday"; break; case 3: echo "Wednesday"; break; case 4: echo "Thursday"; break; case 5: echo "Friday"; break; case 6: echo "Saturday"; break; case 7: echo "Sunday"; break; default: echo "Invalid day";
PHP math functions are used for performing various mathematical operations. The following are the math functions −
Function | Example |
---|---|
abs() | echo abs(-5); // Outputs: 5 |
ceil() | echo ceil(4.3); // Outputs: 5 |
floor() | echo floor(4.7); // Outputs: 4 |
round() | echo round(4.5); // Outputs: 5 |
max() | echo max(1, 3, 2); // Outputs: 3 |
min() | echo min(1, 3, 2); // Outputs: 1 |
pow() | echo pow(2, 3); // Outputs: 8 |
sqrt() | echo sqrt(16); // Outputs: 4 |
rand() | echo rand(1, 100); // Outputs: random number |
mt_rand() | echo mt_rand(1, 100); // Outputs: random number |
sin() | echo sin(deg2rad(90)); // Outputs: 1 |
cos() | echo cos(deg2rad(180)); // Outputs: -1 |
tan() | echo tan(deg2rad(45)); // Outputs: 1 |
deg2rad() | echo deg2rad(180); // Outputs: 3.14159 |
rad2deg() | echo rad2deg(M_PI); // Outputs: 180 |
PHP constants are the variables with a fixed value. Constants are defined using define().
Open Compiler
<?php define("SITE_NAME", "MyWebsite"); echo SITE_NAME; ?>
PHP magic constants are special constants with special meanings. The following are the magic constants −
Constant Name | Description |
---|---|
__LINE__ | Current line number of the file. |
__FILE__ | Full path and filename of the file. |
__DIR__ | Directory of the file. |
__FUNCTION__ | Name of the function (case-sensitive). |
__CLASS__ | Name of the class (case-sensitive). |
__METHOD__ | Name of the method (case-sensitive). |
__NAMESPACE__ | Current namespace (empty if none). |
__TRAIT__ | Name of the trait (case-sensitive). |
<?php echo "Current line: " . __LINE__ . "<\n"; echo "Full file path: " . __FILE__ . "<\n"; echo "Directory: " . __DIR__ . "<\n"; function tpFunction() {} class tpClass {echo "Function name: " . __FUNCTION__ . "<\n";
} namespace MyNamespace; echo "Namespace: " . __NAMESPACE__ . "<\n"; ?>public function tpFun() { echo "Method name: " . __METHOD__ . "<\n"; }
PHP loops repeat a block of code multiple times. The following are the types of loops −
Open Compiler
<?php echo "The for Loop:<\n"; for ($i = 0; $i < 10; $i++) {} ?>echo "Iteration: $i<\n";
Open Compiler
<?php echo "The foreach Loop:<\n"; $cities = ['Hyderabad', 'Bangalore', 'Mangalore']; foreach ($cities as $city) {} ?>echo "City: $city<\n";
Open Compiler
<?php echo "The while Loop:<\n"; $count = 0; while ($count < 10) {} ?>echo "Count: $count<\n"; $count++;
Open Compiler
<?php echo "The do...while Loop:<\n"; $count = 0; do {} while ($count < 10); ?>echo "Count: $count<\n"; $count++;
PHP functions are blocks of code that can be executed on demand. The following is an example of a simple function −
Open Compiler
<?php // Defining function function printName($name) {} // Calling function echo printName("Kelly Hu"); ?>return "Hello, " . $name . "!";
PHP arrays are used to store multiple values of the same or different types. The following are the different types of arrays −
Open Compiler
<?php $cities = ["Hyderabad", "Bangalore", "Mangalore"]; // Accessing elements echo $cities[0]; echo $cities[1]; echo $cities[2]; ?>
Open Compiler
<?php // Associative array with named keys $student = []; // Accessing elements by key echo $student["name"]; echo $student["age"]; echo $student["city"]; ?>"name" => "Kelly Hu", "age" => 21, "city" => "Brentwood"
PHP global variables (also known as superglobals) are built-in global arrays that are used to provide information or track variables. The superglobals are:
Superglobal | Description |
---|---|
$_GET | Collects data sent via URL parameters in a GET request. |
$_POST | Collects data sent via HTTP POST method. |
$_REQUEST | Collects data from $_GET , $_POST , and $_COOKIE . |
$_SESSION | Stores data across pages for individual users. |
$_COOKIE | Stores data on the clients browser as small text files. |
$_FILES | Manages file uploads. |
$_ENV | Holds environment variables. |
$_SERVER | Contains information about server and execution environment. |
$_GLOBALS | Accesses all global variables in the PHP script. |
PHP regular expressions are the patterns used for matching strings.
Open Compiler
<?php $email = "[email protected]"; if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {} else {echo "Valid Email.";
} ?>echo "Invalid Email";
Open Compiler
<?php $phone = "1234567890"; if (preg_match("/^\d{10}$/", $phone)) {} else {echo "It's a valid phone number.";
} ?>echo "It's not a valid phone number.";
Open Compiler
<?php $url = "https://www.tutorialspoint.com"; if (preg_match("/\b(?:https?|ftp):\/\/[a-zA-Z0-9-]+\.[a-zA-Z]{2,6}\b/", $url)) {} else {echo "It's a valid URL";
} ?>echo "It's not a valid URL";
PHP form handling is all about collecting and validating the user data via HTML forms. Here is an example −
<form method="post" action="form.php"> Name: <input type="text" name="name"><input type="submit" value="Submit"></form><?php // Check if form was submitted or not if ($_SERVER["REQUEST_METHOD"] == "POST") {} ?>$name = htmlspecialchars($_POST['name']); if (!empty($name)) { echo "Hello, " . $name . "!"; } else { echo "Fill your name."; }
Use the date() function to get the date and time. Here is an example −
Open Compiler
<?php // Get the current date and time echo "Current Date: " . date("Y-m-d") . "<\n"; echo "Current Time: " . date("H:i:s") . "<\n"; echo "Full Date and Time: " . date("Y-m-d H:i:s"); ?>
Use the include statement to include files within another PHP file.
include'header.php';
PHP file handling is used for creating, reading, writing, and managing files.
<?php $file = fopen("file1.txt", "w"); fclose($file); ?>
<?php $file = fopen("file1.txt", "w"); fwrite($file, "Some text to file."); fclose($file); ?>
<?php $file = fopen("file1.txt", "r"); $content = fread($file, filesize("file1.txt")); echo $content; fclose($file); ?>
<?php $file = fopen("file1.txt", "a"); fwrite($file, "\nSome extra text."); fclose($file); ?>
<?php if (file_exists("file1.txt")) {} else {unlink("file1.txt"); echo "DONE.";
} ?>echo "File doesn't exist";
PHP file upload allows you to upload files to the server.
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/".$_FILES["file"]["name"]);
PHP cookies store small pieces of data on the clients computer.
setcookie("user","Kelly Hu",time()+(86400*30),"/");
PHP sessions store data across multiple pages for a user.
session_start();$_SESSION["username"]="Kelly Hu";
PHP filters are used to validate and sanitize data.
$email=filter_var($email,FILTER_VALIDATE_EMAIL);
PHP is very rich in terms of Built-in functions. Here is the list of various important function categories. There are various other function categories which are not covered here.
Select a category to see a list of all the functions related to that category.
PDO is an acronym for PHP Data Objects. PHP can interact with most of the relational as well as NOSQL databases. The default PHP installation comes with vendor-specific database extensions already installed and enabled. In addition to such database drivers specific to a certain type of database, such as the mysqli extension for MySQL, PHP also supports abstraction layers such as PDO and ODBC.
The PDO extension defines a lightweight, consistent interface for accessing databases in PHP. The functionality of each vendor-specific extension varies from the other. As a result, if you intend to change the backend database of a certain PHP application, say from PostGreSql to MySQL, you need to make a lot of changes to the code. The PDO API on the other hand doesnt require any changes apart from specifying the URL and the credentials of the new database to be used.
Your current PHP installation must have the corresponding PDO driver available to be able to work with. Currently the following databases are supported with the corresponding PDO interfaces −
Driver Name | Supported Databases |
---|---|
PDO_CUBRID | Cubrid |
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase |
PDO_FIREBIRD | Firebird |
PDO_IBM | IBM DB2 |
PDO_INFORMIX | IBM Informix Dynamic Server |
PDO_MYSQL | MySQL 3.x/4.x/5.x/8.x |
PDO_OCI | Oracle Call Interface |
PDO_ODBC | ODBC v3 (IBM DB2, unixODBC and win32 ODBC) |
PDO_PGSQL | PostgreSQL |
PDO_SQLITE | SQLite 3 and SQLite 2 |
PDO_SQLSRV | Microsoft SQL Server / SQL Azure |
By default, the PDO_SQLITE driver is enabled in the settings of php.ini, so if you wish to interact with a MySQL database with PDO, make sure that the following line is uncommented by removing the leading semicolon.
extension=pdo_mysql
You can obtain the list of currently available PDO drivers by calling PDO::getAvailableDrivers() static function in PDO class.
An instance of PDO base class represents a database connection. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).
The following snippet is a typical way of establishing connection with a MySQL database −
<?php $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); ?>
If there is any connection error, a PDOException object will be thrown.
Take a look at the following example −
<?php $dsn="localhost"; $dbName="myDB"; $username="root"; $password=""; try{} catch(Exception $e){$dbConn= new PDO("mysql:host=$dsn;dbname=$dbName",$username,$password); Echo "Successfully connected with $dbName database";
} ?>echo "Connection failed" . $e->getMessage();
It will produce the following output −
Successfully connected with myDB database
In case of error −
Connection failedSQLSTATE[HY000] [1049] Unknown database 'mydb'
The PDO class defines the following static methods −
After obtaining the connection object, you should call this method to that initiates a transaction.
publicPDO::beginTransaction():bool
This method turns off autocommit mode. Hence, you need to call commit() method to make persistent changes to the database Calling rollBack() will roll back all changes to the database and return the connection to autocommit mode.This method returns true on success or false on failure.
The commit() method commits a transaction.
publicPDO::commit():bool
Since the BeginTransaction disables the autocommit mode, you should call this method after a transaction. It commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction. This method returns true on success or false on failure.
The exec() method executes an SQL statement and return the number of affected rows
publicPDO::exec(string$statement):int|false
The exec() method executes an SQL statement in a single function call, returning the number of rows affected by the statement.
Note that it does not return results from a SELECT statement. If you have a SELECT statement that is to be executed only once during your program, consider issuing PDO::query().
On the other hand For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute().
The exec() method need a string parameter that represents a SQL statement to prepare and execute, and returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.
The query() method prepares and executes an SQL statement without placeholders
publicPDO::query(string$query,?int$fetchMode=null):PDOStatement|false
This method prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.
The rollback() method rolls back a transaction as initiated by PDO::beginTransaction().
publicPDO::rollBack():bool
If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.
Note that some databases, including MySQL, automatically issue an implicit COMMIT when a DDL statement such as DROP TABLE or CREATE TABLE is issued within a transaction, and hence it will prevent you from rolling back any other changes within the transaction boundary. This method returns true on success or false on failure.
The following code creates a student table in the myDB database on a MySQL server.
<?php $dsn="localhost"; $dbName="myDB"; $username="root"; $password=""; try{} catch(Exception $e){$conn= new PDO("mysql:host=$dsn;dbname=$dbName",$username,$password); Echo "Successfully connected with $dbName database"; $qry = <<<STRING CREATE TABLE IF NOT EXISTS STUDENT ( student_id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL, marks INTEGER(3), PRIMARY KEY (student_id) ); STRING; echo $qry . PHP_EOL; $conn->exec($qry); $conn->commit(); echo "Table created\n";
} ?>echo "Connection failed : " . $e->getMessage();
Use the following code to insert a new record in student table created in the above example −
<?php $dsn="localhost"; $dbName="myDB"; $username="root"; $password=""; try {$conn= new PDO("mysql:host=$dsn;dbname=$dbName",$username,$password); echo "Successfully connected with $dbName database";
} catch(Exception $e){$sql = "INSERT INTO STUDENT values(1, 'Raju', 60)"; $conn->exec($sql); $conn->commit(); echo "A record inserted\n";
} ?>echo "Connection failed : " . $e->getMessage();
The following PHP script fetches all the records in the student table −
<?php $dsn="localhost"; $dbName="myDB"; $username="root"; $password=""; try {$conn= new PDO("mysql:host=$dsn;dbname=$dbName",$username,$password); echo "Successfully connected with $dbName database"; $sql = "SELECT * from student"; $statement = $conn->query($sql); $rows = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e){foreach ($rows as $row) { var_dump($row); }
} ?>echo "Connection failed : " . $e->getMessage();
PHP FastCGI Process Manager (PHP-FPM) is an efficient alternative to traditional CGI-based methods for handling PHP requests, particularly in high-traffic environments. PHP-FPM has a number of important features. These features are as follows −
With the help of a pool of worker processes to handle requests PHP-FPM significantly reduces memory overhead compared to traditional CGI methods that spawn a new process for each request.
PHP-FPM’s worker processes are persistent. It allows them to handle multiple requests. It doesnt need ti repeatedly create and destroy processes. This leads to faster response times and improved handling of high concurrency.
PHP-FPM’s pool of worker processes can be dynamically adjusted based on traffic demands, allowing it to scale effectively to handle varying workloads.
PHP-FPM offers graceful startup and shutdown. It also has granular control over process management, including, emergency restarts, and monitoring of worker processes.
PHP-FPM enables the creation of separate pools for different applications or user groups, so that better isolation and security can be provided for each environment.
PHP-FPM uses php.ini based configuration options. With these extensive options, fine-tuning of its behavior is possible to match specific application requirements.
PHP-FPM can manage multiple PHP versions simultaneously, enabling the deployment of different PHP applications on a single server.
PHP-FPM is commonly used with web servers like Nginx or Apache. It acts as a backend processor for handling PHP requests. It has become the preferred method for managing PHP applications in production environments due to its performance, scalability, and reliability.
The acronym “CSRF” stands for Cross-Site Request Forgery. CSRF is an Internet exploit that involves a trusted website user issuing unauthorized commands. Providing adequate protection to a PHP web application against this attack can be achieved by taking the measures explained in this chapter.
By default, the browser uses the “GET” request method to send data. This is commonly used as the exploit point in a CSRF. To inject commands into a specific website, the attacker employs HTML tags like “IMG.” For example, the url endpoint of a web application such as “/delete.php?empcode=1234” deletes account as passed from empcode parameter of a GET request. Now, if an authenticated user come across the following script in any other application.
<img src="http://example.com/delete.php?empcode=1234" width="0" height="0" border="0">
Inadvertently causes the data related to empcode=1234 to be deleted.
A common workaround for this problem is the use of CSRF tokens. A CSRF token is a string of random characters embedded into requests so that a web application can trust that a request has been received from an expected source as per the normal workflow.
The steps to implement CSRF token protection in PHP are as follows −
Here is the PHP code that implements CSRF token verification mechanism. The following script generates a token and embeds in a HTML form.
<?php session_start(); if(!isset($_SESSION["csrf_token"])) {} else {// No token present, generate a new one $token = md5(uniqid(rand(), true)); $_SESSION["csrf_token"] = $token;
} ?><html><body><form method="get" action="test.php"><input type="text" name="empcode" placeholder="empcode" /><input type="hidden" name="csrf_token" value="<?php echo $token;?>" /><input type="submit" /></form></body></html>// Reuse the token $token = $_SESSION["csrf_token"];
The form is submitted to “test.php” script as below −
<?php session_start(); echo "hello"; if ($_GET["csrf_token"] == $_SESSION["csrf_token"]) {} else {// Reset token echo $_GET["csrf_token"] . "<br>"; echo $_SESSION["csrf_token"] . "<br>"; echo "<h3>CSRF token validation successful. Proceed to further action</h3>";
} ?>echo "<h3>CSRF token validation failed</h3>";
It will produce the following output −
To simulate the failure of CSRF validation, open the inspect tool of the browser, edit the value in the hidden field manually and submit the form to see that the tokens dont match leading to the validation failure.
PEAR is an acronym for PHP Extension and Application Repository. It is a repository of PHP packages or extensions. You can freely incorporate any of these extensions from PEAR in your code. The PEAR project was established by Stig S. Bakken in 1999.
Most of the precompiled distributions of PHP such as XAMPP already have PEAR bundled with it. If not, you can install PEAR by downloading go-pear.phar file from https://pear.php.net/go-pear.phar and run
php go-pear.phar
In a Windows Command Prompt to start the installation.
Based on your responses to the setup steps, the PEAR Package Manager will be installed in the path, specified during installation.
You can then add that installation path to your PATH environment. Either do this manually (Start > Control Panel > System > Environment) or run (double-click) the newly generated PEAR_ENV.reg that’s now found in the PHP source directory.
You can now access the PEAR Package Manager by running the command −
C:\xampp\php>pear
In a Windows Command Prompt.
You will get the list of PEAR commands as follows −
C:\xampp\php>pear Commands: build Build an Extension From C Source bundle Unpacks a Pecl Package channel-add Add a Channel channel-alias Specify an alias to a channel name channel-delete Remove a Channel From the List channel-discover Initialize a Channel from its server channel-info Retrieve Information on a Channel channel-login Connects and authenticates to remote channel server channel-logout Logs out from the remote channel server channel-update Update an Existing Channel clear-cache Clear Web Services Cache config-create Create a Default configuration file config-get Show One Setting config-help Show Information About Setting config-set Change Setting config-show Show All Settings convert Convert a package.xml 1.0 to package.xml 2.0 format cvsdiff Run a "cvs diff"for all files in a package cvstag Set CVS Release Tag download Download Package download-all Downloads each available package from the default channel info Display information about a package install Install Package listList Installed Packages In The Default Channel list-all List All Packages list-channels List Available Channels list-files List Files In Installed Package list-upgrades List Available Upgrades login Connects and authenticates to remote server [Deprecated in favor of channel-login] logout Logs out from the remote server [Deprecated in favor of channel-logout] makerpm Builds an RPM spec file from a PEAR package package Build Package package-dependencies Show package dependencies package-validate Validate Package Consistency pickle Build PECL Package remote-info Information About Remote Packages remote-listList Remote Packages run-scripts Run Post-Install Scripts bundled with a package run-tests Run Regression Tests search Search remote package database shell-test Shell Script Test sign Sign a package distribution file svntag Set SVN Release Tag uninstall Un-install Package update-channels Update the Channel List upgrade Upgrade Package upgrade-all Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]
Installing packages with PEAR is so easy. One way to find packages, is using the official PEAR site https://pear.php.net/packages.php and then run
pear install <package-name>
The next step is to use the PEAR package in your code. To do that, you should include the main PHP script of the package in your program with include, require, include_once or require_once statements.
<?php include "PEARPACKAGE.php"; . . . . . // rest of the code . . . . . ?>
A newer PHP package manager called Composer is an alternative available for managing packages for a PHP project. Composer also supports the installation of PEAR packages. Composer is preferred by many instead of PEAR for PHP package distribution.
With each new version of PHP, new functionality is added and at the same time certain obsolete functionality is removed. PHP version 7 is a major version when a number of PHP extensions and SAPIs (Server-side Application Programming Interface) were removed. In the subsequent PHP 8 version also, a few more extensions have been removed.
In PHP, an extension is a library or plugin, written in C/C++, and compiled into shared libraries so that can be loaded into the PHP interpreter. Once the PHP interpreter starts, the functions in the extension are available to PHP scripts.
The extensions are periodically removed because they are either no longer maintained or have been replaced with more modern alternatives. Coinciding with PHP 7 for example, the ereg extension was replaced with the preg extension, and the mssql extension was replaced with the PDO_MSSQL extension.
The following extensions have been removed with effect from PHP 7 −
The following extensions have been removed from PHP 8 onwards −
SAPI stands for Server-side Application Programming Interface in PHP. The SAPI is responsible for translating PHP code into something that the web server can understand. It parses the PHP code and calls the appropriate web server functions. The web server then generates an HTTP response that is sent back to the client.
The following SAPIs (Server-side Application Programming Interfaces) have been removed from PHP 7 onwards −
As some new features are added with each new version, some features are also removed as they are deemed to be obsolete. In this chapter, we have a look at deprecated features after PHP version 5.
PHP 4 style Constructors are methods having same name as the class they are defined in, are now deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes implementing a __construct() method are unaffected.
Take a look at the following example −
<?php class A {} ?>function A() { print('Style Constructor'); }
It produces the following output on the browser −
Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; A has a deprecated constructor in...
Static calls to non-static methods are deprecated, and may be removed in the future.
Take a look at the following example −
<?php class A {} A::b(); ?>function b() { print('Non-static call'); }
It produces the following output on the browser −
Deprecated: Non-static method A::b() should not be called statically in... Non-static call
The salt option for the password_hash() function has been deprecated so that the developers do not generate their own (usually insecure) salts. The function itself generates a cryptographically secure salt, when no salt is provided by the developer – thus custom salt generation is not required any more.
The capture_session_meta SSL context option has been deprecated. SSL metadata is now used through the stream_get_meta_data() function.
The mcrypt extension has been deprecated in favour of OpenSSL.
Unquoted strings that are non-existent global constants are taken to be strings of themselves. This behaviour used to emit an E_NOTICE, but will now emit an E_WARNING. In the next major version of PHP, an Error exception will be thrown instead.
The __autoload() method has been deprecated because it is inferior to spl_autoload_register() (due to it not being able to chain autoloaders), and there is no interoperability between the two autoloading styles.
Given the security issues of this function has now been deprecated. The preferred alternative is to use anonymous functions.
This function causes implementation issues for some language changes. It has therefore been deprecated.
The declaration of case-insensitive constants has been deprecated. Passing true as the third argument to define() will now generate a deprecation warning.
The (real) cast is deprecated, use (float) instead. The is_real() function is also deprecated, use is_float() instead.
Using parent inside a class without a parent is deprecated, and will throw a compile-time error in the future. Currently an error will only be generated if/when the parent is accessed at run-time.
If a parameter with a default value is followed by a required parameter, the default value has no effect. This is deprecated as of PHP 8.0.0 and can generally be resolved by dropping the default value, without a change in functionality −
<?php function test($a = [], $b) {} // Before function test($a, $b) {} // After ?>
One exception to this rule are parameters of the form Type $param = null, where the null default makes the type implicitly nullable. This usage remains allowed, but it is recommended to use an explicit nullable type instead −
<?php function test(A $a = null, $b) {} // Still allowed function test(?A $a, $b) {} // Recommended ?>
Calling get_defined_functions() with exclude_disabled explicitly set to false is deprecated and no longer has an effect. get_defined_functions() will never include disabled functions.
Sort comparison functions that return true or false will now throw a deprecation warning, and should be replaced with an implementation that returns an integer less than, equal to, or greater than zero.
<?php // Replace usort($array, fn($a, $b) => $a > $b); // With usort($array, fn($a, $b) => $a <=> $b); ?>
The implicit conversion of float to int which leads to a loss in precision is now deprecated. This affects array keys, int type declarations in coercive mode, and operators working on ints.
Calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.
date_sunrise() and date_sunset() have been deprecated. Use date_sun_info() instead.
strptime() has been deprecated. Use date_parse_from_format() instead (for locale-independent parsing), or IntlDateFormatter::parse() (for locale-dependent parsing).
strftime() and gmstrftime() have been deprecated. You can use date() instead (for locale-independent formatting), or IntlDateFormatter::format() (for locale-dependent formatting).
The creation of dynamic properties is deprecated. Instead, use stdClass that allows dynamic properties.
PHP has introduced a new function intdiv(), which performs integer division of its operands and return the division as int.
The intdiv() function returns integer quotient of two integer parameters. If “a/b” results in “c” as division and “r” as remainder such that −
a=b*c+r
In this case, intdiv(a,b) returns r −
intdiv(int$x,int$y):int
The $x and $y are the numerator and denominator parts of the division expression. The intdiv() function returns an integer. The return value is positive if both parameters are positive or both parameters are negative.
If numerator is < denominator, the intdiv() function returns “0”, as shown below −
Open Compiler
<?php $x=10; $y=3; $r=intdiv($x, $y); echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n"; $r=intdiv($y, $x); echo "intdiv(" . $y . "," . $x . ") = " . $r; ?>
It will produce the following output −
intdiv(10,3) = 3 intdiv(3,10) = 0
In the following example, the intdiv() function returns negative integer because either the numerator or denominator is negative.
<?php $x=10; $y=-3; $r=intdiv($x, $y); echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n"; $x=-10; $y=3; $r=intdiv($x, $y); echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n"; ?>
It will produce the following output −
intdiv(10,-3) = -3 intdiv(-10,3) = -3
The intdiv() function returns a positive integer in the case of numerator and denominator both being positive or both being negative.
<?php $x=10; $y=3; $r=intdiv($x, $y); echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n"; $x=-10; $y=-3; $r=intdiv($x, $y); echo "intdiv(" . $x . "," . $y . ") = " . $r ; ?>
It will produce the following output −
intdiv(10,3) = 3 intdiv(-10,-3) = 3
In the following example, the denominator is “0”. It results in DivisionByZeroError exception.
<?php $x=10; $y=0; $r=intdiv($x, $y); echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n"; ?>
It will produce the following output −
PHP Fatal error: Uncaught DivisionByZeroError: Division by zero in hello.php:4