使用PHP处理标签<input type ='file'... />时出错

时间:2019-10-06 13:44:46

标签: php html

对于我的网站,我希望用户发送图片。我当前的php代码无法检查内容。

我试图直接在html代码中限制扩展名。

if (isset($_POST['postphoto'])) {
    if (isset($_FILES['picture']) AND !empty($_FILES['picture']['name'])) {
        $comentarysender = htmlspecialchars($_POST['commentarysenderpost']);
        $extensionsValides = array('jpg', 'jpeg', 'gif', 'png');
            $extensionUpload = strtolower(substr(strrchr($_FILES['picture']['name'], '.'), 1));
            $chemin = "picture/post/".$id.".".$extensionUpload;
            move_uploaded_file($_FILES['picture']['tmp_name'], $chemin);
    } else {
        $message = "Please enter a picture!";
    }
}

当我发送带有图像的表单时,它返回错误消息:

  

请输入图片!

1 个答案:

答案 0 :(得分:0)

您可以这样做:

    $uploadStatus = 1;
    $uploadedFile = '';
    if (!empty($_FILES["img1"]["name"]))
    {
        $fileName = basename($_FILES["img1"]["name"]);
        $filenamewithoutextension = strtolower(pathinfo($fileName, PATHINFO_FILENAME));
        $fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        $filename_to_store = $filenamewithoutextension. '_' .uniqid(). '.' .$fileType;

        $allowTypes = array(
            'jpg',
            'png',
            'jpeg'
        );
        if (in_array($fileType, $allowTypes))
        {
            if (move_uploaded_file($_FILES["img1"]["tmp_name"], $uploadDir.$filename_to_store))
            {
                $uploadedFile = $filename_to_store;
            }
            else
            {
                $uploadStatus = 0;
                $response['message'] = 'Sorry, there was an error uploading your file.';
            }
        }
        else
        {
            $uploadStatus = 0;
            $response['message'] = 'Sorry, only JPG, JPEG & PNG files are allowed.';
        }
    }
    if($uploadStatus==1)
    { //execute sth else if you wish, like printing success message }

PS:我想您的html代码是正确的,否则它将不起作用