PHP Image Resize&我的上传脚本 [英] PHP Image Resize & My upload script

查看:108
本文介绍了PHP Image Resize&我的上传脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多例子,但我不确定它如何与我目前拥有的上传脚本相关联。有人可以解释我如何能够使用ImageMagick或其他类似的东西将上传的图像调整到固定宽度,同时保持w:h比率?

I have seen a lot of examples, but I am not sure how it can tie into the upload script i currently have. Could someone please explain how I might be able to use ImageMagick or something of the like to resize an uploaded image to a fixed width while keeping the w:h ratio?

我用Google搜索并查看了超过150个网页,但它们都没有真正给出一个我觉得适用于我的情况的例子。任何帮助,将不胜感激。这是我的代码:

I have googled and looked at over 150 web pages but none of them really give an example that i feel applies to my situation. Any help would be appreciated. Here is my code:

// Include Extension finder function.
include_once 'find_extension.php';

    // Function Gathers the Input Name, Store Number and Picture Number. The picture number is assigned by the loop that will be cycling through the images to be uploaded. The store Number and the Picure Number will make the file name.
    function uploadImage($inputname, $storenum, $picturenum){

// A few parameters, to restrict file types and file size to 20kb.
if ((($_FILES[$inputname]["type"] == "image/gif")
|| ($_FILES[$inputname]["type"] == "image/png") 
|| ($_FILES[$inputname]["type"] == "image/jpeg") 
|| ($_FILES[$inputname]["type"] == "image/pjpeg"))
&& ($_FILES[$inputname]["size"] < 200000))
  {
      // If there is an error, echo the error, if not continue.
    if ($_FILES[$inputname]["error"] > 0){
        echo "Error: " . $_FILES[$inputname]["error"] . "<br />";
    }else{
      // Echo out File information.
 /* echo "Upload: " . $_FILES[$inputname]["name"] . "<br />";
  echo "Type: " . $_FILES[$inputname]["type"] . "<br />";
  echo "Size: " . ($_FILES[$inputname]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES[$inputname]["tmp_name"]; */
    }

    // Get the extension so we can rename using the previous function.
    $ext = findexts($_FILES[$inputname]["name"]);

    $newpicturename = $storenum . $picturenum . "." . $ext;
    // Check to see if the file exists, if it does then tell the user. If not continue.
    if (file_exists("userimages/" . $newpicturename)){

      echo "<br>" . $newpicturename . " already exists. ";

      }else{

    // Uploads the file.
      move_uploaded_file($_FILES[$inputname]["tmp_name"], "userimages/" . $newpicturename);

    $picturefield = "picture" . $picturenum;
    $picturepath = "userimages/" . $newpicturename;
    //Inserts data into ad DB
    mysql_query("UPDATE storead SET $picturefield='$picturepath' WHERE storenum='$storenum'");
    // Tells the User.
     // echo "Stored in: " . "userimages/" . $newpicturename;
      }

  }else{
      // If the upload does not meet the parameters above, then tell the user and cancel.
      echo "Error uploading " . $_FILES[$inputname]["name"] . ". File may be too large or of unnacepted format.";
  }

}

谢谢:)

推荐答案

您可以将文件加载到图像处理库中,调整大小并保存,而不是move_uploaded_file()。

Instead of move_uploaded_file(), you'd load the file into the image processing library, resize it, and save it out.

例如。使用GD,从imagecreatefromgif(),imagecreatefromjpeg()或imagecreatefrompng()(取决于你得到的格式)开始,然后使用imagecreatetruecolor()创建所需缩略图大小的新图像,并使用imagecopyresampled将原始图像调整大小()。最后使用imagegif()/ imagejpeg()/ imagepng()保存结果,具体取决于您想要的格式。

