php

Create The Upload File PHP Script

Uploading files via a web interface is a common requirement in many web applications. PHP provides a straightforward way to handle file uploads securely. In this blog post, we will create a simple file upload script that allows users to upload files to your server.

1. Setting Up the Environment

Before we dive into coding, ensure you have a PHP environment set up. You can use tools like XAMPP, WAMP, or a live server to test the script.

2. Creating the HTML Form

First, we need to create an HTML form that will allow users to select and upload files. This form will include the necessary attributes to handle file uploads.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h2>Upload a File</h2>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Choose file to upload:</label>
        <input type="file" name="file" id="file" required>
        <br><br>
        <input type="submit" value="Upload">
    </form>
</body>
</html>

Explanation of the HTML Form

  • Form Attributes:
    • action: The script that will process the file upload (upload.php).
    • method: Set to post to send the data.
    • enctype: Set to multipart/form-data to allow file uploads.
  • Input Type: The <input type="file"> element enables users to browse and select files.

3. Creating the PHP File Upload Script

Now, create a file named upload.php to handle the file upload. This script will process the uploaded file and provide feedback to the user.

<?php
// Define the target directory for uploads
$target_dir = "uploads/";

// Create the uploads directory if it doesn't exist
if (!is_dir($target_dir)) {
    mkdir($target_dir, 0777, true);
}

// Get the file details
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if the file is an actual image or a fake image
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if ($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size (limit to 5MB)
if ($_FILES["file"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats (you can adjust this as needed)
$allowed_types = array("jpg", "jpeg", "png", "gif", "pdf");
if (!in_array($fileType, $allowed_types)) {
    echo "Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    // If everything is ok, try to upload the file
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file " . htmlspecialchars(basename($_FILES["file"]["name"])) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
<?php
// Define the target directory for uploads
$target_dir = "uploads/";

// Create the uploads directory if it doesn't exist
if (!is_dir($target_dir)) {
    mkdir($target_dir, 0777, true);
}

// Get the file details
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if the file is an actual image or a fake image
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if ($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size (limit to 5MB)
if ($_FILES["file"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats (you can adjust this as needed)
$allowed_types = array("jpg", "jpeg", "png", "gif", "pdf");
if (!in_array($fileType, $allowed_types)) {
    echo "Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    // If everything is ok, try to upload the file
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file " . htmlspecialchars(basename($_FILES["file"]["name"])) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Explanation of the PHP Script

  • Target Directory: The script defines a target directory (uploads/) where uploaded files will be stored. It creates the directory if it doesn’t already exist.
  • File Information: The script retrieves the file name and type from the $_FILES superglobal array.
  • File Validations:
    • Image Check: It checks if the file is an actual image using getimagesize(). You can modify this check based on your needs (for non-image files).
    • Existing File Check: It checks if a file with the same name already exists.
    • File Size Limit: It restricts uploads to a maximum of 5MB.
    • Allowed File Formats: The script specifies allowed file types (JPG, PNG, GIF, PDF). You can adjust this array as needed.
  • File Upload: If all checks pass, the script moves the uploaded file from the temporary location to the target directory using move_uploaded_file().

<?php

(1) if(isset($_FILES[‘image’])){ // This name (image) is use to input name line no 15.
(2) echo”<pre>”;

(3) print_r($_FILES);

(4) echo”<pre>”;

(5) echo dirname(__FILE__);

//4 arrays are provides name, size, tmp_name, type is mandatory.

$file_name = $_FILES[‘image’][‘name’];
$file_size = $_FILES[‘image’][‘size’];
$file_tmp = $_FILES[‘image’][‘tmp_name’];
$file_type = $_FILES[‘image’][‘type’];

(6) move_uploaded_file($file_tmp,dirname(__FILE__).”/uploads-images/”.$file_name);
}

?>

(8)<html>

(9)<head>

(10)<title>File upload </title>

(11)</head>

(12) <body>

(13) <form action =”” method =”post” enctype=”multipart/form-data”>

(14) Select image to upload:

(15) <input type =”file” name = “image” id =”image”>

(16) <input type = ” submit”/>

(17) </form>

(18) </body>

Related Articles

Leave a Reply

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

Back to top button