简体   繁体   English

PHP - 将上传的图像保存到服务器

[英]PHP - Saving Uploaded Image to Server

I am trying to save an uploaded image from an iPhone to a server using PHP. 我试图使用PHP将上传的图像从iPhone保存到服务器。 I am using ASIHTTPRequest to handle the data request. 我正在使用ASIHTTPRequest来处理数据请求。 This is my iPhone code: 这是我的iPhone代码:

[request setPostValue:someString forKey:@"string1"];
[request setPostValue:anotherString forKey:@"string2"];
[request addData:[NSData dataWithData:UIImageJPEGRepresentation(anImage, 0.9)]
         withFileName:@"img.jpg" andContentType:@"image/jpeg" forKey:@"img"];

[request startSynchronous];

On the server side, I am using this PHP code currently to try saving the image to a folder on my server: 在服务器端,我目前正在使用此PHP代码尝试将映像保存到服务器上的文件夹中:

print_r($_FILES);

$folder = 'upload/';
$image_path = basename($_FILES['img']['name']);
echo $folder . $image_path . "\n";
if (move_uploaded_file($_FILES['img']['tmp_name'], $folder . $image_path)) {
    echo 'ok!';
} 
else {
    echo 'fail !';
}

The strings are uploaded just fine and when I print_r() i see the contents of the image array as I expect, but for some reason when trying to save the image, i am getting "fail !" 字符串上传得很好,当我print_r()我看到了我期望的图像数组的内容,但出于某种原因,当我试图保存图像时,我正在“失败!” printed to the console. 打印到控制台。 What is wrong here? 这有什么不对?

Thanks. 谢谢。

Try the following step before you move your image 移动图像之前,请尝试以下步骤

if(!is_dir($folder))
{
   echo "Folder does not exist" ;

   if(!mkdir($folder))
   {
      echo "Attempt to create folder failed" ;
   }
}
else if(!is_writable($folder))
{
   echo "Folder nto writeable" ;

   if(!chmod($folder, 0755))
   {
        echo "Attempt to make writeable failed" ;
   }
}
 else {

   if (move_uploaded_file($_FILES['img']['tmp_name'], $folder . $image_path)) {
      echo 'ok!';
   }
   else {
    echo 'fail !';
   }    
}

What do you get ??? 你得到了什么 ???

Please also remember to do security checks on the file being uploaded. 还要记得对正在上传的文件进行安全检查。 For example, check the file types against a whitelist (jpeg, png, gif, etc)- I'm sure you don't want someone being able to upload a script to your website? 例如,根据白名单(jpeg,png,gif等)检查文件类型 - 我确定您不希望有人能够将脚本上传到您的网站?

Also for the long term you would be better off manually creating the upload folder and setting the appropriate permissions as oppose to having the PHP script do it for you.. 另外从长远来看,最好手动创建上传文件夹并设置相应的权限,而不是让PHP脚本为你做这件事。

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

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