Upload a file using PHP

Trusted SSL from just $3.44
Advertisements
PHP file handling read and write
File Handling using PHP

If you want to upload a file to a given folder, follow the solutions given below.

solution 1

Below is one way to upload files, there are many other ways.

<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {

    if ($target_file == "upload/") {
        $msg = "cannot be empty";
        $uploadOk = 0;
    } // Check if file already exists
    else if (file_exists($target_file)) {
        $msg = "Sorry, file already exists.";
        $uploadOk = 0;
    } // Check file size
    else if ($_FILES["fileToUpload"]["size"] > 5000000) {
        $msg = "Sorry, your file is too large.";
        $uploadOk = 0;
    } // Check if $uploadOk is set to 0 by an error
    else if ($uploadOk == 0) {
        $msg = "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)) {
            $msg = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
        }
    }
}

?>

solution 2

First, write your HTML code like this, and don’t forget to add enctype="multipart/form-data"

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

Then create a file name called upload.php

Trusted SSL from just $3.44
Advertisements
<?php
$path = "form/";
$target_file =  $path.basename($_FILES["fileToUpload"]["name"]);
$file=$_FILES['fileToUpload']['name'];    
$result = move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target_file.$file);
if ($result) {
    echo "file successfully uploaded";
}
else {
    echo "please select your file";
}
PHP file handling read and write
File Handling using PHP
close

Stay up-to-date about PHP!

We don’t spam!

Trusted SSL from just $3.44
Advertisements

en English
X
Scroll to Top