How to download a CSV file in PHP that is triggered through a URL ?
Last Updated :
11 Jun, 2020
Why do we need to download CSV files?
Comma-Separated Values or CSV files are an important part of computer science. Almost every dataset required for training data science models are in CSV file format. Datasets are available all over the internet and it becomes the utmost necessity to have them readily on one's machine be it someone's personal computer or on a server. On the server end, one can train his or her web models with various data sets easily if the person can develop a server-side system to easily download a CSV file on the server via any URL pointing to a data set.
How we can download CSV files triggered through a URL?
Downloading a CSV file through a URL is very easy with
PHP and we will discuss here how to achieve that to download a CSV file on both server end and client end.
For server end download:
To achieve this, we need a PHP function
file_get_contents(). This is an inbuilt PHP function that reads the contents of a file in a string type. The function uses a memory mapping technique with a cache on the server end. Hence, this is a preferable choice for our very purpose.
Syntax:
file_get_contents($path, $include_path,
$context, $start, $max_length)
Parameters: The function has got one mandatory parameter which the
$path and the rest are optional.
- $path: It holds the path or the URL of the file concerned.
- $include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1.
- $context: It is used to specify a context.
- $max_length: It is used to restrict the bytes to be read.
Return Value: Returns back the read data from the file or False if the process is failure.
Example 1: The simple example demonstrates how a CSV file can be downloaded on the server end with the
file_get_contents() function.
php
<?php
// Initialize a file URL to the variable
$url = 'Sample-Spreadsheet-10-rows.csv';
// Use basename() function to return
// the base name of file
$file_name = basename($url);
// Checking if the file is a
// CSV file or not
$info = pathinfo($file_name);
if ($info["extension"] == "csv") {
/* Use file_get_contents() function
to get the file from url and use
file_put_contents() function to save
the file by using base name */
if(file_put_contents( $file_name,
file_get_contents($url))) {
echo "File downloaded successfully";
}
else {
echo "File downloading failed.";
}
}
else echo "Sorry, that's not a CSV file";
?>
Output:
The response the browser will show on successful execution.

The file downloaded in the server directory.
For client end download: Forcing a CSV file on the client end through PHP is cakewalk with a PHP inbuilt function called
readfile() method. The function reads a file and passes it to the output buffer.
Syntax:
readfile($filename, $include_path, $context)
Parameters:
- $filename: The name of the file to be read.
- $include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1.
- $context: It is used to specify a context.
Return Value: On success returns the number of bytes read, else it returns False.
Example 2: The simple following program demonstrates downloading csv file on client end machine with the use of
readfile() function.
php
<?php
$url = "Sample-Spreadsheet-10-rows.csv";
echo "Your file is being checked. <br>";
// Use basename() function to return
// the base name of file
$file_name = basename($url);
$info = pathinfo($file_name);
// Checking if the file is a
// CSV file or not
if ($info["extension"] == "csv") {
/* Informing the browser that
the file type of the concerned
file is a MIME type (Multipurpose
Internet Mail Extension type).
Hence, no need to play the file
but to directly download it on
the client's machine. */
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header(
"Content-Disposition: attachment; filename=\""
. $file_name . "\"");
echo "File downloaded successfully";
readfile ($url);
}
else echo "Sorry, that's not a CSV file";
exit();
?>
Output:
Similar Reads
How to append data in JSON file through HTML form using PHP ?
The purpose of this article is to append data to a JSON file through HTML form using PHP. Approach 1: If the JSON file is not created then we create a new JSON file, send data to it, and append data in it. To see how to create a JSON file by taking data from the HTML form, refer this link. Approach
4 min read
How to automatically start a download in PHP ?
This post deals with creating a start downloading file using PHP. The idea is to make a download button which will redirect you to another page with the PHP script that will automatically start the download. Creating a download button: html <!DOCTYPE html> <html> <head> <meta na
2 min read
How to read data from a file stored in XAMPP webserver using PHP ?
We have given a file stored on XAMPP server and the task is to read the file from server and display the file content on the screen using PHP. We use some PHP functions to solve this problem. File: A file is set of data stored in a disk in different formats. For example - .txt, .exe, .pdf etc fopen
2 min read
How to make PDF file downloadable in HTML link using PHP ?
In web development, it is common to provide users with downloadable resources, such as PDF files. If you want to create a downloadable PDF link using HTML and PHP, this article will guide you through the process of making a PDF file downloadable when the user clicks on a link. ApproachCreate an HTML
3 min read
How to post data using file_get_contents in PHP ?
The file_get_contents() function in PHP is used to read the contents of a file and make HTTP requests using GET and get HTTP responses using POST methods. The HTTP POST request can be made using the $context parameter of the file_get_contents() function, which posts the specified data to the URL spe
3 min read
How to test a URL for 404 error in PHP?
Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without using cURL library. cURL: The cURL stands for âClient for URLsâ, originally with URL spelled in uppercase to make it obvious
2 min read
How to copy a file from one directory to another using PHP ?
The copy() function in PHP is used to copy a file from source to target or destination directory. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure. Syntax: bool
2 min read
How to get parameters from a URL string in PHP?
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions.Note: The page URL and the parameters are separated by the ? character.parse_url() FunctionThe parse_url() function is used to return the components of a URL by parsing it. It parses a URL and return
2 min read
How to Convert Query String to an Array in PHP?
In this article, we will see how to convert a query string to an array in PHP. The Query String is the part of the URL that starts after the question mark(?).Examples:Input: str = "company=GeeksforGeeks&address=Noida&mobile=9876543210"Output: Array ( [company] => GeeksforGeeks [ad
4 min read
How to Convert File Content to Byte Array in PHP ?
Converting file content to a byte array in PHP is a useful technique for various applications, including file manipulation, data processing, and when working with binary files like images or PDFs. PHP offers multiple ways to read file content and convert it into a byte array, providing flexibility t
5 min read