简体   繁体   English

PHP文件上传问题

[英]PHP File Upload Issues

I'm looking for some help with PHP File Upload. 我正在寻找有关PHP File Upload的帮助。 I'm trying to upload an image, using the following code (provided in the w3schools tutorial): 我正在尝试使用以下代码(在w3schools教程中提供)上传图片:

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
 else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

if (file_exists("upload/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "upload/" . $_FILES["file"]["name"]);
  echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  }
}
        }
          else
            {
           echo "Invalid file";
  }

Obviously I have some changes to make to their code, but it doesn't do what it says it's supposed to do as it is. 显然,我需要对他们的代码进行一些更改,但是它并没有像它原本应该做的那样工作。 So I'm asking: 所以我问:

  1. Why does this not make a new folder called 'upload' as it claims it will? 为什么这不会像它声称的那样建立一个名为“上载”的新文件夹? I get the following error: Warning: move_uploaded_file(upload/donkeykong.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in ... etc. 我收到以下错误: Warning: move_uploaded_file(upload/donkeykong.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in ... etc.

  2. How should I write the URL where I want the image uploaded? 如何在要上传图像的位置写URL?

It doesn't create a folder because mkdir() is never called. 它不会创建文件夹,因为从不调用mkdir() The code assumes the upload/ directory already exists. 该代码假定上upload/目录已经存在。 Create the directory if it doesn't exist with: 创建目录(如果不存在):

if (!file_exists('upload')) {
  mkdir('./upload');
}

As an aside, the statement at the beginning can be cleaned up in a number of ways. 顺便说一句,开头的语句可以通过多种方式进行清理。 One possibilty is to use in_array() rather than a bunch of || 一种可能是使用in_array()而不是一串|| conditions: 条件:

if (in_array($_FILES['file']['type'], array("image/gif", "image/jpeg", "image/pjpeg")
  && ($_FILES["file"]["size"] < 20000)
)

To place the uploads in upload/ relative to the server document root, you can use $_SERVER['DOCUMENT_ROOT'] . 要将上载放在相对于服务器文档根目录的upload/ ,可以使用$_SERVER['DOCUMENT_ROOT'] However, you should create the upload/ directory manually and make it writable by the web server. 但是,您应该手动创建upload/目录,并使其可被Web服务器写入。 In order to create the directory through PHP, the whole document root would need to be writable by the web server, which is a massive security flaw. 为了通过PHP创建目录,整个文档根目录都需要Web服务器可写,这是一个巨大的安全漏洞。

$uploads_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
move_uploaded_file($_FILES["file"]["tmp_name"], $uploads_dir . $_FILES["file"]["name"]);

I built this awial ago, works for JPEG , JPG , GIF , PNG 我以前很难构建,可用于JPEGJPGGIFPNG

Saves to current directory "images". 保存到当前目录“图像”。

<?
max_size = 300; //size in kbs

if($_POST['Submit'] == "Upload"){$image =$_FILES["file"]["name"];$uploadedfile = $_FILES['file']['tmp_name'];
    if ($image){$filename = stripslashes($_FILES['file']['name']);$extension = getExtension($filename); $extension = strtolower($extension);    
        if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {$change='Invalid Picture';$errors=1;}
        else{$size=filesize($_FILES['file']['tmp_name']);
            if ($size > $max_size*1024){$change='File too big!';$errors=1;}
            else{
                if($extension=="jpg" || $extension=="jpeg" ){$uploadedfile = $_FILES['file']['tmp_name'];$src = imagecreatefromjpeg($uploadedfile);}
                else if($extension=="png"){$uploadedfile = $_FILES['file']['tmp_name'];$src = imagecreatefrompng($uploadedfile);}
                else {$src = imagecreatefromgif($uploadedfile);}
                echo $scr;
                list($width,$height)=getimagesize($uploadedfile);

                //MAIN IMAGE
                $newwidth=300;
                $newheight=($height/$width)*$newwidth;
                $tmp=imagecreatetruecolor($newwidth,$newheight);
                $kek=imagecolorallocate($tmp, 255, 255, 255);
                imagefill($tmp,0,0,$kek);
                imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

                //Does Directory Exhist?
                if(is_dir("images")==FALSE){mkdir("images");}

                //Build file path and SAVE
                $filepath = "images/".md5(genRandomString().$_FILES['file']['name']).".".$extension;
                imagejpeg($tmp,$filepath,100);
                imagejpeg($tmp,$filepath,100);
                imagedestroy($src);
                imagedestroy($tmp);

                //ERROR HANDLING
                if($_FILES["file"]["size"]<=0){$errors=1;$change='No file';}
                if($errors!=1){$change='Image Uploaded!';}
            }
        }
    }
}
?>

For your errors: 对于您的错误:

<div><? echo $change ?></div>

1.Usually means the file path is incorrect or the permissions are not set correctly. 1.通常表示文件路径错误或权限设置不正确。 You should create the upload directory and set it so that the appropriate people can read and write from it manually. 您应该创建并设置上传目录,以便适当的人可以手动对其进行读写。 In apache I think it is something like this: 在Apache中,我认为是这样的:

mkdir uploaded_files
chown -R nobody uploaded_files
chmod 755 -R uploaded_files

2.In regards to the path, you can use absolute or relative- best to do just use: 2.关于路径,您可以使用绝对或相对最佳来使用:

$_SERVER['DOCUMENT_ROOT] . '/uploaded_files'

Hope this helps 希望这可以帮助

<?php
if (isset($_FILES['photo']))
{
    $mimetype = mime_content_type($_FILES['photo']['tmp_name']);
    if(in_array($mimetype, array('image/jpeg', 'image/gif', 'image/png'))) {

    move_uploaded_file($_FILES['photo']['tmp_name'],
 '/images/' . $_FILES['photo']['name']);
   echo 'OK';
     } else {
             echo 'Not an image file!';
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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