PHP form uploading multiple image files

2019-09-14 11:55发布

I'm trying to create a site where the user has to upload at least a profile picture, and 4 additional yet optional pictures. I'm struggling to wrap my head around the logic required, so can someone please point me in a general direction. Here's the form:

<form id=userform action="updatepictures.php" method=post enctype="multipart/form-data">
                <div id="slogan">Upload A Profile Picture*</div>
                <center><input type=file name=profilepicture></center>
                <div id="slogan">Upload Up To Four Additional Pictures</div>
                <center><input type=file name=pic1></center>
                <br>
                <center><input type=file name=pic2></center>
                <br>
                <center><input type=file name=pic3></center>
                <br>
                <center><input type=file name=pic4></center>
                <center><input style="margin-top: 20px;" type="submit" value="Update" class="butt" name="upload"></center>
            </form>

And Here's the PHP script for it:

<?php

include ('connect.php');

session_start();

$target_dir = "gallery/";
$target_file = $target_dir . basename($_FILES["profilepicture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_file = $target_dir . bin2hex(openssl_random_pseudo_bytes(16)) . "." . $imageFileType;

if (isset($_POST["upload"]))
{
    $check = getimagesize($_FILES["profilepicture"]["tmp_name"]);
    if($check == false)
    {
        header("refresh:0;url=profile.php?error=filetype");
        return ;
    }
}

if ($_FILES["profilepicture"]["size"] > 1000000)
{
    header("refresh:0;url=profile.php?error=size");
    return ;
}

if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" )
{
    header("refresh:0;url=profile.php?error=unsupported");
    return ;
}
if (move_uploaded_file($_FILES["profilepicture"]["tmp_name"], $target_file))
{
    //Push Images To Database
    $conn = Connect();
    $pfp = $conn->prepare("INSERT INTO `images` (`id`, `user`, `profile`, `pic1`, `pic2`, `pic3`, `pic4`) VALUES (NULL, :email, :pfp, '', '', '', '')");
    $pfp->bindParam(':email', $_SESSION['email']);
    $pfp->bindParam(':pfp', $target_file);
    $pfp->execute();
    $confirmed = $conn->prepare("UPDATE `users` SET `confirmed` = '1' WHERE `users`.`email` = :email");
    $confirmed->bindParam(':email', $_SESSION['email']);
    $confirmed->execute();
    header("refresh:0;url=home.php");
}
else
{
    header("refresh:0;url=profile.php?error=unknown");
}


?>

Right now, the script uploads the profile picture, but how do I get it to check for the other files and upload them too, even though they're optional?

1条回答
我想做一个坏孩纸
2楼-- · 2019-09-14 12:24

Thanks to Hasibur Rahaman for the solution. I changed it into a function and called it when $_FILES['image name'] is not empty.

查看更多
登录 后发表回答