Upload a file using PHP

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

As @nordenheim said, $HTTP_POST_FILES has been deprecated since PHP 4.1.0, thus not advisable to use so.

PHP Code (upload.php)

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

?>

HTML Code to start function

<form action="upload.php" method="post" id="myForm" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <button name="submit" class="btn btn-primary" type="submit" value="submit">Upload File</button>
 </form>

Hope this helps.


PHP 4.1 introduced the superglobals. They replace the old, long-named arrays that contain the data extracted from the request. $_FILES[] replaced$HTTP_POST_FILES[], $_GET[] replaced $HTTP_GET_VARS[] and so on

For subsequent PHP 4 versions the old and the new arrays were available side by side. PHP 5 by default disabled the generation of the old arrays and introduced the php.ini directive register_long_arrays that could be used to re-enable the creation of the old arrays.

Since PHP 5.4 the old long-named arrays were removed completely and register_long_arrays went together with them.

Conclusion: You are learning from a very old or very bad tutorial. Find a better one.