PHP File upload example script

PHP File upload example script

In this tutorial, you will learn about PHP File upload. Below all the PHP file upload example list.

What you’ll learn in this tutorial –

  • Simple File Upload
  • Check file already exists(uploaded) or not
  • Rename the File If the File Already Exists
  • Set PHP upload size limit
  • Upload the only specified file type. Such as only images
  • Upload image and store image name in Database

All the PHP File upload example

DEMO

1 – Simple File Upload

In simple file upload section, you can simply upload a file on your server.

<?php
if(isset($_FILES["target_file"])){
    // var_dump($_FILES["target_file"]);
    $upload_dir = 'uploads/';
    $target_file = $upload_dir.$_FILES["target_file"]["name"];

    if(move_uploaded_file($_FILES["target_file"]["tmp_name"], $target_file)){
        $message = "The file has been uploaded";
    }
    else{
        $message = "File not uploaded.";
    }

}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP File Upload</title>
    <style>
       *{box-sizing:border-box}body{font-family:sans-serif}h1{text-align:center}h1 small{font-size:16px}h1 small span{color:#999;font-weight:400;font-size:14px}.container{max-width:400px;border:1px solid #ddd;margin:0 auto;padding:10px}input[type=file]{width:100%;border:1px solid #ddd;cursor:pointer;margin-bottom:5px;padding:10px}input[type=submit]{padding:10px;background-color:#005670;color:#fff;text-transform:uppercase;border:1px solid rgba(0,0,0,.1);cursor:pointer}input[type=submit]:hover{border:1px solid #005670;color:#222;background:#fff}.messageBox{margin-top:5px; text-align:center; font-weight:bold;border:1px solid rgba(0,0,0,.1);background:#f7f7f7; padding:10px;}
    </style>
</head>
<body>
    <div class="container">
    <h1>PHP File Upload<br><small>By, <span>Webtutorials.ME</span></small></h1>
        <form action="" method="POST" enctype="multipart/form-data">
            <strong>Choose a file</strong><br>
            <input type="file" name="target_file" required><br>
            <input type="submit" value="Upload">
        </form>
        <?php
            if(isset($message)){
                echo '<div class="messageBox">'.$message.'</div>';
            }
        ?>
    </div>
</body>
</html>

2 – Check file already exists(uploaded) or not

But in Simple File Upload, when you upload a file like example.png and then upload another file with the same name.

Then you can see, the new file replaced the old file.

In this section before uploading a file, we first check the file name already exists on our upload folder or not.

If not exists then upload the new file otherwise not.

<?php
if(isset($_FILES["target_file"])){
    // var_dump($_FILES["target_file"]);
    $upload_dir = 'uploads/';
    $target_file = $upload_dir.$_FILES["target_file"]["name"];
    // CHECK IF FILE EXIST OR NOT
    if(file_exists($target_file)){
        $message = "File Already Exists";
    }
    else{
        
        if(move_uploaded_file($_FILES["target_file"]["tmp_name"], $target_file)){
            $message = "The file has been uploaded";
        }
        else{
            $message = "File not uploaded.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP File Upload</title>
    <style>
       *{box-sizing:border-box}body{font-family:sans-serif}h1{text-align:center}h1 small{font-size:16px}h1 small span{color:#999;font-weight:400;font-size:14px}h4{margin:0;padding:0;text-align:center;color:#f85a40;}.container{max-width:400px;border:1px solid #ddd;margin:0 auto;padding:10px}input[type=file]{width:100%;border:1px solid #ddd;cursor:pointer;margin-bottom:5px;padding:10px}input[type=submit]{padding:10px;background-color:#005670;color:#fff;text-transform:uppercase;border:1px solid rgba(0,0,0,.1);cursor:pointer}input[type=submit]:hover{border:1px solid #005670;color:#222;background:#fff}.messageBox{margin-top:5px; text-align:center; font-weight:bold;border:1px solid rgba(0,0,0,.1);background:#f7f7f7; padding:10px;}
    </style>
</head>
<body>
    <div class="container">
    <h1>PHP File Upload<br><small>By, <span>Webtutorials.ME</span></small></h1>
    <h4>If File Already Exists</h4>
        <form action="" method="POST" enctype="multipart/form-data">
            <strong>Choose a file</strong><br>
            <input type="file" name="target_file" required><br>
            <input type="submit" value="Upload">
        </form>
        <?php
            if(isset($message)){
                echo '<div class="messageBox">'.$message.'</div>';
            }
        ?>
    </div>
</body>
</html>

3 – Rename the File If the File Already Exists

In the previous section, you learn how to check file already exists or not.

Now in this section, we add a feature, that is Rename the File If the File Already Exists.

And yes this feature automatically changes the file name if the file already exists.

For example, you upload a file like example.jpg, and again you upload this or another file with the same name.

Now into the uploads folder, you will see two files – example.jpg and example-1.jpg

If you upload again with the same name, then you will see – example.jpg,example-1.jpg, and example-2.jpg. And it will keep repeating.

<?php
if(isset($_FILES["target_file"])){
    
    // var_dump($_FILES["target_file"]);
    $upload_dir = 'uploads/';
    $target_file = $upload_dir.$_FILES["target_file"]["name"];

    $path_info = pathinfo($_FILES["target_file"]["name"]);
    // var_dump($path_info);

    $number = 1;

    while(file_exists($target_file)){
        // CHANGE FILE NAME
        $target_file = $upload_dir.$path_info['filename'].'-'.$number.'.'.$path_info['extension'];
        $number++;
    }

    if(move_uploaded_file($_FILES["target_file"]["tmp_name"], $target_file)){
        $message = "The file has been uploaded";
    }
    else{
        $message = "File not uploaded.";
    }

}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP File Upload</title>
    <style>
       *{box-sizing:border-box}body{font-family:sans-serif}h1{text-align:center}h1 small{font-size:16px}h1 small span{color:#999;font-weight:400;font-size:14px}h4{margin:0;padding:0;text-align:center;color:#f85a40;}.container{max-width:400px;border:1px solid #ddd;margin:0 auto;padding:10px}input[type=file]{width:100%;border:1px solid #ddd;cursor:pointer;margin-bottom:5px;padding:10px}input[type=submit]{padding:10px;background-color:#005670;color:#fff;text-transform:uppercase;border:1px solid rgba(0,0,0,.1);cursor:pointer}input[type=submit]:hover{border:1px solid #005670;color:#222;background:#fff}.messageBox{margin-top:5px; text-align:center; font-weight:bold;border:1px solid rgba(0,0,0,.1);background:#f7f7f7; padding:10px;}
    </style>
</head>
<body>
    <div class="container">
    <h1>PHP File Upload<br><small>By, <span>Webtutorials.ME</span></small></h1>
    <h4>Rename the File If the File Already Exists</h4>
        <form action="" method="POST" enctype="multipart/form-data">
            <strong>Choose a file</strong><br>
            <input type="file" name="target_file" required><br>
            <input type="submit" value="Upload">
        </form>
        <?php
        if(isset($message)){
            echo '<div class="messageBox">'.$message.'</div>';
        }
        ?>
    </div>
</body>
</html>

4 – Set PHP upload size limit

In the set PHP upload size limit section, we will specify the upload size, so that users can upload only limited size files.

In here we set only below 1MB files are allowed to upload.

<?php
if(isset($_FILES["target_file"])){

    // var_dump($_FILES["target_file"]);
    $upload_dir = 'uploads/';
    $target_file = $upload_dir.$_FILES["target_file"]["name"];

    $path_info = pathinfo($_FILES["target_file"]["name"]);
    // var_dump($path_info);

    $number = 1;

    // 1048576 = 1MB
    // Only below 1MB files are allowed to upload
    if($_FILES["target_file"]["size"] > 1048576){
        $message = "File is too large. Please choose another.";
    }
    elseif($_FILES["target_file"]["error"] === 1){
        $message = "File is too large. Please choose another.";
    }
    else{

        while(file_exists($target_file)){
            $target_file = $upload_dir.$path_info['filename'].'-'.$number.'.'.$path_info['extension'];
            $number++;
        }

        if(move_uploaded_file($_FILES["target_file"]["tmp_name"], $target_file)){
            $message = "The file has been uploaded";
        }
        else{
            $message = "File not uploaded.";
        }

    }

}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP File Upload</title>
    <style>
       *{box-sizing:border-box}body{font-family:sans-serif}h1{text-align:center}h1 small{font-size:16px}h1 small span{color:#999;font-weight:400;font-size:14px}h4{margin:0;padding:0;text-align:center;color:#f85a40;}.container{max-width:400px;border:1px solid #ddd;margin:0 auto;padding:10px}input[type=file]{width:100%;border:1px solid #ddd;cursor:pointer;margin-bottom:5px;padding:10px}input[type=submit]{padding:10px;background-color:#005670;color:#fff;text-transform:uppercase;border:1px solid rgba(0,0,0,.1);cursor:pointer}input[type=submit]:hover{border:1px solid #005670;color:#222;background:#fff}.messageBox{margin-top:5px; text-align:center; font-weight:bold;border:1px solid rgba(0,0,0,.1);background:#f7f7f7; padding:10px;}
    </style>
</head>
<body>
    <div class="container">
    <h1>PHP File Upload<br><small>By, <span>Webtutorials.ME</span></small></h1>
    <h4>Set file upload size (max 1MB)</h4>
        <form action="" method="POST" enctype="multipart/form-data">
            <strong>Choose a file</strong><br>
            <input type="file" name="target_file" required><br>
            <input type="submit" value="Upload">
        </form>
        <?php
            if(isset($message)){
                echo '<div class="messageBox">'.$message.'</div>';
            }
        ?>
    </div>
</body>
</html>

5 – Upload the only specified file type

Here we will specify the file type so that users can only upload this type of files.

Here we’ll be allowed to upload only images ['png','jpg','jpeg','gif']

<?php
if(isset($_FILES["target_file"])){

    // var_dump($_FILES["target_file"]);
    $upload_dir = 'uploads/';
    $target_file = $upload_dir.$_FILES["target_file"]["name"];

    $path_info = pathinfo($_FILES["target_file"]["name"]);
    // var_dump($path_info);

    $number = 1;

    $fileType = ['png','jpg','jpeg','gif'];
    // IF THE FILE EXTENSION IS NOT IN ARRAY
    if(!in_array($path_info['extension'],$fileType)){
        $message = "Invalid Image!";
    }
    else{
        //IF THE FILE EXTENSION HAS IN ARRAY
        if($_FILES["target_file"]["size"] > 1048576){
            $message = "File is too large";
        }
        elseif($_FILES["target_file"]["error"] === 1){
            $message = "File is too large";
        }
        else{

            while(file_exists($target_file)){
                $target_file = $upload_dir.$path_info['filename'].'-'.$number.'.'.$path_info['extension'];
                $number++;
            }

            if(move_uploaded_file($_FILES["target_file"]["tmp_name"], $target_file)){
                $message = "The file has been uploaded";
            }
            else{
                $message = "File not uploaded.";
            }

        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP File Upload</title>
    <style>
       *{box-sizing:border-box}body{font-family:sans-serif}h1{text-align:center}h1 small{font-size:16px}h1 small span{color:#999;font-weight:400;font-size:14px}h4{margin:0;padding:0;text-align:center;color:#f85a40;}.container{max-width:400px;border:1px solid #ddd;margin:0 auto;padding:10px}input[type=file]{width:100%;border:1px solid #ddd;cursor:pointer;margin-bottom:5px;padding:10px}input[type=submit]{padding:10px;background-color:#005670;color:#fff;text-transform:uppercase;border:1px solid rgba(0,0,0,.1);cursor:pointer}input[type=submit]:hover{border:1px solid #005670;color:#222;background:#fff}.messageBox{margin-top:5px; text-align:center; font-weight:bold;border:1px solid rgba(0,0,0,.1);background:#f7f7f7; padding:10px;}
    </style>
</head>
<body>
    <div class="container">
    <h1>PHP File Upload<br><small>By, <span>Webtutorials.ME</span></small></h1>
    <h4>Upload only Images (max-size 1MB)</h4>
        <form action="" method="POST" enctype="multipart/form-data">
            <strong>Choose a file</strong><br>
            <input type="file" name="target_file" required><br>
            <input type="submit" value="Upload">
        </form>
        <?php
            if(isset($message)){
                echo '<div class="messageBox">'.$message.'</div>';
            }
        ?>
    </div>
</body>
</html>

6 – Upload image and store image name in Database

Here, we will upload an image and save the name of the image into the database so that we can show that image on a browser.

Database structure

Database Name – upload_image
Table Name – images

For creating images table and the structure of the images table, use the below SQL code.

CREATE TABLE `images` (
  `image_id` int(11) NOT NULL,
  `image_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `images`
  ADD PRIMARY KEY (`image_id`);
ALTER TABLE `images`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;
<?php
// DATABASE CONNECTION
$db_conn = mysqli_connect("localhost","root","","upload_image");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
// FETCH ALL IMAGES FROM DATBASE
$all_images = mysqli_query($db_conn,"SELECT * FROM `images`");

if(isset($_FILES["target_file"])){

    // var_dump($_FILES["target_file"]);
    $upload_dir = 'uploads/';
    $target_file = $upload_dir.$_FILES["target_file"]["name"];

    $path_info = pathinfo($_FILES["target_file"]["name"]);
    // var_dump($path_info);
    // GET FILE NAME
    $file_name = $_FILES["target_file"]["name"];

    $number = 1;

    $fileType = ['png','jpg','jpeg','gif'];

    if(!in_array($path_info['extension'],$fileType)){
        $message = "Invalid Image!";
    }
    else{
        // 1048576 = 1MB
        if($_FILES["target_file"]["size"] > 1048576){
            $message = "File is too large";
        }
        elseif($_FILES["target_file"]["error"] === 1){
            $message = "File is too large";
        }
        else{

            while(file_exists($target_file)){
                // CHANGE FILE NAME IF THE ALREADY EXISTS
                $file_name = $path_info['filename'].'-'.$number.'.'.$path_info['extension'];
                $target_file = $upload_dir.$file_name;
                
                $number++;
            }
            // INSERT STATEMENT
            $image_name_insert_stmt = mysqli_prepare($db_conn, "INSERT INTO `images` (image_name) VALUES (?)");
            mysqli_stmt_bind_param($image_name_insert_stmt, "s", $file_name);

            // IF THE FILE HAS BEEN UPLOADED
            if(move_uploaded_file($_FILES["target_file"]["tmp_name"], $target_file)){
                // EXECUTE INSERT STATEMENT
                if(mysqli_stmt_execute($image_name_insert_stmt)){
                    header('Location: 6.php');
                }
                else{
                    $message = "Opps, ERROR";
                }
            }
            else{
                $message = "File not uploaded.";
            }            

        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP File Upload</title>
    <style>
       .container,input[type=file]{border:1px solid #ddd;padding:10px}h1,h3,h4{text-align:center}*{box-sizing:border-box}body{font-family:sans-serif}h1 small{font-size:16px}h1 small span{color:#999;font-weight:400;font-size:14px}h4{margin:0;padding:0;color:#f85a40}.container{max-width:400px;margin:0 auto}input[type=file]{width:100%;cursor:pointer;margin-bottom:5px}input[type=submit]{padding:10px;background-color:#005670;color:#fff;text-transform:uppercase;border:1px solid rgba(0,0,0,.1);cursor:pointer}input[type=submit]:hover{border:1px solid #005670;color:#222;background:#fff}hr{border-color:#fff;border-top:1px solid #ccc}.all_images:after,.all_images:before{content:"";display:table}.all_images:after{clear:both}.all_images{max-width:422px;margin:0 auto}.image-wrapper{width:200px;max-height:200px;overflow:hidden;border:1px solid rgba(0,0,0,.1);padding:3px;background-color:#f7f7f7;float:left;margin:5px}.image-wrapper img{width:100%;height:auto;display:block}.messageBox{margin-top:5px; text-align:center; font-weight:bold;border:1px solid rgba(0,0,0,.1);background:#f7f7f7; padding:10px;}
    </style>
</head>
<body>
    <div class="container">
    <h1>PHP File Upload<br><small>By, <span>Webtutorials.ME</span></small></h1>
    <h4>Upload image and store image name in Database</h4>
        <form action="" method="POST" enctype="multipart/form-data">
            <strong>Choose a file</strong><br>
            <input type="file" name="target_file" required><br>
            <input type="submit" value="Upload">
        </form>
        <?php
            if(isset($message)){
                echo '<div class="messageBox">'.$message.'</div>';
            }
        ?>
    </div>
<hr/>
<h3>All images</h3>
    <div class="all_images">
        <?php
        if(mysqli_num_rows($all_images) > 0){
            while($row = mysqli_fetch_assoc($all_images)){
                echo '<div class="image-wrapper">
                <img src="uploads/'.$row['image_name'].'" alt="image alt">
            </div>';
            }
        }
        else{
            echo '<p>No image found! | <strong>Please Insert an Image.</strong></p>';
        }
        ?>
    </div>
</body>
</html>

Completed.

Posts Navigation


Leave a Reply

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