用php问题上传文件

时间:2018-08-15 18:43:22

标签: php html image file upload

我正在尝试在我们的网页上使用文件上传元素,以便客户可以向我们上传图片。 我从代码笔下载了一个漂亮的图片上传元素

然后我从w3学校获得了PHP代码(完整的代码在底部):

https://www.w3schools.com/php/php_file_upload.asp

浏览器在使用“ getimagesize”进行第一次检查时返回错误。它说:

警告:getimagesize():在第10行的W:\ xampp \ htdocs \ image-upload-preview \ upload.php中文件名不能为空 文件不是图像。很抱歉,您的文件尚未上传。

<form action="upload.php" method="post" enctype="multipart/form-data">
  <h1>Image-upload with preview</h1>
<div class="wrapper">
  <div class="box">
    <div class="js--image-preview"></div>
    <div class="upload-options">
      <label>
        <input type="file" class="image-upload" accept="image/*" name="fileToUpload" />
      </label>
    </div>
  </div>


if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;
}

}

2 个答案:

答案 0 :(得分:0)

您得到的警告是没有破坏您的代码。修复警告检查,如果您正在调用的文件设置为

$checkfile = isset($_FILES['fileToUpload']['tmp_name']) ? $_FILES['fileToUpload']['tmp_name'] : '';

然后

$check = getimagesize($checkfile);

您遇到的问题是文件为空,因此它正在运行else语句并使$ uploadOk =0。尝试找出图像的去向,并确保将其放置在$ _FILES ['fileToUpload' ]数组。

答案 1 :(得分:0)

感谢您的答复。我从头开始有了一个更好的教程here 我还不得不应对php,ini中的文件大小限制(然后忘记重新启动apache),但最终我使它工作了。这是我的php代码:

<?php

if (isset($_POST['submit'])){
//the name 'file' is from the HTML
//$_FILES is a super global
$file = $_FILES['file'];

//creating variables for the file attributes
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];

//creates an array for the name and extension
$fileExt = explode('.', $fileName);

//creates variable for the lower case extension, from the end of the array
$fileActualExt = strtolower(end($fileExt));

//allowed extensions
$allowed = array('jpg','jpeg','png','tif');

//checks
if(in_array($fileActualExt,$allowed)){ 
        if($fileError === 0){
            if($fileSize < 25000000){
                //creates a new file name
                $fileNameNew = uniqid('',true).".".$fileActualExt;
                //set file destination
                $fileDestination = 'uploads/'.$fileNameNew;
                //moves from temp to proper destination
                move_uploaded_file($fileTmpName,$fileDestination);
                //goes back to previous page upon sucess
                header("Location: index.html?uploadsucsess");
            }else{
                echo "File must be less than 25 mb";
            }
        } else{
            echo "There was an error uploading your file";
            echo $fileError;
        }
    } else{
        echo "Invalid File Type Must be a JPG, PNG, or TIF";
    }

}