PHP Knowledge Base

PHP to Upload a File Using HTML Form

php example #1
<?php

// Include the database configuration file 
include_once 'dbConfig.php'; 
 
$statusMsg = ''; 
 
// File upload directory 
$targetDir = "uploads/"; 
 
if(isset($_POST["submit"])){ 
    if(!empty($_FILES["file"]["name"])){ 
        $fileName = basename($_FILES["file"]["name"]); 
        $targetFilePath = $targetDir . $fileName; 
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); 
     
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            // Upload file to server 
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ 
                // Insert image file name into database 
                $insert = $db->query("INSERT INTO images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())"); 
                if($insert){ 
                    $statusMsg = "The file ".$fileName. " has been uploaded successfully."; 
                }else{ 
                    $statusMsg = "File upload failed, please try again."; 
                }  
            }else{ 
                $statusMsg = "Sorry, there was an error uploading your file."; 
            } 
        }else{ 
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $statusMsg = 'Please select a file to upload.'; 
    } 
} 
 
// Display status message 
echo $statusMsg; 

?>
php example #2
<?php
if (isset($_POST['submit'])) {
    // 1. Check if the file upload encountered any errors
    if ($_FILES['my_file']['error'] === UPLOAD_ERR_OK) {
        
        // 2. Extract information
        $fileName = $_FILES['my_file']['name'];
        $fileTmpPath = $_FILES['my_file']['tmp_name'];
        $fileSize = $_FILES['my_file']['size'];
        
        // 3. Define your target upload path
        $uploadFolder = 'uploads/';
        $targetPath = $uploadFolder . basename($fileName);
        
        // 4. Move the file out of the temporary folder
        if (move_uploaded_file($fileTmpPath, $targetPath)) {
            echo "File uploaded successfully!";
        } else {
            echo "Error moving the file to the target directory.";
        }
        
    } else {
        echo "Upload error code: " . $_FILES['my_file']['error'];
    }
}
?>
html for example #2
<form action="upload.php" method="POST" enctype="multipart/form-data">
    <label for="fileUpload">Choose file:</label>
    <input type="file" name="my_file" id="fileUpload">
    <button type="submit" name="submit">Upload</button>
</form>