php

File Uploading & Downloading



In PHP, it's a common practice to first upload the files to a temporary directory and then move them to a target destination. This is done to perform additional checks or processing before allowing the file to be permanently stored on the server.

 

Configure “php.ini” File:
In php.ini file, file_uploads = On;

 

Here's an HTML form(`form.html`) and a PHP script(`upload.html`) that allows us to upload file:

 

form.html

<!DOCTYPE html>
	<html lang="en">
	<head>
    	<meta charset="UTF-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>File Upload Form</title>
	</head>
	<body>
    	<h2>File Upload Form</h2>
    	<form action="uploadFIle.php" method="post" enctype="multipart/form-data">
        	<label for="file">Select a file to upload:</label>
        	<input type="file" name="file" id="file" required>
        	<br>
        	<input type="submit" name="submit" value="Upload File">
    	</form>
	</body>
	</html>

 

While Uploading files we need to consider two rules:
 

  1. Method Attribute: Ensure that the form used the `POST` method.
  2. Enctype Attribute: The `enctype` attribute should be set to “multipart/form-data”.

 

uploadFile.php

<?php
    	if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
        	$uploadDir = "uploads/"; // Directory to store uploaded files
        	$uploadedFile = $uploadDir . basename($_FILES["file"]["name"]);
        	$uploadSuccess = move_uploaded_file($_FILES["file"]["tmp_name"], $uploadedFile);

	
        	if ($uploadSuccess) {
            	echo "File uploaded successfully!";
        	} else {
            	echo "Error uploading file.";
        	}
    	}
	?>

 

It checks if the request method is POST and if a file has been uploaded. Then it moves the uploaded file to the specified directory “uploads/” in this case and displays a success or error message.

 

Ensure that the "uploads" directory has the necessary write permissions for the web server. You may need to adjust the directory path based on your server configuration
 

File Downloader:

Let’s create a simple file downloader in PHP which downloads a simple txt file. Below is a basic example of a PHP script that allows users to download a file.
 

downloaderFile.php

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

 

PHP's `readfile()` function simplifies file downloads by efficiently reading a file and streaming its content directly to the output buffer.