2012-12-22 28 views
0

我想从iOS设备发送图像到php脚本。我没有在iOS端发生错误,所以我认为问题出在我的php脚本上。我是新手,所以请原谅我。下面是PHP脚本:通过来自iOS的http post请求在php中接收图像

<?php 
$uploaddir = './';  //Uploading to same directory as PHP file 
$file = basename($_FILES['userfile']['name']); 
$uploadFile = $file; 
$randomNumber = rand(0, 99999); 
$newName = $uploadDir . $randomNumber . $uploadFile; 


if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { 
    echo "Temp file uploaded. \r\n"; 
} else { 
    echo "Temp file not uploaded. \r\n"; 
} 

if ($_FILES['userfile']['size']> 300000) { 
    exit("Your file is too large."); 
} 

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newName)) { 
    $postsize = ini_get('post_max_size'); //Not necessary, I was using these 
    $canupload = ini_get('file_uploads'); //server variables to see what was 
    $tempdir = ini_get('upload_tmp_dir'); //going wrong. 
    $maxsize = ini_get('upload_max_filesize'); 
    echo "http://www.iroboticshowoff.com/dir/{$file}" . "\r\n" . $_FILES['userfile']['size'] . "\r\n" . $_FILES['userfile']['type'] ; 
} 
?> 

而如果有人知道很多有关iOS的,这里是我用来发送图像的代码:

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept. 
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; 
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]]; 
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]]; 

// the boundary string : a random string, that will not repeat in post data, to separate post data fields. 
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"]; 

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = [NSString stringWithString:@"file"]; 

// the server url to which the image (or the media) is uploaded. Use your server url here 
NSURL* requestURL = [NSURL URLWithString:@"http://myurl.com/upload.php"]; 


// create request 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; 
[request setHTTPShouldHandleCookies:NO]; 
[request setTimeoutInterval:30]; 
[request setHTTPMethod:@"POST"]; 

// set Content-Type in HTTP header 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; 
[request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 

// post body 
NSMutableData *body = [NSMutableData data]; 

// add params (all params are strings) 
for (NSString *param in _params) { 
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; 
} 

// add image data 
NSData *imageData = UIImageJPEGRepresentation(finalImage, 1.0); 
if (imageData) { 
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:imageData]; 
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
} 

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; 

// setting the body of the post to the reqeust 
[request setHTTPBody:body]; 

// set the content-length 
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

// set URL 
[request setURL:requestURL]; 

我发现两者的这对计算器,但我了解iOS工作正常,PHP应该将照片放在我的服务器的根目录下。

+0

适合PHP新手的好书:http://www.sitepoint.com/books/phpmysql5/ –

回答

1

$_FILES数组拥有很多有用的信息。您可以(也应该)使用var_dump()打印出内容。这是一个可以上传文件的脚本。也许你可以根据自己的需要调整设计。

<?php // RAY_upload_example.php 
error_reporting(E_ALL); 


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES 
// http://php.net/manual/en/features.file-upload.php 
// http://php.net/manual/en/features.file-upload.common-pitfalls.php 
// http://php.net/manual/en/function.move-uploaded-file.php 
// http://php.net/manual/en/reserved.variables.files.php 

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES 
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize 
// http://php.net/manual/en/ini.core.php#ini.post-max-size 
// http://php.net/manual/en/info.configuration.php#ini.max-input-time 


