PHP version 7 extends the scalar type declaration feature to the return value of a function also. As per this new provision, the return type declaration specifies the type of value that a function should return. We can declare the following types for return types −
int
float
bool
string
interfaces
array
callable
To implement the return type declaration, a function is defined as −
functionmyfunction(type$par1,type$param2):type{# function bodyreturn$val;}
PHP parser is coercive typing by default. You need to declare “strict_types=1” to enforce stricter verification of the type of variable to be returned with the type used in the definition.
Example
In the following example, the division() function is defined with a return type as int.
Since the type checking has not been set to strict_types=1, the division take place even if one of the parameters is a non-integer.
First number: 20.5
Second number: 10
Division: 2
However, as soon as you add the declaration of strict_types at the top of the script, the program raises a fatal error message.
Fatal error: Uncaught TypeError:division():Argument#1 ($x) must be of type int, float given, called in div.php on line 12 and defined in div.php:3
Stack trace:#0 div.php(12): division(20.5, 10)#1 {main}
thrown in div.php on line 3
VS Code warns about the error even before running the code by displaying error lines at the position of error −
Example
To make the division() function return a float instead of int, cast the numerator to float, and see how PHP raises the fatal error −
<?php
// declare(strict_types=1);
function division(int $x, int $y): int {
Uncomment the declare statement at the top and run this code here to check its output. It will show an error −
First number: 20
Second number: 10PHP Fatal error: Uncaught TypeError: division(): Return value must be of type int, float returned in /home/cg/root/14246/main.php:5
Stack trace:
#0 /home/cg/root/14246/main.php(13): division()
#1 {main}
thrown in /home/cg/root/14246/main.php on line 5
The feature of providing type hints has been in PHP since version 5. Type hinting refers to the practice of providing the data type of a parameter in the function definition. Before PHP 7, it was possible to use only the array, callable, and class for type hints in a function. PHP 7 onward, you can also insert type hints for parameters of scalar data type such as int, string, bool, etc.
PHP is a dynamically (and weakly) typed language. Hence, you don’t need to declare the type of the parameter when a function is defined, something which is necessary in a statically type language like C or Java.
A typical definition of function in PHP is as follows −
functionaddition($x,$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}
Here, we assume that the parameters $x and $y are numeric. However, even if the values passed to the function aren’t numeric, the PHP parser tries to cast the variables into compatible type as far as possible.
If one of the values passed is a string representation of a number, and the second is a numeric variable, PHP casts the string variable to numeric in order to perform the addition operation.
A new feature introduced with PHP version 7 allows defining a function with parameters whose data type can be specified within the parenthesis.
PHP 7 has introduced the following Scalar type declarations −
Int
Float
Bool
String
Interfaces
Array
Callable
Older versions of PHP allowed only the array, callable and class types to be used as type hints. Furthermore, in the older versions of PHP (PHP 5), the fatal error used to be a recoverable error while the new release (PHP 7) returns a throwable error.
Scalar type declaration is implemented in two modes −
Coercive Mode − Coercive is the default mode and need not to be specified.
Strict Mode − Strict mode has to be explicitly hinted.
Coercive Mode
The addition() function defined in the earlier example can now be re-written by incorporating the type declarations as follows −
functionaddition(int$x,int$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}
Note that the parser still casts the incompatible types i.e., string to an int if the string contains an integer as earlier.
Obviously, this is because PHP is a weakly typed language, as PHP tries to coerce a variable of string type to an integer. PHP 7 has introduced a strict mode feature that addresses this issue.
Strict Mode
To counter the weak type checking of PHP, a strict mode has been introduced. This mode is enabled with a declare statement −
declare(strict_types=1);
You should put this statement at the top of the PHP script (usually just below the PHP tag). This means that the strictness of typing for scalars is configured on a per-file basis.
In the weak mode, the strict_types flag is 0. Setting it to 1 forces the PHP parser to check the compatibility of the parameters and values passed. Add this statement in the above code and check the result. It will show the following error message −
Fatal error: Uncaught TypeError:addition():Argument#1 ($x) must be of type int, string given,
called in add.php on line 12and defined in add.php:4
Stack trace:#0 add.php(12): addition('10', 20)#1 {main}
thrown in add.php on line 4
Example
Here is another example of scalar type declaration in the function definition. The strict mode when enabled raises fatal error if the incompatible types are passed as parameters.
Uncomment the declare statement at the top of this code and run it. Now it will produce an error −
Fatal error: Uncaught TypeError:
sum(): Argument #2 must be of type int, string given,
called in add.php on line 9 and defined in add.php:4
Stack trace:
#0 add.php(9): sum(2, '3', 4.1)
#1 {main}
thrown in add.php on line 4
The type-hinting feature is mostly used by IDEs to prompt the user about the expected types of the parameters used in the function declaration. The following screenshot shows the VS Code editor popping up the function prototype as you type.
The built-in library of PHP has a wide range of functions that helps in programmatically handling and manipulating date and time information. Date and Time objects in PHP can be created by passing in a string presentation of date/time information, or from the current system’s time.
PHP provides the DateTime class that defines a number of methods. In this chapter, we will have a detailed view of the various Date and Time related methods available in PHP.
The date/time features in PHP implements the ISO 8601 calendar, which implements the current leap-day rules from before the Gregorian calendar was in place. The date and time information is internally stored as a 64-bit number.
Here are the topics we will cover in this chapter −
Getting the Time Stamp with time()
Converting a Time Stamp with getdate()
Converting a Time Stamp with date()
Formatting Date and Time
Converting Strings to Dates
Getting the Time Stamp with time()
PHP’s time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.
time():int
The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.
<?php
print time();
?>
Output
It will produce the following output −
1699421347
We can convert a time stamp into a form that humans are comfortable with.
Converting a Time Stamp with getdate()
The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().
The following table lists the elements contained in the array returned by getdate().
Sr.No
Key & Description
Example
1
secondsSeconds past the minutes (0-59)
20
2
minutesMinutes past the hour (0 – 59)
29
3
hoursHours of the day (0 – 23)
22
4
mdayDay of the month (1 – 31)
11
5
wdayDay of the week (0 – 6)
4
6
monMonth of the year (1 – 12)
7
7
yearYear (4 digits)
1997
8
ydayDay of year ( 0 – 365 )
19
9
weekdayDay of the week
Thursday
10
monthMonth of the year
January
11
0Timestamp
948370048
Now you have complete control over date and time. You can format this date and time in whatever format you want.
The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
date(string$format,?int$timestamp=null):string
The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.
The following table lists the codes that a format string can contain −
Sr.No
Format & Description
Example
1
a‘am’ or ‘pm’ lowercase
pm
2
A‘AM’ or ‘PM’ uppercase
PM
3
dDay of month, a number with leading zeroes
20
4
DDay of week (three letters)
Thu
5
FMonth name
January
6
hHour (12-hour format – leading zeroes)
12
7
HHour (24-hour format – leading zeroes)
22
8
gHour (12-hour format – no leading zeroes)
12
9
GHour (24-hour format – no leading zeroes)
22
10
iMinutes ( 0 – 59 )
23
11
jDay of the month (no leading zeroes
20
12
l (Lower ‘L’)Day of the week
Thursday
13
LLeap year (‘1’ for yes, ‘0’ for no)
1
14
mMonth of year (number – leading zeroes)
1
15
MMonth of year (three letters)
Jan
16
rThe RFC 2822 formatted date
Thu, 21 Dec 2000 16:01:07 +0200
17
nMonth of year (number – no leading zeroes)
2
18
sSeconds of hour
20
19
UTime stamp
948372444
20
yYear (two digits)
06
21
YYear (four digits)
2006
22
zDay of year (0 – 365)
206
23
ZOffset in seconds from GMT
+5
Example
Take a look at this following example −
<?php
print date("m/d/y G.i:s \n", time()) . PHP_EOL;
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
Output
It will produce the following output −
11/08/23 11.23:08
Today is 8 2023f November 2023, at 11.23 am
Formatting Date and Time
You can format the date and time in different ways with the help of the date() function. Here are some examples −
Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions.
MySQL is a popular choice as a backend database for PHP powered web applications. In this chapter, we shall learn to develop a login page for a PHP application that authenticates the given username and password.
You should have a web server having PHP and MySQL installed for experimenting with the example discussed in this chapter. The bundled binaries of Apache, PHP and MySQL (MariaDB) in the form of XAMPP for your operating system can be easily installed.
Before running the example code, you should have a MySQL database called mydb in which there must be a table called admin. You can use following SQL script to create the table and insert a test data
The first part of PHP login application is to establish database connection object. We use myqli API to obtain connection object. Save following code as “config.php”
This PHP script is called inside the login script. It presents the user with a HTML form to enter username and password. In case the form is submitted, PHP runs a SELECT query to retrieve a row in the admin table where the username and passcode matches with the user inputs.
$myusername=mysqli_real_escape_string($db,$_POST['username']);$mypassword=mysqli_real_escape_string($db,$_POST['password']);$sql="SELECT * FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";$result=mysqli_query($db,$sql);$row=mysqli_num_rows($result);
If the row count is one, it indicates that the username and the password entered matches. The username is save to the $_SESSION variable and the browser is directed to welcome.php script.
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT * FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
</style></head><body bgcolor = "#FFFFFF"><div align = "center"><div style = "width:300px; border: solid 1px #333333; " align = "left"><div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div><div style = "margin:30px"><form action = "" method = "post"><label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br /><label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br /><input type = "submit" value = " Submit "/><br /></form><div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div></div></div></div></body></html>
Session.php
The following is thesession.phpcode file. It checks if the session variable is set; then the user credentials will be assigned to the$login_sessionvariable. If not, the user is redirected back to thelogin.phpfile.
<?php
// Start the session
session_start();
if(!isset($_SESSION['login_user'])){
header("location: login.php");
die();
}
$login_session = $_SESSION['login_user'];
?>
Welcome.php
The “welcome.php” script gets invoked when the user is authenticated. It reads the session variable to display a welcome message.
Finally, the logout script removes the destroys the session and redirects the user to the login page.
<?php
session_start();
if(session_destroy()) {
header("Location: login.php");
}
?>
To start the login application, visit “http://localhost/login.php”
Enter the username and password. On pressing the submit button, these inputs are checked against the rows in admin table. On success, you get the following message −
If the query doesnt fetch any matching row, the error message is displayed as follows −
PayPal is a payment processing system. We can integrate PayPal with websites by using with PHP.
PayPal Integration File System
PayPal integration file system included four files as shown below −
constants.php − This file includes the API user name, password and signature.
CallerService.php − This file includes the PayPal Services, which are used to call PayPal services.
confirmation.php − This file includes a form with minimum fields required to make payment process and it will return payment success or failure.
PayPal_entry.php − This page has used to send the user the data to PayPal. It acts as an adapter between PayPal and user form.
The user has to download a PayPal SDK file from here and exact a zip file. The zip file contains four PHP files. We don’t need to change any file except “constants.php”.
constants.php
The “constants.php” file contains code as shown below −
<?php
define('API_USERNAME', 'YOUR USER NAME HERE');
define('API_PASSWORD', 'YOUR PASSWORD HERE');
define('API_SIGNATURE', 'YOUR API SIGNATURE HERE');
define('API_ENDPOINT', 'https://api-3t.paypal.com/nvp');
define('USE_PROXY',FALSE);
define('PROXY_HOST', '127.0.0.1');
define('PROXY_PORT', '808');
define('PAYPAL_URL', 'https://www.PayPal.com/webscr&cmd=_express-checkout&token=');
define('VERSION', '53.0');
?>
The user will declare the username, password and signature in the above syntax which are placed in “constants.php”.
This is an experimental example so the last amount will be added to sandbox’s account.
Users can be asked to log into a web application with the help of Social media login, also called SSO. This way users need not create a new account. Instead, users can use their existing social media account information to log in. Some examples of social media login include: Google, Facebook, LinkedIn, Apple.
In this chapter, we shall explain how to activate logging into a PHP application with Facebook credentials.
The first step to add Facebook login feature is to create a Facebook app. Visit https://developers.facebook.com/apps/creation/ and sign in with your Facebook account.
Next, enter the name of the Facebook app you want to create −
Go in the App settings and obtain Application ID and secret code −
Select platform as website −
Next, you need to set Up Facebook SDK in PHP. Download the Facebook SDK for PHP from “https://packagist.org/packages/facebook/php-sdk” or use composer: composer require “facebook/graph-sdk-v5”. Extract the SDK files to a directory accessible by your PHP application.
To configure Facebook SDK in PHP Code, include the Facebook SDK autoloader in your PHP file: require_once __DIR__ . ‘/vendor/autoload.php’;
]);
$helper = $fb->getRedirectLoginHelper();
$accessToken = $helper->getAccessToken();
if ($accessToken) {
// User is logged in, handle their data
$user = $fb->get('/me', ['fields' => 'id,name,email']);
$_SESSION['user_data'] = $user;
header('Location: profile.php');
} else {
// User is not logged in, redirect to login page
$loginUrl = $helper->getLoginUrl(['scope' => 'public_profile,email']);
header('Location: ' . $loginUrl);
}
?>
After successful login, store user data in the session and redirect to a protected page. On protected pages, check the session for user data to verify access.
A typical PHP web application authenticates the user before logging in, by asking his credentials such as username and password. The credentials are then checked against the user data available with the server. In this example, the user data is available in the form of an associative array. The following PHP Login script is explained below −
HTML Form
The HTML part of the code presents a simple HTML form, that accepts username and password, and posts the data to itself.
The PHP script parses the POST data, and checks if the username is present in the users array. If found, it further checks whether the password corresponds to the registered user in the array
<?php
if (array_key_exists($user, $users)) {
if ($users[$_POST['username']]==$_POST['password']) {
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = $_POST['username'];
$msg = "You have entered correct username and password";
} else {
$msg = "You have entered wrong Password";
}
} else {
$msg = "You have entered wrong user name";
}
?>
The username and the appropriate message is added to the $_SESSION array. The user is prompted with a respective message, whether the credentials entered by him are correct or not.
The Complete Code
Here is the complete code −
Login.php
<?php
ob_start();
session_start();
?><html lang = "en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="loginstyle.css"><title>Login</title></head><body><h2 style="margin-left:10rem; margin-top:5rem;">Enter Username and Password</h2><?php
The DOM extension in PHP comes with extensive functionality with which we can perform various operations on XML and HTML documents. We can dynamically construct a DOM object, load a DOM document from a HTML file or a string with HTML tag tree. We can also save the DOM document to a XML file, or extract the DOM tree from a XML document.
The DOMDocument class is one the most important classes defined in the DOM extension.
$obj=newDOMDocument($version="1.0",$encoding="")
It represents an entire HTML or XML document; serves as the root of the document tree. The DOMDocument class includes definitions of a number of static methods, some of which are introduced here −
Sr.No
Methods & Description
1
createElementCreate new element node
2
createAttributeCreate new attribute
3
createTextNodeCreate new text node
4
getElementByIdSearches for an element with a certain id
5
getElementsByTagNameSearches for all elements with given local tag name
6
loadLoad XML from a file
7
loadHTMLLoad HTML from a string
8
loadHTMLFileLoad HTML from a file
9
loadXMLLoad XML from a string
10
saveDumps the internal XML tree back into a file
11
saveHTMLDumps the internal document into a string using HTML formatting
12
saveHTMLFileDumps the internal document into a file using HTML formatting
13
saveXMLDumps the internal XML tree back into a string
Example
Let us use the following HTML file for this example −
We shall now extract the Document Object Model from the above HTML file by calling the loadHTMLFile() method in the following PHP code −
<?php
/*** a new dom object ***/
$dom = new domDocument;
/*** load the html into the object ***/
$dom->loadHTMLFile("hello.html");
/*** discard white space ***/
$dom->preserveWhiteSpace = false;
/*** the table by its tag name ***/
$tables = $dom->getElementsByTagName('table');
/*** get all rows from the table ***/
$rows = $tables[0]->getElementsByTagName('tr');
/*** loop over the table rows ***/
foreach ($rows as $row) {
/*** get each column by tag name ***/
$cols = $row->getElementsByTagName('td');
PHP has the XML parser extension enabled by default in the php.ini settings file. This parser implements SAX API, which is an event-based parsing algorithm.
An event-based parser doesnt load the entire XML document in the memory. instead, it reads in one node at a time. The parser allows you to interact with in real time. Once you move onto the next node, the old one is removed from the memory.
SAX based parsing mechanism is faster than the tree based parsers. PHP library includes functions to handle the XML events, as explained in this chapter.
The first step in parsing a XML document is to have a parser object, with xml_parse_create() function
xml_parse() parses an XML document. The handlers for the configured events are called as many times as necessary.
The XMLParser extension provides different event handler functions.
xml_set_element_handler()
This function sets the element handler functions for the XML parser. Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags.
The start_handler() function is called when a new XML element is opened. end_handler() function is called when an XML element is closed.
xml_set_character_data_handler()
This function sets the character data handler function for the XML parser parser. Character data is roughly all the non-markup contents of XML documents, including whitespace between tags.
This function sets the processing instruction (PI) handler function for the XML parser parser. <?php ?> is a processing instruction, where php is called the “PI target”. The handling of these are application-specific.
A processing instruction has the following format −
<?target
data
?>
xml_set_default_handler()
This function sets the default handler function for the XML parser parser. What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler.
The following example demonstrates the use of SAX API for parsing the XML document. We shall use the SAX.xml as below −
<?xml version = "1.0" encoding = "utf-8"?><tutors><course><name>Android</name><country>India</country><email>[email protected]</email><phone>123456789</phone></course><course><name>Java</name><country>India</country><email>[email protected]</email><phone>123456789</phone></course><course><name>HTML</name><country>India</country><email>[email protected]</email><phone>123456789</phone></course></tutors>
Example
The PHP code to parse the above document is given below. It opens the XML file and calls xml_parse() function till its end of file is reached. The event handlers store the data in tutors array. Then the array is echoed element wise.
<?php
// Reading XML using the SAX(Simple API for XML) parser
$tutors = array();
$elements = null;
// Called to this function when tags are opened
function startElements($parser, $name, $attrs) {
global $tutors, $elements;
if(!empty($name)) {
if ($name == 'COURSE') {
// creating an array to store information
$tutors []= array();
}
$elements = $name;
}
}
// Called to this function when tags are closed
function endElements($parser, $name) {
global $elements;
if(!empty($name)) {
$elements = null;
}
}
// Called on the text between the start and end of the tags
function characterData($parser, $data) {
The SimpleXML extension of PHP provides a very simple and easy to use toolset to convert XML to an object that can be processed with normal property selectors and array iterators. It is a tree_based parser, and works well with simple XML files, but may face issues when working with larger and complex XML documents.
The following functions are defined in SimpleXML extension −
simplexml_load_file
The simplexml_load_file() function interprets an XML file into an object −
A well-formed XML document in the given file is converted into an object.
The filename parameter is a string representing the XML file to be parsed. class_name is the optional parameter. It specifies the class whose object will be returned by the function. The function returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure.
A well-formed XML document in the given string is converted into an object.
The $data parameter is a string representing the XML document to be parsed. class_name is the optional parameter. It specifies the class whose object will be returned by the function. The function returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure.
This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.
The node parameter is a DOM Element node. The optional class_name may be given so that simplexml_import_dom() will return an object of the specified sub class of the SimpleXMLElement class. The value returned by this function is a SimpleXMLElement or null on failure.
Example
Take a look at the following example −
<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>PHP Handbook</title></book></books>');
if (!$dom) {