Sending email messages are very common for a web application, for example, sending welcome email when a user create an account on your website, sending newsletters to your registered users, or getting user feedback or comment through website’s contact form, and so on.
You can use the PHP built-in mail() function for creating and sending email messages to one or more recipients dynamically from your PHP application either in a plain-text form or formatted HTML. The basic syntax of this function can be given with:
mail(to, subject, message, headers, parameters)
The following table summarizes the parameters of this function.
Parameter
Description
Required — The following parameters are required
to
The recipient’s email address.
subject
Subject of the email to be sent. This parameter i.e. the subject line cannot contain any newline character (\n).
message
Defines the message to be sent. Each line should be separated with a line feed-LF (\n). Lines should not exceed 70 characters.
Optional — The following parameters are optional
headers
This is typically used to add extra headers such as “From”, “Cc”, “Bcc”. The additional headers should be separated with a carriage return plus a line feed-CRLF (\r\n).
parameters
Used to pass additional parameters.
Sending Plain Text Emails
The simplest way to send an email with PHP is to send a text email. In the example below we first declare the variables — recipient’s email address, subject line and message body — then we pass these variables to the mail() function to send the email.
Example
<?php
$to = '[email protected]';
$subject = 'Marriage Proposal';
$message = 'Hi Jane, will you marry me?';
$from = '[email protected]';
// Sending email
if(mail($to, $subject, $message)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Sending HTML Formatted Emails
When you send a text message using PHP, all the content will be treated as simple text. We’re going to improve that output, and make the email into a HTML-formatted email.
To send an HTML email, the process will be the same. However, this time we need to provide additional headers as well as an HTML formatted message.
Example
<?php
$to = '[email protected]';
$subject = 'Marriage Proposal';
$from = '[email protected]';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Create email headers
$headers .= 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = '<html><body>';
$message .= '<h1 style="color:#f40;">Hi Jane!</h1>';
$message .= '<p style="color:#080;font-size:18px;">Will you marry me?</p>';
$message .= '</body></html>';
// Sending email
if(mail($to, $subject, $message, $headers)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Note: However, the PHP mail() function is a part of the PHP core but you need to set up a mail server on your machine to make it really work.
In the next two chapters (PHP Form Handling and PHP Form Validation) you will learn how to implement an interactive contact form on your website to receive the user’s comment and feedback through emails using this PHP send mail feature.
Although you can store data using cookies but it has some security issues. Since cookies are stored on user’s computer it is possible for an attacker to easily modify a cookie content to insert potentially harmful data in your application that might break your application.
Also every time the browser requests a URL to the server, all the cookie data for a website is automatically sent to the server within the request. It means if you have stored 5 cookies on user’s system, each having 4KB in size, the browser needs to upload 20KB of data each time the user views a page, which can affect your site’s performance.
You can solve both of these issues by using the PHP session. A PHP session stores data on the server rather than user’s computer. In a session based environment, every user is identified through a unique number called session identifier or SID. This unique session ID is used to link each user with their own information on the server like emails, posts, etc.
Tip: The session IDs are randomly generated by the PHP engine which is almost impossible to guess. Furthermore, because the session data is stored on the server, it doesn’t have to be sent with every browser request.
Starting a PHP Session
Before you can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID for the user.
The PHP code in the example below simply starts a new session.
Example
<?php
// Starting session
session_start();
?>
The session_start() function first checks to see if a session already exists by looking for the presence of a session ID. If it finds one, i.e. if the session is already started, it sets up the session variables and if doesn’t, it starts a new session by creating a new session ID.
Note: You must call the session_start() function at the beginning of the page i.e. before any output generated by your script in the browser, much like you do while setting the cookies with setcookie() function.
Storing and Accessing Session Data
You can store all your session data as key-value pairs in the $_SESSION[] superglobal array. The stored data can be accessed during lifetime of a session. Consider the following script, which creates a new session and registers two session variables.
To access the session data we set on our previous example from any other page on the same web domain — simply recreate the session by calling session_start() and then pass the corresponding key to the $_SESSION associative array.
However, to destroy a session completely, simply call the session_destroy() function. This function does not need any argument and a single call destroys all the session data.
Note: Before destroying a session with the session_destroy() function, you need to first recreate the session environment if it is not already there using the session_start() function, so that there is something to destroy.
Every PHP session has a timeout value — a duration, measured in seconds — which determines how long a session should remain alive in the absence of any user activity. You can adjust this timeout duration by changing the value of session.gc_maxlifetime variable in the PHP configuration file (php.ini).
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user’s computer. They are typically used to keeping track of information such as username that the site can retrieve to personalize the page when user visit the website next time.
Tip: Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request.
Setting a Cookie in PHP
The setcookie() function is used to set a cookie in PHP. Make sure you call the setcookie() function before any output generated by your script otherwise cookie will not set. The basic syntax of this function can be given with:
The parameters of the setcookie() function have the following meanings:
Parameter
Description
name
The name of the cookie.
value
The value of the cookie. Do not store sensitive information since this value is stored on the user’s computer.
expires
The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default value is 0.
path
Specify the path on the server for which the cookie will be available. If set to /, the cookie will be available within the entire domain.
domain
Specify the domain for which the cookie is available to e.g www.example.com.
secure
This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection exists.
Tip: If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the session i.e. when the browser closes.
Here’s an example that uses setcookie() function to create a cookie named username and assign the value value John Carter to it. It also specify that the cookie will expire after 30 days (30 days * 24 hours * 60 min * 60 sec).
Example
<?php
// Setting a cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>
Note: All the arguments except the name are optional. You may also replace an argument with an empty string (“”) in order to skip that argument, however to skip the expire argument use a zero (0) instead, since it is an integer.
Warning: Don’t store sensitive data in cookies since it could potentially be manipulated by the malicious user. To store the sensitive data securely use sessions instead.
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It typically an associative array that contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. The individual cookie value can be accessed using standard array notation, for example to display the username cookie set in the previous example, you could use the following code.
Example
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>
The PHP code in the above example produce the following output.
John Carter
It’s a good practice to check whether a cookie is set or not before accessing its value. To do this you can use the PHP isset() function, like this:
Example
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
?>
You can use the print_r() function like print_r($_COOKIE); to see the structure of this $_COOKIE associative array, like you with other arrays.
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie name and any value (such as an empty string) however this time you need the set the expiration date in the past, as shown in the example below:
Example
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Normally, you don’t necessarily need to use any server side scripting language like PHP to download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click on the link, browser will automatically downloads that file.
Example
<a href="downloads/test.zip">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>
Clicking a link that points to a PDF or an Image file will not cause it to download to your hard drive directly. It will only open the file in your browser. Further you can save it to your hard drive. However, zip and exe files are downloaded automatically to the hard drive by default.
Forcing a Download Using PHP
You can force images or other kind of files to download directly to the user’s hard drive using the PHP readfile() function. Here we’re going to create a simple image gallery that allows users to download the image files from the browser with a single mouse click.
Let’s create a file named “image-gallery.php” and place the following code inside it.
If you see the above example code carefully, you’ll find the download link pints to a “download.php” file, the URL also contains image file name as a query string. Also, we’ve used PHP urlencode() function to encode the image file names so that it can be safely passed as URL parameter, because file names may contain URL unsafe characters.
Here’s the complete code of “download.php” file, which force image download.
Example
<?php
if(isset($_REQUEST["file"])){
// Get parameters
$file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
/* Test whether the file name contains illegal characters
such as "../" using the regular expression */
if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
$filepath = "images/" . $file;
// Process download
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
die();
} else {
http_response_code(404);
die();
}
} else {
die("Invalid file name!");
}
}
?>
Similarly, you can force download other files formats like word doc, pdf files, etc.
The regular expression in the above example (line no-8) will simply not allow those files whose name starts or ends with a dot character (.), for example, it allows the file names such as kites.jpg or Kites.jpg, myscript.min.js but do not allow kites.jpg. or .kites.jpg.
In this tutorial we will learn how to upload files on remote server using a Simple HTML form and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files and a wide range of other file types.
Step 1: Creating an HTML form to upload the file
The following example will create a simple HTML form that can be used to upload files.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="upload-manager.php" method="post" enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
</form>
</body>
</html>
Note: In addition to a file-select field the upload form must use the HTTP post method and must contain an enctype="multipart/form-data" attribute. This attribute ensures that the form data is encoded as mulitpart MIME data — which is required for uploading the large quantities of binary data such as image, audio, video, etc.
Step 2: Processing the uploaded file
Here’s the complete code of our “upload-manager.php” file. It will store the uploaded file in a “upload” folder on permanent basis as well as implement some basic security check like file type and file size to ensure that users upload the correct file type and within the allowed limit.
Example
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
Note: The above script prevents uploading a file with the same name as an existing file in the same folder. However, if you want to allow this just prepend the file name with a random string or timestamp, like $filename = time() . '_' . $_FILES["photo"]["name"];
You might be wondering what this code was all about. Well, let’s go through each part of this example code one by one for a better understanding of this process.
Explanation of Code
Once the form is submitted information about the uploaded file can be accessed via PHP superglobal array called $_FILES. For example, our upload form contains a file select field called photo (i.e. name="photo"), if any user uploaded a file using this field, we can obtains its details like the name, type, size, temporary name or any error occurred while attempting the upload via the $_FILES["photo"] associative array, like this:
$_FILES["photo"]["name"] — This array value specifies the original name of the file, including the file extension. It doesn’t include the file path.
$_FILES["photo"]["type"] — This array value specifies the MIME type of the file.
$_FILES["photo"]["size"] — This array value specifies the file size, in bytes.
$_FILES["photo"]["tmp_name"] — This array value specifies the temporary name including full path that is assigned to the file once it has been uploaded to the server.
$_FILES["photo"]["error"] — This array value specifies error or status code associated with the file upload, e.g. it will be 0, if there is no error.
The PHP code in the following example will simply display the details of the uploaded file and stores it in a temporary directory on the web server.
Tip: Once a file has been successfully uploaded, it is automatically stored in a temporary directory on the server. To store this file on a permanent basis, you need to move it from the temporary directory to a permanent location using the PHP’s move_uploaded_file() function.
In the previous chapter you’ve learned how to work with files in PHP. Similarly, PHP also allows you to work with directories on the file system, for example, you can open a directory and read its contents, create or delete a directory, list all files in the directory, and so on.
Creating a New Directory
You can create a new and empty directory by calling the PHP mkdir() function with the path and name of the directory to be created, as shown in the example below:
Example
<?php
// The directory path
$dir = "testdir";
// Check the existence of directory
if(!file_exists($dir)){
// Attempt to create directory
if(mkdir($dir)){
echo "Directory created successfully.";
} else{
echo "ERROR: Directory could not be created.";
}
} else{
echo "ERROR: Directory already exists.";
}
?>
To make the mkdir() function work, the parent directories in the directory path parameter has to exist already, for example, if you specify the directory path as testdir/subdir than the testdir has to exist otherwise PHP will generate an error.
Copying Files from One Location to Another
You can copy a file from one location to another by calling PHP copy() function with the file’s source and destination paths as arguments. If the destination file already exists it’ll be overwritten. Here’s an example which creates a copy of “example.txt” file inside backup folder.
Example
<?php
// Source file path
$file = "example.txt";
// Destination file path
$newfile = "backup/example.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to copy file
if(copy($file, $newfile)){
echo "File copied successfully.";
} else{
echo "ERROR: File could not be copied.";
}
} else{
echo "ERROR: File does not exist.";
}
?>
To make this example work, the target directory which is backup and the source file i.e. “example.txt” has to exist already; otherwise PHP will generate an error.
Listing All Files in a Directory
You can use the PHP scandir() function to list files and directories inside the specified path.
Now we’re going to create a custom function that will recursively list all files in a directory using PHP. This script will be helpful if you’re working with deeply nested directory structure.
Example
<?php
// Define a function to output files in a directory
function outputFiles($path){
// Check directory exists or not
if(file_exists($path) && is_dir($path)){
// Scan the files in this directory
$result = scandir($path);
// Filter out the current (.) and parent (..) directories
$files = array_diff($result, array('.', '..'));
if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$path/$file")){
// Display filename
echo $file . "<br>";
} else if(is_dir("$path/$file")){
// Recursively call the function if directories found
outputFiles("$path/$file");
}
}
} else{
echo "ERROR: No files found in the directory.";
}
} else {
echo "ERROR: The directory does not exist.";
}
}
// Call the function
outputFiles("mydir");
?>
Listing All Files of a Certain Type
While working on directory and file structure, sometimes you might need to find out certain types of files within the directory, for example, listing only .text or .png files, etc. You can do this easily with the PHP glob() function, which matches files based on the pattern.
The PHP code in the following example will search the documents directory and list all the files with .text extension. It will not search the subdirectories.
Example
<?php
/* Search the directory and loop through
returned array containing the matched files */
foreach(glob("documents/*.txt") as $file){
echo basename($file) . " (size: " . filesize($file) . " bytes)" . "<br>";
}
?>
The glob() function can also be used to find all the files within a directory or its subdirectories. The function defined in the following example will recursively list all files within a directory, just like we’ve done in previous example with the scandir() function.
Example
<?php
// Define a function to output files in a directory
function outputFiles($path){
// Check directory exists or not
if(file_exists($path) && is_dir($path)){
// Search the files in this directory
$files = glob($path ."/*");
if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$file")){
// Display only filename
echo basename($file) . "<br>";
} else if(is_dir("$file")){
// Recursively call the function if directories found
outputFiles("$file");
}
}
} else{
echo "ERROR: No such file found in the directory.";
}
} else {
echo "ERROR: The directory does not exist.";
}
}
// Call the function
outputFiles("mydir");
?>
Since PHP is a server side programming language, it allows you to work with files and directories stored on the web server. In this tutorial you will learn how to create, access, and manipulate files on your web server using the PHP file system functions.
Opening a File with PHP fopen() Function
To work with a file you first need to open the file. The PHP fopen() function is used to open a file. The basic syntax of this function can be given with:
fopen(filename, mode)
The first parameter passed to fopen() specifies the name of the file you want to open, and the second parameter specifies in which mode the file should be opened. For example:
Example
<?php
$handle = fopen("data.txt", "r");
?>
The file may be opened in one of the following modes:
Modes
What it does
r
Open the file for reading only.
r+
Open the file for reading and writing.
w
Open the file for writing only and clears the contents of file. If the file does not exist, PHP will attempt to create it.
w+
Open the file for reading and writing and clears the contents of file. If the file does not exist, PHP will attempt to create it.
a
Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it.
a+
Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it.
x
Open the file for writing only. Return FALSE and generates an error if the file already exists. If the file does not exist, PHP will attempt to create it.
x+
Open the file for reading and writing; otherwise it has the same behavior as ‘x’.
If you try to open a file that doesn’t exist, PHP will generate a warning message. So, to avoid these error messages you should always implement a simple check whether a file or directory exists or not before trying to access it, with the PHP file_exists() function.
Example
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to open the file
$handle = fopen($file, "r");
} else{
echo "ERROR: File does not exist.";
}
?>
Tip: Operations on files and directories are prone to errors. So it’s a good practice to implement some form of error checking so that if an error occurs your script will handle the error gracefully. See the tutorial on PHP error handling.
Closing a File with PHP fclose() Function
Once you’ve finished working with a file, it needs to be closed. The fclose() function is used to close the file, as shown in the following example:
Example
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
/* Some code to be executed */
// Closing the file handle
fclose($handle);
} else{
echo "ERROR: File does not exist.";
}
?>
Note: Although PHP automatically closes all open files when script terminates, but it’s a good practice to close a file after performing all the operations.
Reading from Files with PHP fread() Function
Now that you have understood how to open and close files. In the following section you will learn how to read data from a file. PHP has several functions for reading data from a file. You can read from just one character to the entire file with a single operation.
Reading Fixed Number of Characters
The fread() function can be used to read a specified number of characters from a file. The basic syntax of this function can be given with.
fread(file handle, length in bytes)
This function takes two parameter — A file handle and the number of bytes to read. The following example reads 20 bytes from the “data.txt” file including spaces. Let’s suppose the file “data.txt” contains a paragraph of text “The quick brown fox jumps over the lazy dog.”
Example
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
// Read fixed number of bytes from the file
$content = fread($handle, "20");
// Closing the file handle
fclose($handle);
// Display the file content
echo $content;
} else{
echo "ERROR: File does not exist.";
}
?>
The above example will produce the following output:
The quick brown fox
Reading the Entire Contents of a File
The fread() function can be used in conjugation with the filesize() function to read the entire file at once. The filesize() function returns the size of the file in bytes.
Example
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
// Reading the entire file
$content = fread($handle, filesize($file));
// Closing the file handle
fclose($handle);
// Display the file content
echo $content;
} else{
echo "ERROR: File does not exist.";
}
?>
The above example will produce the following output:
The quick brown fox jumps over the lazy dog.
The easiest way to read the entire contents of a file in PHP is with the readfile() function. This function allows you to read the contents of a file without needing to open it. The following example will generate the same output as above example:
Example
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Reads and outputs the entire file
readfile($file) or die("ERROR: Cannot open the file.");
} else{
echo "ERROR: File does not exist.";
}
?>
The above example will produce the following output:
The quick brown fox jumps over the lazy dog.
Another way to read the whole contents of a file without needing to open it is with the file_get_contents() function. This function accepts the name and path to a file, and reads the entire file into a string variable. Here’s an example:
Example
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Reading the entire file into a string
$content = file_get_contents($file) or die("ERROR: Cannot open the file.");
// Display the file content
echo $content;
} else{
echo "ERROR: File does not exist.";
}
?>
One more method of reading the whole data from a file is the PHP’s file() function. It does a similar job to file_get_contents() function, but it returns the file contents as an array of lines, rather than a single string. Each element of the returned array corresponds to a line in the file.
To process the file data, you need to iterate over the array using a foreach loop. Here’s an example, which reads a file into an array and then displays it using the loop:
Example
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Reading the entire file into an array
$arr = file($file) or die("ERROR: Cannot open the file.");
foreach($arr as $line){
echo $line;
}
} else{
echo "ERROR: File does not exist.";
}
?>
Writing the Files Using PHP fwrite() Function
Similarly, you can write data to a file or append to an existing file using the PHP fwrite() function. The basic syntax of this function can be given with:
fwrite(file handle, string)
The fwrite() function takes two parameter — A file handle and the string of data that is to be written, as demonstrated in the following example:
Example
<?php
$file = "note.txt";
// String of data to be written
$data = "The quick brown fox jumps over the lazy dog.";
// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");
// Write data to the file
fwrite($handle, $data) or die ("ERROR: Cannot write the file.");
// Closing the file handle
fclose($handle);
echo "Data written to the file successfully.";
?>
In the above example, if the “note.txt” file doesn’t exist PHP will automatically create it and write the data. But, if the “note.txt” file already exist, PHP will erase the contents of this file, if it has any, before writing the new data, however if you just want to append the file and preserve existing contents just use the modea instead of w in the above example.
An alternative way is using the file_put_contents() function. It is counterpart of file_get_contents() function and provides an easy method of writing the data to a file without needing to open it. This function accepts the name and path to a file together with the data to be written to the file. Here’s an example:
Example
<?php
$file = "note.txt";
// String of data to be written
$data = "The quick brown fox jumps over the lazy dog.";
// Write data to the file
file_put_contents($file, $data) or die("ERROR: Cannot write the file.");
echo "Data written to the file successfully.";
?>
If the file specified in the file_put_contents() function already exists, PHP will overwrite it by default. If you would like to preserve the file’s contents you can pass the special FILE_APPEND flag as a third parameter to the file_put_contents() function. It will simply append the new data to the file instead of overwitting it. Here’s an example:
Example
<?php
$file = "note.txt";
// String of data to be written
$data = "The quick brown fox jumps over the lazy dog.";
// Write data to the file
file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file.");
echo "Data written to the file successfully.";
?>
Renaming Files with PHP rename() Function
You can rename a file or directory using the PHP’s rename() function, like this:
Example
<?php
$file = "file.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to rename the file
if(rename($file, "newfile.txt")){
echo "File renamed successfully.";
} else{
echo "ERROR: File cannot be renamed.";
}
} else{
echo "ERROR: File does not exist.";
}
?>
Removing Files with PHP unlink() Function
You can delete files or directories using the PHP’s unlink() function, like this:
Example
<?php
$file = "note.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to delete the file
if(unlink($file)){
echo "File removed successfully.";
} else{
echo "ERROR: File cannot be removed.";
}
} else{
echo "ERROR: File does not exist.";
}
?>
The following table provides the overview of some other useful PHP filesystem functions that can be used for reading and writing the files dynamically.
Function
Description
fgetc()
Reads a single character at a time.
fgets()
Reads a single line at a time.
fgetcsv()
Reads a line of comma-separated values.
filetype()
Returns the type of the file.
feof()
Checks whether the end of the file has been reached.
is_file()
Checks whether the file is a regular file.
is_dir()
Checks whether the file is a directory.
is_executable()
Checks whether the file is executable.
realpath()
Returns canonicalized absolute pathname.
rmdir()
Removes an empty directory.
Please check out the PHP filesystem reference for other useful PHP filesystem functions.
The include() and require() statement allow you to include the code contained in a PHP file within another PHP file. Including a file produces the same result as copying the script from the file specified and pasted into the location where it is called.
You can save a lot of time and work through including files — Just store a block of code in a separate file and include it wherever you want using the include() and require() statements instead of typing the entire block of code multiple times. A typical example is including the header, footer and menu file within all the pages of a website.
The basic syntax of the include() and require() statement can be given with:
include("path/to/filename"); -Or- include "path/to/filename"; require("path/to/filename"); -Or- require "path/to/filename";
Tip: Like the print and echo statements, you can omit the parentheses while using the include and require statements as demonstrated above.
The following example will show you how to include the common header, footer and menu codes which are stored in separate ‘header.php’, ‘footer.php’ and ‘menu.php’ files respectively, within all the pages of your website. Using this technique you can update all pages of the website at once by making the changes to just one file, this saves a lot of repetitive work.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tutorial Republic</title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body>
</html>
Difference Between include and require Statements
You might be thinking if we can include files using the include() statement then why we need require(). Typically the require() statement operates like include().
The only difference is — the include() statement will only generate a PHP warning but allow script execution to continue if the file to be included can’t be found, whereas the require() statement will generate a fatal error and stops the script execution.
Example
<?php require "my_variables.php"; ?>
<?php require "my_functions.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php displayTitle($home_page); ?></title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body>
</html>
Tip: It is recommended to use the require() statement if you’re including the library files or files containing the functions and configuration variables that are essential for running your application, such as database configuration file.
The include_once and require_once Statements
If you accidentally include the same file (typically functions or classes files) more than one time within your code using the include or require statements, it may cause conflicts. To prevent this situation, PHP provides include_once and require_once statements. These statements behave in the same way as include and require statements with one exception.
The include_once and require_once statements will only include the file once even if asked to include it a second time i.e. if the specified file has already been included in a previous statement, the file is not included again. To better understand how it works, let’s check out an example. Suppose we’ve a ‘my_functions.php’ file with the following code:
Example
<?php
function multiplySelf($var){
$var *= $var; // multiply variable by itself
echo $var;
}
?>
Here’s is the PHP script within which we’ve included the ‘my_functions.php’ file.
Example
<?php
// Including file
require "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
// Including file once again
require "my_functions.php";
// Calling the function
multiplySelf(5); // Doesn't execute
?>
When you run the above script, you will see the error message something like this: “Fatal error: Cannot redeclare multiplySelf()”. This occurs because the ‘my_functions.php’ included twice, this means the function multiplySelf() is defined twice, which caused PHP to stop script execution and generate fatal error. Now rewrite the above example with require_once.
Example
<?php
// Including file
require_once "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
// Including file once again
require_once "my_functions.php";
// Calling the function
multiplySelf(5); // Output: 25
?>
As you can see, by using require_once instead of require, the script works as we expected.
The PHP date() function convert a timestamp to a more readable date and time.
The computer stores dates and times in a format called UNIX Timestamp, which measures time as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January 1, 1970 i.e. January 1, 1970 00:00:00 GMT ).
Since this is an impractical format for humans to read, PHP converts a timestamp to a format that is readable to humans and dates from your notation into a timestamp the computer understands. The syntax of the PHP date() function can be given with.
date(format, timestamp)
The format parameter in the date() function is required which specifies the format of returned date and time. However the timestamp is an optional parameter, if not included then current date and time will be used. The following statement displays today’s date:
Example
<?php
$today = date("d/m/Y");
echo $today;
?>
Note: The PHP date() function return the current date and time according to the built-in clock of the web server on which the script has been executed.
Formatting the Dates and Times with PHP
The format parameter of the date() function is in fact a string that can contain multiple characters allowing you to generate a date string containing various components of the date and time, like day of the week, AM or PM, etc. Here are some the date-related formatting characters that are commonly used in format string:
d – Represent day of the month; two digits with leading zeros (01 or 31)
D – Represent day of the week in text as an abbreviation (Mon to Sun)
m – Represent month in numbers with leading zeros (01 or 12)
M – Represent month in text, abbreviated (Jan to Dec)
y – Represent year in two digits (08 or 14)
Y – Represent year in four digits (2008 or 2014)
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting.
The time() function is used to get the current time as a Unix timestamp (the number of seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
Example
<?php
// Executed at March 05, 2014 07:19:18
$timestamp = time();
echo($timestamp);
?>
The above example produce the following output.
1394003958
We can convert this timestamp to a human readable date through passing it to the previously introduce date() function.
Example
<?php
$timestamp = 1394003958;
echo(date("F d, Y h:i:s", $timestamp));
?>
The above example produce the following output.
March 05, 2014 07:19:18
The PHP mktime() Function
The mktime() function is used to create the timestamp based on a specific date and time. If no date and time is provided, the timestamp for the current date and time is returned.
The syntax of the mktime() function can be given with:
mktime(hour, minute, second, month, day, year)
The following example displays the timestamp corresponding to 3:20:12 pm on May 10, 2014:
Example
<?php
// Create the timestamp for a particular date
echo mktime(15, 20, 12, 5, 10, 2014);
?>
The above example produce the following output.
1399735212
Note: You can leave out as many arguments as you like, and the value corresponding to the current time will be used instead. If you omit all the arguments, the mktime() function will return the UNIX timestamp corresponding to the current date and time, just like time().
The mktime() function can be used to find the weekday name corresponding to a particular date. To do this, simply use the ‘l’ (lowercase ‘L’) character with your timestamp, as in the following example, which displays the day that falls on April 1, 2014:
Example
<?php
// Get the weekday name of a particular date
echo date('l', mktime(0, 0, 0, 4, 1, 2014));
?>
The above example produce the following output.
Tuesday
The mktime() function can also be used to find a particular date in future after a specific time period. As in the following example, which displays the date which falls on after 30 month from the current date?
Example
<?php
// Executed at March 05, 2014
$futureDate = mktime(0, 0, 0, date("m")+30, date("d"), date("Y"));
echo date("d/m/Y", $futureDate);
?>
The above example produce the following output.
05/09/2016
Complete PHP Date Reference
Please check out the PHP Date/Time Functions reference section for a complete list of all the useful date and time functions available in PHP.
A web browser communicates with the server typically using one of the two HTTP (Hypertext Transfer Protocol) methods — GET and POST. Both methods pass the information differently and have different advantages and disadvantages, as described below.
The GET Method
In GET method the data is sent as URL parameters that are usually strings of name and value pairs separated by ampersands (&). In general, a URL with GET data will look like this:
The bold parts in the URL are the GET parameters and the italic parts are the value of those parameters. More than one parameter=value can be embedded in the URL by concatenating with ampersands (&). One can only send simple text data via GET method.
Advantages and Disadvantages of Using the GET Method
Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page with specific query string values.
The GET method is not suitable for passing sensitive information such as the username and password, because these are fully visible in the URL query string as well as potentially stored in the client browser’s memory as a visited page.
Because the GET method assigns data to a server environment variable, the length of the URL is limited. So, there is a limitation for the total data to be sent.
PHP provides the superglobal variable $_GET to access all the information sent either through the URL or submitted through an HTML form using the method="get".
In POST method the data is sent to the server as a package in a separate communication with the processing script. Data sent through POST method will not visible in the URL.
Advantages and Disadvantages of Using the POST Method
It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST.
Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with specific query.
Like $_GET, PHP provide another superglobal variable $_POST to access all the information sent via post method or submitted through an HTML form using the method="post".
PHP provides another superglobal variable $_REQUEST that contains the values of both the $_GET and $_POST variables as well as the values of the $_COOKIE superglobal variable.