简体   繁体   中英

Image upload failing in PHP

So I'm trying to set up an image upload from a form via php on my localhost and after running the code and connecting to the database okay, I'm getting the error for the upload. Since all of the other parts of the form are working after a section by section check, I'll just add the html for the upload input and its relevant php script.

<input type="file" name="image" id="image-select" />

And the portion of the php that has to deal with the image upload and verification after upload:

$image = $_FILES ['image']['name'];
$type = @getimagesize ($_FILES ['image']['tmp_name']);

//Never assume image will upload okay
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    die("Upload failed with error code " . $_FILES['image']['error']);
}

//Where the file will be placed
$target_path = "uploads/";

// Add the original filename to target path
$path= $target_path . basename($image);

// Check if the image is invalid before continuing
 if($type === FALSE || !($type[2] === IMAGETYPE_TIFF || $type[2] === IMAGETYPE_JPEG || $type[2] === IMAGETYPE_PNG)) {
    echo '<script "text/javascript">alert("This is not a valid image file!")</script>';
    die("This is not a valid image file!");
 } else {
        move_uploaded_file($_FILES['image']['tmp_name'], $path);
 }

So error appears once the code hits the upload process. I was attempting to upload a small PNG file The relevant code I added is also in their respective orders when they appear in the script.

Just a wild stab in the dark here as you haven't provided your form tag but you have remembered the enctype attribute haven't you?

Sorry I don't have 50 reputation otherwise I would ask this as a comment.

<form enctype='multipart/form-data' action=''>
<input type="file" name="image" id="image-select" />
</form>

Also you should check if the file uploaded OK before calling getimagesize() (not that this would be the source of your issue)

如果您使用的是PHP5Imagick ,那么您可以尝试使用类似以下的内容:

$image->readImageFile($f);

can you please put error here. If error means that after submit page file is not being upload. then please check your form enctype. see below an example

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image-select" />
<input type="submit" value="Submit">
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM