PHP File Upload | How to upload a file in PHP | E-CODEC

How to upload a file in PHP

 

PHP File Upload

To upload a file in PHP, you need to follow these step

First, ensure that PHP is configured to allow file uploads
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On

1. Create an HTML form with an input field of type "file" to allow users to select the file they want to upload. For example: 

1
2
3
4
<form action="<?=$_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
        <input type="file" name="upload" required>
        <input type="submit" name="submit">
    </form>

Some rules to follow for the HTML form above:

 
Make sure that the form uses method="post"
The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form

2. In the form, set the action attribute to the PHP file that will handle the file upload. In this example, the file is named "index.php".

3. In the PHP file ("index.php" in this case), you can process the uploaded file using the $_FILES super global variable. This variable contains information about the uploaded file. Here's an example of how you can handle the file upload:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
if(isset($_POST['submit'])){

    $file = $_FILES['upload'];

    $file_name = $file['name'];
    $tmp_name = $file['tmp_name'];

    $path = $_SERVER['DOCUMENT_ROOT'].'/youtube/upload-document/upload/';

    if(move_uploaded_file($tmp_name, $path.$file_name)){
        $res = mysqli_query($conn, "INSERT INTO photos(document) VALUES('$file_name')");
        if($res){
            echo "Document save and upload successfully.";
        }else{
            echo "Document upload but not data save.";
        }
    }else{
        echo "Document failed to upload";
    }
}


4. In the PHP code, the move_uploaded_file function is used to move the uploaded file from the temporary directory to the desired location. The function takes two parameters: the temporary file location ($_FILES["upload"]["tmp_name"]) and the target file location ($path).

5. You should also add some security measures, such as checking the file size, file type, and implementing file validation and sanitation to prevent malicious uploads.

I hope you enjoyed this video tutorial. If you had any doubts, then please comment them below. And if you enjoyed this tutorial, then please hit the like button below and subscribe my channel. Thank you.

How to fetch files from database in PHP using MySQL database

 

Post a Comment

0 Comments