// PHP 5.1+ SEE http://php.net/manual/en/function.date-default-timezone-set.php 
date_default_timezone_set('America/Chicago'); 

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY (MUST ALREADY EXIST) 
$uploads = 'RAY_junk'; 

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB 
$max_file_size = '8000000'; 

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD 
$nf = 3; 

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT 
$file_exts = array 
('jpg' 
, 'gif' 
, 'png' 
, 'txt' 
, 'pdf' 
) 
; 

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5) 
$errors = array 
(0 => "Success!" 
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini" 
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" 
, 3 => "The uploaded file was only partially uploaded" 
, 4 => "No file was uploaded" 
, 5 => "UNDEFINED ERROR" 
, 6 => "Missing a temporary folder" 
, 7 => "Cannot write file to disk" 
) 
; 




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT 
if (empty($_POST)) 
{ 
    ?> 
    <h2>Upload <?php echo $nf; ?> file(s)</h2> 

    <!-- 
     SOME THINGS TO NOTE ABOUT THIS FORM... 
     ENCTYPE IN THE HTML <FORM> STATEMENT 
     MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD 
     INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY 
     ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL 
    --> 

    <form name="UploadForm" enctype="multipart/form-data" method="post"> 
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" /> 
    <p> 
    Find the file(s) you want to upload and click the "Upload" button below. 
    </p> 

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES 
    for ($n = 0; $n < $nf; $n++) 
    { 
     echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n"; 
    } 
    ?> 

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files. 
    <input type="submit" value="Upload" /> 
    </form> 
    <?php 
    die(); 
} 
// END OF THE FORM SCRIPT 



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT 
else 
{ 
    // THERE IS POST DATA - PROCESS IT 
    echo "<h2>Results: File Upload</h2>\n"; 

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH 
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n"; 

    // ITERATE OVER THE CONTENTS OF $_FILES 
    foreach ($_FILES as $my_uploaded_file) 
    { 
     // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED 
     $error_code = $my_uploaded_file["error"]; 
     if ($error_code == 4) continue; 

     // SYNTHESIZE THE NEW FILE NAME 
     $f_type = trim(strtolower(end (explode('.', basename($my_uploaded_file['name']))))); 
     $f_name = trim(strtolower(current(explode('.', basename($my_uploaded_file['name']))))); 
     $my_new_file 
     = getcwd() 
     . DIRECTORY_SEPARATOR 
     . $uploads 
     . DIRECTORY_SEPARATOR 
     . $f_name 
     . '.' 
     . $f_type 
     ; 
     $my_file 
     = $uploads 
     . DIRECTORY_SEPARATOR 
     . $f_name 
     . '.' 
     . $f_type; 

     // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS 
     if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed"); 

     // IF THERE ARE ERRORS 
     if ($error_code != 0) 
     { 
      $error_message = $errors[$error_code]; 
      die("Sorry, Upload Error Code: $error_code: $error_message"); 
     } 

     // GET THE FILE SIZE 
     $file_size = number_format($my_uploaded_file["size"]); 

     // IF THE FILE IS NEW (DOES NOT EXIST) 
     if (!file_exists($my_new_file)) 
     { 
      // IF THE MOVE FUNCTION WORKED CORRECTLY 
      if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file)) 
      { 
       $upload_success = 1; 
      } 
      // IF THE MOVE FUNCTION FAILED 
      else 
      { 
       $upload_success = -1; 
      } 
     } 

     // IF THE FILE ALREADY EXISTS 
     else 
     { 
      echo "<br/><b><i>$my_file</i></b> already exists.\n"; 

      // SHOULD WE OVERWRITE THE FILE? IF NOT 
      if (empty($_POST["overwrite"])) 
      { 
       $upload_success = 0; 
      } 
      // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP 
      else 
      { 
       $now = date('Y-m-d'); 
       $my_bak = $my_new_file . '.' . $now . '.bak'; 
       if (!copy($my_new_file, $my_bak)) 
       { 
        echo "<br/><strong>Attempted Backup Failed!</strong>\n"; 
       } 
       if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file)) 
       { 
        $upload_success = 2; 
       } 
       else 
       { 
        $upload_success = -1; 
       } 
      } 
     } 

     // REPORT OUR SUCCESS OR FAILURE 
     if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; } 
     if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; } 
     if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; } 
     if ($upload_success < 0) { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; } 
     if ($upload_success > 0) 
     { 
      echo "$file_size bytes uploaded.\n"; 
      if (!chmod ($my_new_file, 0755)) 
      { 
       echo "<br/>chmod(0755) FAILED: fileperms() = "; 
       echo substr(sprintf('%o', fileperms($my_new_file)), -4); 
      } 
      echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n"; 
     } 
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE 
    } 
}