0% found this document useful (0 votes)
22 views

File Upload in PHpnotes

Php file upload

Uploaded by

jaimonjose587
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

File Upload in PHpnotes

Php file upload

Uploaded by

jaimonjose587
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

File Upload in PHP

File upload in PHP allows you to upload files with different extensions to the server.
We can use HTML forms and enable the users to upload files to the server. These files are
stored in a temporary directory unless moved to a target location for permanent storage. But
for the file upload in PHP to work, we have to ensure some configuration settings are set
appropriately.
To configure these settings, we need to find the php.ini file.

The primary settings along with recommended values are:

file_uploads = On

upload_max_filesize = 16M

max_file_uploads = 20

post_max_size = 20M

max_input_time = 60

memory_limit = 128M

max_execution_time = 30

Best Key Settings for File Upload in PHP

 file_uploads: The file_uploads key defines whether to allow file upload or not. By
default, it is set to On, and that’s exactly what we want it to be.

 upload _max_filesize: This key describes the maximum file size allowed while
uploading. When you upload a greater resolution image, it says a file size of (n)MB is
allowed. The default size is set to 2MB. But you can change it according to your
preference and requirement.

 upload_tmp_dir: This is the directory that stores the uploaded file temporarily. You can
set it to anything. However, if you don’t provide a path here, the system will choose a
default path as the temporary directory.

 post_max_size: This key allows you to set the maximum limit for storing the POST data.
When using the file upload in PHP, the file is sent and stored along with POST requests’
data. Thus, it should always be greater than the upload_max_filesize value.

 max_file_uploads: With this key setting, you can configure the number of maximum
files uploaded through a single request. The default value for the max_file_uploads key is
20.
 max_input_time: This directive defines the maximum amount of time allowed for the
PHP script to parse the input data of the uploaded file(s). The value is specified in
seconds, and 60 seconds is usually a good amount.

 memory_limit: The key indicates the maximum memory the PHP script can consume.
The default size is 128MB, which is a considerable amount. However, if you are still
facing challenges while uploading large files, increase the number. Another thing worth
noting is always to keep the number greater than that of the post_max_size value.

 max_execution_time: It indicates the maximum number of time in seconds allowed for


the script to run. The value of this key should be directly proportional to the size of the
files uploaded.

Creating the HTML Form for File Upload in PHP

Now that we are done with the configuration settings let's move ahead with creating an
HTML form for uploading the file. For this, we will be creating thefileupload1.php file and
save it inside a folder.

<!DOCTYPE html>

<html>

<head>

<title>Upload File</title>

</head>

<body>

<form action="fileupload2.php" method="post" enctype="multipart/form-data">

<label for="fileToUpload">Select file to upload:</label>

<input type="file" name="fileToUpload" id="fileToUpload">

<input type="submit" value="Upload File" name="submit">

</form>

</body>
</html>

Some Important Things to Note From the Form

There are some things to note in the above HTML form.

 action="fileUpload2.php": The value in the action field refers to the file that will handle
the file upload in PHP. We will create the file in a moment.

 method="POST": This value indicates the browser about the script’s action to upload
the selected file.

 enctype="multipart/form-data": This value refers to the content type of the files that
will be accepted for uploading. It also indicates the type of encoding that the PHP script
will use for uploading. The multipart/form-data value enables us to upload files using the
POST method. It also ensures the characters of the files are not encoded while submitting
the form. Besides multipart/form-data, enctype also accepts application/x-www-form-
urlencoded and text/plain values.

Running the file through the server will allow you to browse and choose any file from your
computer.

Creating the Upload Logic for File Upload in PHP

The HTML form represents the client-side code. Now that our form is ready, let’s move
towards the server-side scripting to handle the file upload in PHP. Below is the code that you
need to copy in the fileUpload2.php file.

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// Directory where the uploaded file will be saved

$target_dir = "C:\Downloads";

// Path to the file to be uploaded

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$uploadOk = 1;
// Get file extension

$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 (limit to 5MB for example)

if ($_FILES["fileToUpload"]["size"] > 5000000) {

echo "Sorry, your file is too large.";

$uploadOk = 0;

// Allow certain file formats (e.g., only images)

$allowedTypes = ['jpg', 'png', 'jpeg', 'gif'];

if (!in_array($fileType, $allowedTypes)) {

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.";

// If everything is ok, try to upload file

} else {

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.";

?>

There are some things to note in the above upload code.

 The first thing we did was to check if the file had come from a valid source or not. We used
the if statement and cross-checked them with the upload button’s variables’ values.
 When the file is uploaded, the $_Files superglobal variable is populated with the following
information:
 tmp_name: Temporary path that holds the upload file
 name: Name of the file
 size: The size of the uploaded file in bytes
 type: Information about the mime type of the uploaded file
 error: In case of any error while uploading, this variable gets the appropriate error
message
 Through the inner if statement, we checked whether the file upload in PHP was successful
or not.
 We then use the multi-dimensional $_Files array that holds the information as discussed
above.
 We then figured out the file’s extension and matched it with the allowed types.
 After, we used the move_uploaded_file function t,is used to move the uploaded file into the
desired location.
.

You might also like