eg. using GD, start with imagecreatefromgif(), imagecreatefromjpeg() or imagecreatefrompng() (depending on what format you've got), then create a new image of the desired thumbnail size using imagecreatetruecolor() and resize the original image into it using imagecopyresampled(). Finally save the results using imagegif()/imagejpeg()/imagepng() depending on what format you want.

如果您只是想要一个,那么确定目标大小非常简单固定宽度,同时保持纵横比:new_height = round_to_whole_pixels(new_width * original_height / original_width)。然而,值得进行一些健全性检查:比如有人上传1x2000像素图像。瞄准(例如)200像素的宽度,然后将它吹到200x400000,这是一个巨大的图像,可能会占用你服务器的所有内存!所以也有一个max_height。

Determining the target size is pretty easy if you just want a fixed width whilst retaining the aspect ratio: new_height= round_to_whole_pixels(new_width*original_height/original_width). However it is worth putting some sanity checks in: say someone uploads a 1x2000 pixel image. Aiming for a width of (say) 200 pixels, you'd then be blowing it up to 200x400000, an enormous image that might eat all your server's memory! So have a max_height as well.

最后,你的脚本包含太多严重的安全漏洞要列出。在将这类内容放在公共互联网上之前,您需要了解目录遍历攻击,SQL注入,HTML注入(XSS)和文件上载类型嗅探漏洞(例如,将JavaScript嵌入到伪装成图像文件的HTML中)。

Finally, your script as it stands contains too many severe security holes to list. Before you put anything like that on the public internet you need to learn about directory traversal attacks, SQL injection, HTML injection (XSS) and file upload type sniffing vulnerabilities (eg. embedding JavaScript in HTML disguised as an image file).

ETA:


您认为此网站涵盖了大多数基地吗?

Do you think this web site covers most bases?

不完全,但这是一个开始。这个建议:

Not quite, but it's a start. This advice:


当您将任何上传的文件放入上传文件夹时,将文件重命名为一些随机名称并跟踪数据库中的文件名。

When you place any uploaded files in your upload folder, rename the file to some random names and track the filename in the database.

非常重要。您永远不会信任用户提交的文件名。文件名比你想象的要复杂得多,即使它们不是恶意的,文件名也会出现许多奇怪的错误:

is very important. You can never trust a filename submitted by the user. Filenames are more complicated than you think, and even if they're not trying to be malicious, there are many weird ways filenames can go wrong:


  • 一些浏览器提交文件叶子名,一些整个路径,你不知道客户端机器上的文件路径格式(各种平台上的目录分隔符包括'/','\',':',' 。'和其他人)。

  • some browsers submit file leafnames, some whole paths, and you don't know the format of filepaths on the client machine (directory separators on various platforms include ‘/’, ‘\’, ‘:’, ‘.’ and probably others).

如果给定的文件名包含不允许的字符,会发生什么?控制字符? Unicode字符?

what's going to happen if the given filenames contain disallowed characters? Control characters? Unicode characters?

如果您使用的是Windows服务器,请尝试创建具有看似无害但保留名称的文件,例如'com',您将会来一个收割机。 Windows也会以一种容易混淆你的脚本的方式静静地抛弃尾随空格和点。

if you're on a Windows server, try to create files with innocuous-looking but reserved names like ‘com’ and you'll come a cropper. Also Windows silently throws away trailing spaces and dots in a way that can easily confuse your scripts.

后者是一个您链接的脚本中的潜在安全漏洞。它检查文件名末尾的'。'文件扩展名,如'.php'。但是如果你将一个名为x.php的文件(带有空格)上传到Windows服务器,它会很乐意接受它并将其保存为x.php。 (脚本中也有一个错误,因为它在正则表达式中使用'。',代表任何字符。因此文件名'poo.potatophp'将被视为具有.php扩展名。)

The latter is a potential security hole in the script you linked. It checks for ‘bad’ file extensions like ‘.php’ at the end of the filename. But if you uploaded a file called ‘x.php ’ (with a space) to a Windows server it would happily accept it and save it as ‘x.php’. (There is also a bug in the script, as it uses ‘.’ in a regular expression, which stands for any character. So the filename ‘poo.potatophp’ would be taken as having a .php extension.)

像往常一样,白名单优于黑名单。仅允许例如。 '.jpeg'扩展更有可能比禁止已知的扩展更有效。但是,这仍然不够,因为无法保证提交的JPEG文件实际上具有扩展名.jpeg。在Windows上,它可能有一个扩展名'.jpg'或'.pjpeg'或其他完全恰好在客户端计算机上映射到JPEG的东西。在Mac或Linux上,它可能根本没有文件扩展名!

As usual, whitelisting is better than blacklisting. Allowing only eg. ‘.jpeg’ extensions is more likely to work than disallowing known-bad ones. However, this is still insufficient, because there is no guarantee a submitted JPEG file will actually have the extension ‘.jpeg’. On Windows it might have an extension ‘.jpg’ or ‘.pjpeg’ or something else completely that happens to be mapped to JPEG on the client machine. On Mac or Linux it might have no filename extension at all!

总结一下:最好忽略用文件上传字段提交的任何文件名/路径。如果你还不知道,也许你可以看一下它来猜测文件的格式,但你不能依赖它,你永远不应该用它的用户的话来实际保存它名称。

So to sum up: it is best to ignore any filename/path submitted with file upload fields. Maybe you can have a look at it to guess what format the file might be in if you don't already know, but you can't rely on that and you should never ever take the user's word for it and actually save it under that name.

该页面也未涵盖我提到的伪装成图像文件的HTML案例。如果您允许任何人上传您不完全信任的文件并完全访问您网站上的所有内容,则需要担心这一点。你可以在这里阅读它。有关PHP文件上载脚本风险的更多讨论,请此处

The page also does not cover the ‘HTML disguised as an image file’ case I mentioned. If you allow anyone to upload files that you don't completely trust with full access to everything on your site, you need to worry about this. You can read about it here. See more discussion of PHP file upload script risks here.

ETA2:


我看到很多关于在网络上传的建议目录。然而,我的脚本仍会将这些文件显示给网站的访问者。

I have seen a lot of suggestions of uploading above the web directory. Yet my script will still display these files to the visitors of the web site.

是的,这是一个好的开始。通过控制服务流程,您可以避免Web服务器以意外方式处理文件类型的任何问题,您可以使用自己的已知安全文件名,并通过让脚本添加Content-Disposition:attachment标头,您可以主要阻止浏览器将JavaScript等活动内容视为源自您网站的安全上下文,从而导致跨站点脚本问题。

Yeah, that's a good place to start. By taking control of the serving process into your own hands you avoid any problems with the webserver handling filetypes in unexpected ways, you can use your own known-safe filenames, and by having your script add a "Content-Disposition: attachment" header, you can mostly prevent browsers from treating active content like JavaScript as originating from your site's security context, causing cross-site scripting problems.

此方法的缺点是服务于通过PHP的文件比让Web服务器更快地。您可以通过在文件服务脚本中实现大量HTTP缓存标头内容来改善问题,但这是一项很多工作,它仍然不会像用C编写的典型Web服务器那样快,也许使用内核级网络效率黑客。对于偶尔提供的文件,这没问题。对于在繁忙的网站上一直查看的流行图像,它一点也不好。

The drawback of this method is that serving a file through PHP is much, much slower than letting the web server do it. You can improve matters by implementing a load of HTTP cacheing header stuff in your file serving script, but it's a lot of work and it still won't be anywhere near as fast as a typical webserver written in C and maybe using kernel-level network efficiency hacks. For a file you serve up occasionally, that's no problem. For a popular image being viewed all the time on a busy site, it's no good at all.

此外,曾经有一些问题,Flash会忽略内容 - 处置标头,仍然可以通过该插件导致偷偷摸摸的文件到XSS。这些现在已经修复,但谁知道其他插件和奇怪的浏览器行为可能会在那里。因此,为了安全起见,最好从不同的主机名提供不受信任的用户上传文件,例如。像data.example.com这样的子域名。这会阻止cookie和身份验证详细信息泄漏到两个安全上下文中。如果你采用基于网络服务器的方式来吐出文件,你肯定需要采取这种预防措施。

Also, there used to be some issues where Flash would ignore the Content-Disposition header, which could still cause sneaky files to XSS via that plugin. These are fixed now, but who knows what other plugins and odd browser behaviours might be out there. So for safety, it may be best to serve your untrusted user-uploaded files from a different hostname, eg. a subdomain like data.example.com. This stops cookies and authentication details leaking across the two security contexts. If you go for a webserver-based way of spitting out files, you definitely need to take this precaution.


我只是想得到这个完成,它太复杂了

I just want to get this done, its way too complicated

是的,它看起来像一个看似简单的任务,但实际上并非如此。由于不受信任的上传,一些非常引人注目的网站遭遇安全问题;如果微软和谷歌的网络人员不能总是把它弄好,它可能 非常复杂......

Yeah, it looks like a deceptively simple task, but it's really not. Some very high-profile web sites have suffered with security problems due to untrusted uploads; if Microsoft and Google's web guys can't always get it right, it probably is quite complicated...

这没有帮助(像往常一样对于PHP)99%的教程都是完全废话。

It doesn't help that (as usual for PHP) 99% of the tutorials out there covering this sort of thing are utter crap.

这篇关于PHP Image Resize&amp;我的上传脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