使用php上传文件时遇到错误

时间:2018-05-26 13:12:18

标签: php file-upload

错误是我使用文件名"文件"在html中。同样使用"文件"在php文件中访问该文件,但它确实无法正常工作。 在这里的家伙,我在PHP面临一个问题相关的上传文件我认为我的代码是正确的但文件没有上传到服务器请帮助我。

Html代码

<form id="login-form"  action="welcome.php" class="form" method="post" witdth= "80px;" enctype="multipart/form-data"> 
<input type="file" class="" name="file" id="file" style="background: gray;">
            <br>
            <br>
            <div class="form-group">
                <button type="submit" id="register-btn" onClick="register();return false;"
                        class="btn btn-primary btn-block">Submit &nbsp; </button>

            </div>
        </form>

这里的PHP代码

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES['file']["name"]);
$uploadOk = 1;
$File = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image

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

?>

2 个答案:

答案 0 :(得分:0)

if (isset($_POST["submit"])) {
    if ($_FILES["file"]["name"] != "") {

//if there was an error uploading the file
        if ($_FILES["file"]["error"] > 0) {

            $msg = "Error while uploading file-Return Code: " . $_FILES["file"]["error"] . "<br />";
            $uploadedStatus = 0;
        } else {


            if (file_exists($_FILES["file"]["name"])) {
                unlink($_FILES["file"]["name"]);
            }

            $allowed_filetypes = array('.jpg', '.JPG', '.jpeg', '.JPEG');

            $filename = $_FILES['file']['name']; // Get the name of the file (including file extension).
            $ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1); // Get the extension from the filename.

            if (!in_array($ext, $allowed_filetypes)) {
                $msg = "invalid file type";
                $uploadedStatus = 0;
            } else {
                $file_name = uniqid() . $ext;
                $storagename = "../assests/images/upload_images/" . $file_name;
                move_uploaded_file($_FILES["file"]["tmp_name"], $storagename);
                $uploadedStatus = 1;
            }
        }
    } else {
        $uploadedStatus = 1;
        $file_name = "";
    }

if ($uploadedStatus == 1) {

//your code
}
else{
$msg = "Error while uploading file-Return Code: " . $_FILES["file"]["error"] . "<br />";
}

}

答案 1 :(得分:0)

您刚刚定义了文件名,但尚未将上传的文件移至您的服务器。

//$target_file = $target_dir . basename($_FILES['file']["name"]);
$uploadOk = 1;
$File = strtolower(pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION));
if(in_array($File, ['png', 'jpg', 'jpeg', 'gif'])){
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_dir . basename($_FILES['file']['name']))){
//echo 'File uploaded !';
//all post manipulations here
}else{
echo 'Upload failed';
}
}else{
echo 'File is not image type';
}
相关问题