From PHP version 7 onwards, the session_start() function accepts an array of options to override the session configuration directives set in “php.ini”. The [session] session in “php.ini” defines the default values of various options.
The options, if provided, are in the form of an associative array of options that will override the currently set session configuration directives. The keys should not include the “session.” prefix.
Start an HTTP session
For example, you may start the HTTP session with the two session options defined as the parameters of session_start() function −
It specifies the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache.
PHP session options provide extensive control over user sessions. Understanding and using these options allows you to design more secure and versatile web apps. To secure user information, always start your session with session_start() and handle session data properly.
A web session is the time duration between the time a user establishes connection with a server and the time the connection is terminated. Along with the cookies, the session variables make the data accessible across the various pages of an entire website.
During a session, the website maintains information about the user’s actions and preferences. The session data is populated in a super-global associative array $_SESSION.
To start a new session in PHP, you need to call the session_start() function.
Starting a Session
In order to enable access to session data, session_start() function must be invoked. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
session_start(array$options=[]):bool
This function returns true if a session was successfully started, otherwise false.
PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers.
The session_id() function sets or retrieves a unique session ID.
session_id(?string$id=null):string|false
PHP will generate a random session ID, if the $id parameter is not given. You may specify your own ID instead. The function returns the session id for the current session or the empty string if there is no current session. On failure, it returns false.
The browser will show a random string as the output −
Session Id: mi3976f8ssethe9f04vq1ag6it
A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the “php.ini” file called “session.save_path”.
Handling Session Variables
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
To create a new session variable, add a key-value pair in the $_SESSION array −
$_SESSION["var"]=value;
To read back the value of a session variable, you can use echo/print statements, or var_dump() or print_r() functions.
echo$_SESSION["var"];
To obtain the list of all the session variables in the current session, you can use a foreach loop to traverse the $_SESSION −
foreach($_SESSIONas$key=>$val)echo$key."=>".$val;
Example
The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
Use the isset() function to check if a session variable is already set or not.
The following PHP script starts a session when it runs for the first time, and sets a session variable named counter. When the client revisits the same URL again, since the session variable is already set, the counter is incremented.
}
$msg = "Number of visits in this session: ". $_SESSION['counter'];
?><?php
echo "$msg";
?>
Refresh the browser multiple times to simulate repeated visits. The browser displays the counter −
Number of visits in this session: 5
Destroying a PHP Session
A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Here is an example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
You don’t need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.
Example
The following PHP script renders a HTML form. The form data is used to create three session variables. A hyperlink takes the browser to another page, which reads back the session variables.
The worldwide web is powered by HTTP protocol, which is a stateless protocol. The mechanism of Cookies helps the server maintain the information of previous requests. PHP transparently supports HTTP cookies.
Understanding Cookies in PHP
When a client first sends its request, the server includes a small piece of data along with its response as cookies. PHP provides the setcookie() method to inject cookies in the response.
This cookie data is stored in the client’s machine as text files. On subsequent visits of the same client, these cookies are included as a part of the request header.
The server populates the PHP superglobal variable “$_COOKIE” with all the cookies present in the client request.
This chapter will teach you how to set cookies, how to access them and how to delete them.
The Anatomy of a Cookie
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser’s headers might look something like this −
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[“name”].
How to Set a Cookie in PHP?
PHP contains the setcookie function to create a cookie object to be sent to the client along with HTTP response.
Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you actually want to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
Example
The PHP script give below checks if the cookie named username is already set, and retrieves its value, if so. If not, a new cookie username is set.
setcookie("username", "MohanKumar");
echo "<h2>Cookie username is now set</h2>";
}
?>
Run this script from the document root of the Apache server. You should see this message −
Cookie username is now set
If this script is re-executed, the cookie is now already set.
Cookie username already set: MohanKumar
Your browser’s developer tool is a very useful facility. You can set, retrieve and delete cookies with its help. The cookie set by the above program can be viewed under the Application tab of the browser’s developer tools.
A foreach loop as below retrieves all the cookies −
<?php
$arr=$_COOKIE;
foreach ($arr as $key=>$val);
echo "<h2>$key=>$val </h2>";
?>
The following script contains an HTML form. It sends the form data to setcookie.php script, that sets the cookies with the use of data retrieved from the $_POST array.
With another getcookie.php code, we can retrieve the cookies set.
if(isset($_COOKIE["name"])echo"Cookie: name => ".$_COOKIE["name"]."<br>";if(isset($_COOKIE["age"])echo"Cookie: age => ".$_COOKIE["age"]."<br>";
Accessing Cookies with PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
You can use isset() function to check if a cookie is set or not.
If the cookie name contains dots (.), PHP replaces them with underscores (_).
Although the main purpose behind the concept of cookies is to help web developers provide a more personalized and convenient user experience, it may pose a risk to your privacy and personal information.
In some cases, the application may deny you full access you don’t accept their cookies. In such cases, periodically clearing the cookie related data from your browser’s cache is advised.
One of the common features required in a typical PHP web application is the provision of letting the user upload files. Uploading files from a client is very easy in PHP. In this chapter, we shall learn how to use PHP script for the file upload process.
How to Upload a File?
The process of uploading a file follows these steps −
The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.
The full path to the selected file appears in the text filed then the user clicks the submit button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the form’s action attribute checks that the file has arrived and then copies the file into an intended directory.
The PHP script confirms the success to the user.
Configuring File Upload Settings in PHP
In order to perform this activity, we must first ensure that configuration settings related to file upload are enabled in “php.ini”.
Open the “php.ini” file and ensure that the following settings are enabled by removing the leading semicolon (;) symbol in file_uploads, upload_tmp_dir, upload_max_filesize and max_file_uploads parameters −
;;;;;;;;;;;;;;;;; File Uploads ;;;;;;;;;;;;;;;;;; Whether to allow HTTP file uploads.; http://php.net/file-uploads
file_uploads=On
; Temporary directory forHTTP uploaded files(will usesystem;defaultif not specified).; http://php.net/upload-tmp-dir
upload_tmp_dir="C:\xampp\tmp"; Maximum allowed size for uploaded files.; http://php.net/upload-max-filesize
upload_max_filesize=40M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=20
It is necessary that the folders for both temporary and final locations have permissions set that enable file writing. If either is set to be read-only then process will fail.
Creating a File Upload Form
Next, we need to design a HTML form for file upload. The form’s method attribute must be POST and enctype must be multipart/form-data. Use the input type as file to let the user browse and select the file to be uploaded.
The uploadfile.php script receives the uploaded file. The file data is collected in a suparglobal variable $_FILES. Fetch the name, file type, size and the tmp_name attributes of the uploaded file.
The move_uploaded_file() function copies the selected file to the document folder.
Assuming that both the files myform.php and uploadfile.php are stored in the document folder.
Open “myform.php” in the browser (http://localhost/myform.php) −
Click the File button, browse to the desired file to be uploaded, and click the Upload button.
The server responds with the following message −
Error Handling
Handling upload errors is important when giving feedback to users. PHP returns an error code for each file upload, which you can check using $_FILES[‘uploadfile’].[‘error’].
if($_FILES["uploadfile"]["error"]>0){switch($_FILES["uploadfile"]["error"]){caseUPLOAD_ERR_INI_SIZE:echo"<h3>The uploaded file exceeds the upload_max_filesize directive in php.ini.</h3>";break;caseUPLOAD_ERR_FORM_SIZE:echo"<h3>The uploaded file exceeds the MAX_FILE_SIZE directive in the HTML form.</h3>";break;caseUPLOAD_ERR_PARTIAL:echo"<h3>The file was only partially uploaded.</h3>";break;caseUPLOAD_ERR_NO_FILE:echo"<h3>No file was uploaded.</h3>";break;caseUPLOAD_ERR_NO_TMP_DIR:echo"<h3>Missing a temporary folder.</h3>";break;caseUPLOAD_ERR_CANT_WRITE:echo"<h3>Failed to write file to disk.</h3>";break;caseUPLOAD_ERR_EXTENSION:echo"<h3>File upload stopped by extension.</h3>";break;default:echo"<h3>Unknown upload error.</h3>";}}else{move_uploaded_file($_FILES["uploadfile"]["tmp_name"],$target_file);echo"<h3>File Successfully Uploaded</h3>";}
Since PHP is mostly used for web application development, the data sent by the browser client is mainly with the GET and POST types of HTTP request methods. The HTTP protocol also defines other methods for sending the request to the server. They are PUT, DELETE, HEAD and OPTIONS (in addition to GET and POST methods). In this chapter, we shall concentrate on how PHP handles the GET and POST methods.
The GET Method
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.
The GET method produces a long string that appears in your server logs, in the browser’s Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to the server.
GET can’t be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment variable.
The PHP provides $_GET associative array to access all the sent information using GET method.
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?><form action = "<?php <b>$_PHP_SELF</b> ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" /><input type = "submit" /></form>
Output
It will produce the following result −
The POST Method
The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides $_POST associative array to access all the sent information using POST method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?><form action = "<?php <b>$_PHP_SELF</b> ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" /><input type = "submit" /></form>
Output
It will produce the following result −
File Uploads using POST
To handle file uploads in PHP using POST requests, create an HTML form for the file input and a PHP script to process the submitted file.
Example
You will need an HTML form where users can upload files. To properly enable file uploads, the form must have the enctype=”multipart/form-data” tag.
Create an upload.php file to manage file uploads. When you submit the form, this code will handle the data.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Directory where files will be uploaded
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size (e.g., limit to 500KB)
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats (e.g., jpg, png, gif)
if (!in_array($fileType, ['jpg', 'png', 'jpeg', 'gif'])) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
// Attempt to upload the file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
} else {
echo "Invalid request method.";
}
?>
Make sure you set up an uploads directory on your server to store uploaded content. Make sure this directory is readable.
mkdir uploads
chmod 775 uploads
Difference between GET and POST
The main difference between the GET and POST methods is that while the request parameters appended to the URL are exposed in the browser’s URL, the POST data is included in the message body, and not revealed in the URL. Hence, the GET method shouldn’t be used to send sensitive data to the server.
Secondly, the request data in GET method cannot exceed 2048 characters and can consist of ASCII characters only, while with POST method, there is no limit to the request data which can be in binary also (the default maximum size of POST data is determined by post_max_size setting in php.ini file)
PHP provides the following three superglobals to retrieve and process the request parameters −
$_GET − an associative array to access all the sent information using GET method.
$_POST − an associative array to access all the sent information using POST method.
$_REQUEST − an associative array that can be used to get the result from form data sent with both the GET and POST methods.
$_GET Array
You can pass the request parameters in the form of query string directly appended to the URL.
Save the following PHP script in the document root folder (htdocs) as “hello.php” −
Enter “http://localhost/hello.php?first_name=Amar&last_name=Sharma” as the URL in a browser window (ensure that the PHP server is running).
The $_GET array is populated from the request and the output is displayed as below −
First name: Amar Last Name: Sharma
You can also populate the $_GET array with the HTML form data if its method attribute is GET.
Use the following HTML form to collect the data and send it to “hello.php”. Under the document root, save the following script as “hello.html” −
<form action="hello.php" method="get">
First Name: <input type="text" name="first_name"/><br/>
Last Name: <input type="text" name="last_name" /><input type="submit" value="Submit" /></form>
Output
In your browser, enter the URL “http://localhost/hello.html” −
You should get the similar output in the browser window.
$_POST Array
The easiest way to send data to a server with the POST request is specifying the method attribute of HTML form as POST. Assuming that the URL in the browser is “http://localhost/hello.php”, method=POST is set in a HTML form “hello.html” as in the earlier example −
<form action="hello.php" method="post">
First Name: <input type="text" name="first_name"/><br/>
Last Name: <input type="text" name="last_name" /><input type="submit" value="Submit" /></form>
The “hello.php” script (in document root folder) retrieves the form data in the $_POST array and renders it as the HTTP response back to the browser −
Open “http://localhost/hello.html” in your browser. The data entered is retrieved by the server, and rendered back to the client, as in the earlier example.
When developing websites, we generally have to reuse the same information or code in many places. For example, we might want the same header, footer or menu across all pages. PHP allows us to use file inclusion instead of writing the same code many times!
File inclusion saves time, organizes our code and allows us to make simple changes. When we make a change to one file, that changes all other files that contain that file.
Types File Inclusion in PHP
You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.
Include() Function
Require() Function
Include_once() and Require_once() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.
The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
Syntax
Below is the syntax of the includefunction −
include'filename.php';
Here, filename.php is the file you want to include. It can be a relative or absolute path.
Example
Assume you want to create a common menu for your website. Then create a file menu.php with the following content.
Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.
<?php <b>include("menu.php");</b> ?><p>This is an example to show how to include PHP file!</p>
Output
It will produce the following result −
Advantages of include() Method
Using the include() method in PHP has several advantages −
Adding a file allows you to reuse the same content on other pages without having to change any code.
You can add basic website elements like headers, footers, and menus to various pages.
If the included file has an error, include() will only display a warning message and the script will continue to run.
If you need to change the included file (for example, to update the header or footer), do so only once, and the changes will be reflected on all pages that use it.
The require() Function
The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
Syntax
Below is the syntax of the requirefunction −
require'filename.php';
Here, filename.php is a file you want to require. It can be a relative or absolute path.
Example
You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.
<?php include("xxmenu.php"); ?><p>This is an example to show how to include wrong PHP file!</p>
Output
This will produce the following result −
This is an example to show how to include wrong PHP file!
Now lets try same example with require() function.
<?php <b>require("xxmenu.php");</b> ?><p>This is an example to show how to include wrong PHP file!</p>
This time file execution halts and nothing is displayed.
NOTE − You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.
Advantages of require() Method
Using the require() method in PHP has many advantages −
If the required file is important for the page (for example, a database connection file), require() makes sure the script stops and displays an error if it is not found, preventing the page from loading with limited functionality.
The function makes sure all necessary files are always available for proper execution. This is useful for files that the website need to work properly.
Like include(), require() allows you to reuse code across multiple pages.
With require(), you only need to include the required code once, which reduces duplication.
Difference between include() and require() Methods
The require statement is also used to include a file within PHP code. However, there is one important difference between include and require: if a file is included using the include line but PHP cannot find it, the script will continue to run.
The include() function shows a warning and continues execution if the file is missing. While the require() method shows a fatal error and stops execution if the file is missing.
The include() function is basically used for non-critical files for example- header, footer. While require() is used for important files like database connection, configuration.
The include() method can include a file multiple times unless include_once() is used. And the require() includes a file multiple times unless require_once() is used.
The include() continues execution even if the file is not present of missing. And require() stops script execution if the file is missing.
The include_once() and require_once() Function
These functions are useful when you have to make sure a file is only included once.
// config.php
<?php
$database_host = 'localhost';
?>
// settings.php
<?php
// Includes config.php only once
include_once 'config.php';
// It will not include again if called multiple times
require_once 'config.php';
echo "Database host is: $database_host";
?>
Security Risks of File Inclusion
While file inclusion can make your code easier to work with, it may also create security risks, particularly if users have control over which files are included. This is known as Local File Inclusion (LFI) and can be used by attackers.
Example of a Vulnerable Code
In this scenario, a malicious user may gain access to any file on the server by changing the page query parameter, which could result in data breaches or other vulnerabilities. Here is an example code which you should avoid in your PHP applications −
<?php
// User can set the page parameter
$page = $_GET['page'];
// This can lead to dangerous inclusions
include($page);
?>
Prevent File Inclusion Vulnerabilities
Always check and sanitize any user input before using it in an include statement.
<?php
$allowed_pages = ['home.php', 'about.php', 'contact.php'];
if (in_array($page, $allowed_pages)) {
include($page);
} else {
echo "Page not found.";
}
?>
Instead of including files with user-generated content you can consider using predefined paths. If you don’t need remote file inclusion so you can disable it in your php.ini file.
Data types in PHP can be of “scalar type” or “compound type”. Integer, float, Boolean and string types are scalar types, whereas array and object types are classified as compound types. Values of more than one types can be stored together in a single variable of a compound type.
In PHP, objects and arrays are the two compound data types.
An array is an ordered collection of elements of other data types, not necessarily of the same type.
An object is an instance of either a built-in or a user defined class, consisting of properties and methods.
Arrays in PHP
An array is a data structure that stores one or more data values in a single variable. An array in PHP is an ordered map that associates the values to their keys.
There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is to put the array elements inside square brackets.
An array which is a collection of only values is called an indexed array. Each value is identified by a positional index staring from 0.
If the array is a collection of key-value pairs, it is called as an associative array. The key component of the pair can be a number or a string, whereas the value part can be of any type.
The array() Function in PHP
The built-in array() function uses the parameters given to it and returns an object of array type. One or more comma-separated parameters are the elements in the array.
array(mixed...$values):array
Each value in the parenthesis may be either a singular value (it may be a number, string, any object or even another array), or a key-value pair. The association between the key and its value is denoted by the “=>” symbol.
Instead of the array() function, the comma-separated array elements may also be put inside the square brackets to declare an array object. In this case too, the elements may be singular values or a string or another array.
To access any element from a given array, you can use the array[key] syntax. For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.
Note that PHP internally treats the indexed array as an associative array, with the index being treated as the key. This fact can be verified by the var_dump() output of the array.
We can unpack each element of the indexed array in the key and value variables with the foreach syntax −
PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting. An object of stdClass is null to begin with. We can add properties to it dynamically.
A variable of any scalar type can also be converted to an object by type casting. The value of the scalar variable becomes the value of the object’s scalar property.
Heredoc and Nowdoc are PHP methods that allow you to write long strings without using too many quotes or escape characters. They allow you to write multi-line strings in a neat and readable manner.
PHP provides two alternatives for declaring single or double quoted strings in the form of heredoc and newdoc syntax.
Heredoc is useful for including variables, but Nowdoc is useful to get raw text without variable change.
The single quoted string doesn’t interpret the escape characters and doesn’t expand the variables.
On the other hand, if you declare a double quoted string that contains a double quote character itself, you need to escape it by the “\” symbol. The heredoc syntax provides a convenient method.
Heredoc Strings in PHP
The heredoc strings in PHP are much like double-quoted strings, without the double-quotes. It means that they don’t need to escape quotes and expand variables.
Heredoc Syntax
$str=<<<IDENTIFIER
place a string here
it can span multiple lines
and include single quote ' and double quotes "
IDENTIFIER;
First, start with the “<<<” operator. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The string can span multiple lines and includes single quotes () or double quotes (“).
The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string.
Example
The identifier must contain only alphanumeric characters and underscores and start with an underscore or a non-digit character. The closing identifier should not contain any other characters except a semicolon (;). Furthermore, the character before and after the closing identifier must be a newline character only.
Take a look at the following example −
<?php
$str1 = <<<STRING
Hello World
PHP Tutorial
by TutorialsPoint
STRING;
echo $str1;
?>
It will produce the following output −
Hello World
PHP Tutorial
by TutorialsPoint
Example
The closing identifier may or may not contain indentation after the first column in the editor. Indentation, if any, will be stripped off. However, the closing identifier must not be indented further than any lines of the body. Otherwise, a ParseError will be raised. Take a look at the following example and its output −
<?php
$str1 = <<<STRING
Hello World
PHP Tutorial
by TutorialsPoint
STRING;
echo $str1;
?>
It will produce the following output −
PHP Parse error: Invalid body indentation level
(expecting an indentation level of at least 16) in hello.php on line 3
Example
The quotes in a heredoc do not need to be escaped, but the PHP escape sequences can still be used. Heredoc syntax also expands the variables.
<?php
$lang="PHP";
echo <<<EOS
Heredoc strings in $lang expand vriables.
The escape sequences are also interpreted.
Here, the hexdecimal ASCII characters produce \x50\x48\x50
EOS;
?>
It will produce the following output −
Heredoc strings in PHP expand vriables.
The escape sequences are also interpreted.
Here, the hexdecimal ASCII characters produce PHP
Nowdoc Strings in PHP
A nowdoc string in PHP is similar to a heredoc string except that it doesn’t expand the variables, neither does it interpret the escape sequences.
<?php
$lang="PHP";
$str = <<<'IDENTIFIER'
This is an example of Nowdoc string.
it can span multiple lines
and include single quote ' and double quotes "
IT doesn't expand the value of $lang variable
IDENTIFIER;
echo $str;
?>
It will produce the following output −
This is an example of Nowdoc string.
it can span multiple lines
and include single quote ' and double quotes "
IT doesn't expand the value of $lang variable
The nowdoc’s syntax is similar to the heredoc’s syntax except that the identifier which follows the “<<<” operator needs to be enclosed in single quotes. The nowdoc’s identifier also follows the rules for the heredoc identifier.
Heredoc strings are like double-quoted strings without escaping. Nowdoc strings are like single-quoted strings without escaping.
Mathematical operations are important parts of programming. PHP has several built-in math functions that make calculations easy. These functions can be used to round numbers, find maximum and minimum values, work with exponents and logarithms and so on.
In this chapter, we will look at different PHP math functions and mathematical (arithmetic) operators and how they can be used with the help of some examples. If you need to calculate absolute values, round numbers or perform complex mathematical operations, PHP’s math functions make it easy and efficient.
List of Math Functions
Here is the list of functions available in PHP −
Function
Description
abs($num)
Returns the absolute (positive) value of a number.
ceil($num)
Rounds a float number up to the next highest integer.
exp($num)
Returns Euler’s number (e) raised to the power of the given number.
floor($num)
Rounds a float number down to the next lowest integer.
intdiv($x, $y)
Returns the integer quotient of two integers (ignoring remainder).
log10($num)
Returns the base-10 logarithm of a number.
max($values)
Returns the highest value from an array or multiple values.
min($values)
Returns the lowest value from an array or multiple values.
pow($base, $exp)
Returns the result of raising a number to a given power.
round($num, $precision)
Rounds a number to the nearest integer or specified decimal places.
sqrt($num)
Returns the square root of a number.
PHP abs() Function
The abs() function is an in-built function in PHP iterpreter. This function accepts any number as argument and returns a positive value, disregarding its sign. Absolute value of any number is always positive.
abs(mixed$num)
PHP abs() function returns the absolute value of num. If the data type of num is float, its return type will also be float. For integer parameter, the return type is integer.
negative float number: -9.99
absolute value : 9.99
positive float number: 25.55
absolute value : 25.55
negative integer number: -45
absolute value : 45
positive integer number: 25
absolute value : 25
PHP ceil() Function
The ceil() function is an in-built function in PHP iterpreter. This function accepts any float number as argument and rounds it up to the next highest integer. This function always returns a float number as the range of float is bigger than that of integer.
ceil(float$num):float
PHP ceil() function returns the smallest integer value that is bigger than or equal to given parameter.
Example 1
The following code rounds 5.78 to its next highest integer which is 6
The exp() function calculates exponent of e that is Euler Number. PHP has a predefined constant M_E that represents Euler Number and is equal to 2.7182818284590452354. Hence, exp(x) returns 2.7182818284590452354x
This function always returns a float.
exp(float$arg):float
PHP exp() function returns the Euler Number e raised to given arg. Note that e is the base of natural algorithm. The exp() function is the inverse of natural logarithm.
Example 1
One of the predefined constants in PHP is M_LN2 which stands for loge2 and is equal to 0.69314718055994530942. So, the exp() of this value will return 2.
The floor() function is another in-built function in PHP interpreter. This function accepts any float number as argument and rounds it down to the next lowest integer. This function always returns a float number as the range of float is bigger than that of integer.
floor(float$num):float
PHP floor() function returns the largest integer less than or equal to the given parameter.
Example 1
The following example shows how to round 15.05 to its next highest integer which is 15
The intdiv() function returns the integer quotient of two integer parameters. If x/y results in “i” as division and “r” as remainder, then −
x = y*i+r
In this case, intdiv(x,y) returns “i”
intdiv(int$x,int$y):int
The “x” parameter forms numerator part of the division expression, while the “y” parameter forms the denominator part of the division expression.
PHP intdiv() function returns the integer quotient of division of “x” by “y”. The return value is positive if both the parameters are positive or both the parameters are negative.
Example 1
The following example shows that if the numerator is less than the denominator, then intdiv() function returns 0.
The log10 () function calculates the base-10 logarithm of a number. Base-10 logarithm is also called common or standard algorithm. The log10(x) function calculates log10x. It is related to natural algorithm by the following equation −
log10x=logex/loge10 ; So that
log10100=loge100/loge10 =2
In PHP, log10 is represented by log10() function
log10(float$arg):float
PHP log10() function returns the base-10 logarithm of arg.
Example 1
The following code calculates the base-10 logarithm of 100
The max () function returns the highest element in an array, or the highest amongst two or more comma separated parameters.
max(array$values):mixed
Or,
max(mixed$value1[,mixed $...]):mixed
If only one parameter is given, it should be an array of values which may be of same or different types.
If two or more parameters are given, they should be any comparable values of same or different types.
PHP max() function returns the highest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned.
Example 1
The following code returns the highest value from a numeric array.
The min () function returns the lowest element in an array, or the lowest amongst two or more comma separated parameters.
min(array$values):mixed
Or,
min(mixed$value1[,mixed $...]):mixed
If only one parameter is given, it should be an array of values which may be of same or different types
If two or more parameters are given, they should be any comparable values of same or different types
PHP min() function returns the lowest value from the array parameter or sequence of values. Standard comparison operators are applicable. If multiple values of different types evaluate as equal (e.g. 0 and ‘PHP’), the first parameter to the function will be returned
Example 1
The following code returns the smallest value from numeric array.
The pow () function is used to compute the power of a certain number. It returns xy calculation, also termed as x raised to y. PHP also provides “**” as exponentiation operator.
So, pow(x,y) returns xy which is same as x**y.
pow(number$base,number$exp):number
The first parameter is the base to be raised. The second parameter is the power to which base needs to be raised.
PHP pow() function returns the base raised to the power of exp. If both arguments are non-negative integers, the result is returned as integer, otherwise it is returned as a float.
Example 1
The following example calculates 102 using pow() function −
The round() function proves useful in rounding any floating point number upto a desired precision level. Positive precision parameter causes the number to be rounded after the decimal point; whereas with negative precision, rounding occurs before the decimal point. Precision is “0” by default.
For example, round(10.6) returns 11, round(10.2) returns 10. The function always returns a floating point number.
This function also has another optional parameter called mode that takes one of the redefined constants described later.
round(float$value,int$precision,int$mode):float
Parameters
Value − A float number to be rounded.
Precision − Number of decimal digits to round to. Default is 0. Positive precision rounds given number after decimal point. Negative precision rounds the given number before decimal point.
Mode − One of the following predefined constants.
Sr.No
Constant & Description
1
PHP_ROUND_HALF_UPRounds number away from 0 when it is half way there. Hence, 1.5 becomes 2 and -1.5 to -2
2
PHP_ROUND_HALF_DOWNRounds number towards 0 when it is half way there. Hence 1.5 becomes 1 and -1.5 to -1
3
PHP_ROUND_HALF_EVENRounds the number to nearest even value
4
PHP_ROUND_HALF_ODDRounds the number to nearest odd value
PHP round() function returns a float number that by rounding the value to a desired precision.
Example 1
The following code rounds the given number to positive precision values −
The sqrt() function returns the square root of a positive float number. Since square root for a negative number is not defined, it returns NAN. This is one of the most commonly used functions. This function always returns a floating point number.
sqrt(float$arg):float
PHP sqrt() function returns the square root of the given arg number. For negative numbers, the function returns NAN.
Example 1
The following code calculates the square root of 100 −
PHP Files and I/O is the process of reading, writing, creating and deleting files. PHP has various functions for easy file management. We can open a file and write to or read from it. Functions like fopen(), fread() and fwrite() are very useful.
Files allow you to store data for later use. Getting data from files is as simple. File management is important in web applications. It allows for the secure storage and management of data.
This chapter will explain following functions related to files −
Opening a File
Reading a File
Writing a File
Closing a File
Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Sr.No
Mode & Purpose
1
rOpens the file for reading only.Places the file pointer at the beginning of the file.
2
r+Opens the file for reading and writing.Places the file pointer at the beginning of the file.
3
wOpens the file for writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
4
w+Opens the file for reading and writing only.Places the file pointer at the beginning of the file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
5
aOpens the file for writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.
6
a+Opens the file for reading and writing only.Places the file pointer at the end of the file.If files does not exist then it attempts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
Reading a File
Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
Open a file using fopen() function.
Get the file’s length using filesize() function.
Read the file’s content using fread() function.
Close the file with fclose() function.
Example
The following example assigns the content of a text file to a variable then displays those contents on the web page.
<html><head><title>Reading a file using PHP</title></head><body><?php
A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.
Example
The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument