The most effective method to Upload File in PHP

Record transfer is a most utilized component in the web application. PHP gives a simple method to transfer record to the server. With PHP, you can upload record or pictures to the server by composing negligible code. In this instructional exercise, we’ll give a PHP content to transfer record to the index on the server. Utilizing our PHP record transfer script you can transfer a wide range of documents including pictures to the server in PHP.
Upload Form HTML
At first, an HTML form needs to be created that allow users to choose a file they want to upload.

1
2
3
4
5
6
7
8
9
Make sure <input> tag contains the following attributes.
method=”post”
enctype=”multipart/form-data”
Also, make sure <input> tag contains type="file" attribute.
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">
</form>

The above file upload form will be submitted to the upload.php file for uploading file to the server.
Upload File in PHP (upload.php)
PHP provides a function called move_uploaded_file() that moves an uploaded file to a new location. Using move_uploaded_file() function we can upload a file in PHP.
The following code is used to upload file in PHP. Specify the directory in $targetDir variable, where the uploaded file will be placed. Also, define the file types that you want to allow for uploading.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
$statusMsg = '';
//file upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])) {
    //allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf');
    if(in_array($fileType, $allowTypes)){
        //upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            $statusMsg = "The file ".$fileName. " has been uploaded.";
        }else{
            $statusMsg = "Sorry, there was an error uploading your file.";
        }
    }else{
        $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
    }
}else{
    $statusMsg = 'Please select a file to upload.';
}
//display status message
echo $statusMsg;
?>
READ  How to Export Data to CSV File using PHP and MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *