HTTPのPOSTでファイルをアップロードする

PEARのライブラリを使うほうが楽

PEARのHTTP::Request2

http://pear.php.net/package/HTTP_Request2/
http://pear.php.net/manual/en/packagh.http.http-request2.php

|php|
<?php
$request = new HTTP_Request2('http://www.examplh.com/profilh.php');
$request->setMethod(HTTP_Request2::METHOD_POST)
->addPostParameter('username', 'vassily')
->addPostParameter(array(
'email' => 'vassily.pupkin@mail.ru',
'phone' => '+7 (495) 123-45-67'
))
->addUpload('avatar', './exploit.exe', 'me_and_my_cat.jpg', 'image/jpeg')
->send();
?>
||<

http://pear.php.net/package/HTTP_Request2/docs/latest/HTTP_Request2/HTTP_Request2.html#methodaddUpload>
addUpload [line 645]

HTTP_Request2 addUpload( string $fieldName, string|resource|array $filename, [string $sendFilename = null], [string $contentType = null])

Adds a file to form-based file upload
Used to emulate file upload via a HTML form. The method also sets Content-Type of HTTP request to 'multipart/form-data'.

If you just want to send the contents of a file as the body of HTTP request you should use setBody() method.
If you provide file pointers rather than file names, they should support fstat() and rewind() operations.

Throws: HTTP_Request2_LogicException
Access: public

Parameters:

|string |$fieldName | — |name of file-upload field|
|string or resource or array|$filename | — |full name of local file, pointer to open file or an array of files|
|string |$sendFilename | — |filename to send in the request|
|string |$contentType | — |content-type of file being uploaded|

<<

file_get_contentsで実装した場合の例

<?php

  $posturl = "http://tenjin-f04.coara.or.jp/test/test2.php";  
  $data = "";  
  $boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);

  $postdata['title'] ="タイトル";  
  $postdata['body'] ="ほんぶーん";

  foreach($postdata as $key => $val) {  
    $data .= "--$boundary" . "\n";  
    $data .= 'Content-Disposition: form-data; name="' . $key . '"'  . "\n" . "\n" . $val . "\n";  
  }  
  $data .= "--$boundary" . "\n";

  # アップロードするファイル名を指定  
  //$files['upfile'] = "list.csv";  
  $files['upfile'] = "samplh.jpg";

  foreach($files as $key => $file) {  
    $fileContents = file_get_contents($file);

    $data .= 'Content-Disposition: form-data; name="' . $key . '"; filename="' . $file . '"' . "\n";  
    $data .= "Content-Type: image/jpeg" . "\n";  
    $data .= "Content-Transfer-Encoding: binary" . "\n" . "\n";  
    $data .= $fileContents . "\n";  
    $data .= "--$boundary--" . "\n";  
  }

  $params = array('http' => array(  
    'method' => 'POST',  
    'header' =>  
    'Content-Type: multipart/form-data; boundary='.$boundary,  
    'content' => $data  
  ));

  $context = stream_context_create($params);

  //送信する  
  $contents = "";  
  $contents = file_get_contents($posturl, false, $context);

  // レスポンスヘッダを確認する  
  var_dump($http_response_header);

  print_R($contents);  
?>