PHP Download File

PHP enables you to download file easily using built-in readfile() function. The readfile() function reads a file and writes it to the output buffer.


PHP readfile() function

Syntax

  1. int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )  

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You can set it to true to the search the file in the included_path.

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.


PHP Download File Example: Text File

  

<?php  
   $file_url = 'http://www.tutorialspro.com/f.txt';  
   header('Content-Type: application/octet-stream');  
   header("Content-Transfer-Encoding: utf-8");   
   header("Content-disposition: attachment; filename=\"" . 
   basename($file_url) . "\"");   
   readfile($file_url);  
?>

PHP Download File Example: Binary File

<?php  
   $file_url = 'http://www.myremoteserver.com/file.exe';  
    header('Content-Type: application/octet-stream');  
   header("Content-Transfer-Encoding: Binary");   
   header("Content-disposition: attachment; filename=\"" . 
   basename($file_url) . "\"");   
   readfile($file_url);  
?>  

PHP File Upload

PHP allows you to upload single and multiple files through few lines of code only.

PHP file upload features allows you to upload binary and text files both. Moreover, you can have the full control over the file to be uploaded through PHP authentication and file operation functions.


PHP $_FILES

The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file.

Here, we are assuming that file name is filename.

$_FILES[‘filename’][‘name’]

returns file name.

$_FILES[‘filename’][‘type’]

returns MIME type of the file.

$_FILES[‘filename’][‘size’]

returns size of the file (in bytes).

$_FILES[‘filename’][‘tmp_name’]

returns temporary file name of the file which was stored on the server.

$_FILES[‘filename’][‘error’]

returns error code associated with this file.


move_uploaded_file() function

The move_uploaded_file() function moves the uploaded file to a new location. The move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the POST request.

Syntax

  1. bool move_uploaded_file ( string $filename , string $destination )  

PHP File Upload Example

<form action="uploader.php" method="post" enctype="multipart/form-data">  
    Select File:  
    <input type="file" name="fileToUpload"/>  
    <input type="submit" value="Upload Image" name="submit"/>  
</form>
<?php  
$target_path = "e:/";  
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);   
  
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {  
    echo "File uploaded successfully!";  
} else{  
    echo "Sorry, file not uploaded, please try again!";  
}  
?>  

PHP Delete File

In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only: file name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is deleted successfully otherwise FALSE.

Syntax

  1. bool unlink ( string $filename [, resource $context ] )  

$filename represents the name of the file to be deleted.

PHP Delete File Example

<?php      
$status=unlink('data.txt');    
if($status){  
echo "File deleted successfully";    
}else{  
echo "Sorry!";    
}  
?>  

Output

File deleted successfully

PHP Append to File

You can append data into file by using a or a+ mode in fopen() function. Let’s see a simple example that appends data into data.txt file.

Let’s see the data of file first.

welcome to php file write

PHP Append to File – fwrite()

The PHP fwrite() function is used to write and append data into file.

Example

 

<?php  
$fp = fopen('data.txt', 'a');//opens file in append mode  
fwrite($fp, ' this is additional text ');  
fwrite($fp, 'appending data');  
fclose($fp);  
  
echo "File appended successfully";  
?>

Output:

welcome to php file write this is additional text appending data

PHP Write File

PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File – fwrite()

The PHP fwrite() function is used to write content of the string into file.

Syntax

  1. int fwrite ( resource $handle , string $string [, int $length ] )  

Example

<?php  
$fp = fopen('data.txt', 'w');//opens file in write-only mode  
fwrite($fp, 'welcome ');  
fwrite($fp, 'to php file write');  
fclose($fp);  
  
echo "File written successfully";  
?> 

Output: data.txt

welcome to php file write

PHP Overwriting File

If you run the above code again, it will erase the previous data of the file and writes the new data. Let’s see the code that writes only new data into data.txt file.

<?php  
$fp = fopen('data.txt', 'w');//opens file in write-only mode  
fwrite($fp, 'hello');  
fclose($fp);  
  
echo "File written successfully";  
?>  

Output:

hello

PHP Read File

PHP provides various functions to read data from file. There are different functions that allow you to read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.

  • fread()
  • fgets()
  • fgetc()

PHP Read File – fread()

The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file size.

Syntax

  1. string fread (resource $handle , int $length )  

$handle represents file pointer that is created by fopen() function.

$length represents length of byte to be read.

Example

<?php    
$filename = "c:\\file1.txt";    
$fp = fopen($filename, "r");//open file in read mode    
  
$contents = fread($fp, filesize($filename));//read file    
  
echo "<pre>$contents</pre>";//printing data of file  
fclose($fp);//close file    
?>

Output

this is first line
this is another line
this is third line

PHP Read File – fgets()

The PHP fgets() function is used to read single line from the file.

Syntax

  1. string fgets ( resource $handle [, int $length ] )  

Example

<?php    
     $fp = fopen("c:\\file1.txt", "r");//open file in read mode    
     echo fgets($fp);  
     fclose($fp);  
?> 

Output

this is first line

PHP Read File – fgetc()

The PHP fgetc() function is used to read single character from the file. To get all data using fgetc() function, use !feof() function inside the while loop.

Syntax

  1. string fgetc ( resource $handle )  

Example

<?php    
    $fp = fopen("c:\\file1.txt", "r");//open file in read mode    
     while(!feof($fp)) {  
       echo fgetc($fp);  
          }  
   fclose($fp);  
?>    

Output

this is first line this is another line this is third line

PHP Open File

PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts two arguments: $filename and $mode. The $filename represents the file to be opended and $mode represents the file mode for example read-only, read-write, write-only etc.

Syntax

  1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )  

PHP Open File Mode

ModeDescription
rOpens file in read-only mode. It places the file pointer at the beginning of the file.
r+Opens file in read-write mode. It places the file pointer at the beginning of the file.
wOpens file in write-only mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file.
w+Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file.
aOpens file in write-only mode. It places the file pointer to the end of the file. If file is not found, it creates a new file.
a+Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found, it creates a new file.
xCreates and opens file in write-only mode. It places the file pointer at the beginning of the file. If file is found, fopen() function returns FALSE.
x+It is same as x but it creates and opens file in read-write mode.
cOpens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file
c+It is same as c but it opens file in read-write mode.

PHP Open File Example

<?php  
$handle = fopen("c:\\folder\\file.txt", "r");  
?>