簡體   English   中英

使用 curl 和 php 將字符串作為文件發送

[英]Send string as a file using curl and php

我知道我可以使用此語法使用 php、post 和 curl 發送文件。

$post = array(
    "file_box"=>"@/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 

如何獲取一個字符串,構建一個臨時文件並使用完全相同的語法發送它?

更新:我更喜歡使用 tmpfile() 或 php://memory 所以我不必處理文件創建。

您可以在臨時目錄中使用tempnam創建文件:

$string = 'random string';

//Save string into temp file
$file = tempnam(sys_get_temp_dir(), 'POST');
file_put_contents($file, $string);

//Post file
$post = array(
    "file_box"=>'@'.$file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

//do your cURL work here...

//Remove the file
unlink($file);

您可以使用file_put_contents創建一個臨時文件,只需確保目標目錄是可寫的。

$path = '/path/to/myfile.txt';    
file_put_contents($myData, $path);

$post = array(
    "file_box"=>"@".$path,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

# Delete the file if you don't need it anymore
unlink($path);

來自http://php.net/manual/en/class.curlfile.php#115161

function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {
    
             // invalid characters for "name" and "filename"
             static $disallow = array("\0", "\"", "\r", "\n");

             // build normal parameters
             foreach ($assoc as $k => $v) {
                 $k = str_replace($disallow, "_", $k);
                 $body[] = implode("\r\n", array(
                     "Content-Disposition: form-data; name=\"{$k}\"",
                     "",
                     filter_var($v),
                 ));
             }

             // build file parameters
             foreach ($files as $k => $v) {
                 switch (true) {
                     case false === $v = realpath(filter_var($v)):
                     case !is_file($v):
                     case !is_readable($v):
                         continue; // or return false, throw new InvalidArgumentException
                 }
                 $data = file_get_contents($v);
                 $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
                 $k = str_replace($disallow, "_", $k);
                 $v = str_replace($disallow, "_", $v);
                 $body[] = implode("\r\n", array(
                     "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
                     "Content-Type: image/jpeg",
                     "",
                     $data,
                 ));
             }

             // generate safe boundary
             do {
                 $boundary = "---------------------" . md5(mt_rand() . microtime());
             } while (preg_grep("/{$boundary}/", $body));

             // add boundary for each parameters
             array_walk($body, function (&$part) use ($boundary) {
                 $part = "--{$boundary}\r\n{$part}";
             });

             // add final boundary
             $body[] = "--{$boundary}--";
             $body[] = "";

             // set options
             return @curl_setopt_array($ch, array(
                 CURLOPT_POST       => true,
                 CURLOPT_POSTFIELDS => implode("\r\n", $body),
                 CURLOPT_HTTPHEADER => array(
                     "Expect: 100-continue",
                     "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
                 ),
             ));
         }

$array1=array('other_post_field'=>'value');
$array2=array('file'=>'document_content_string');
$ch = curl_init();       
curl_setopt($ch, CURLOPT_URL,$url);
curl_custom_postfields($ch,$array1,$array2);//above custom function
$output=curl_exec($ch);
close($ch);

由於 PHP 8.1 還有CURLStringFile允許您在沒有臨時文件的情況下發送它:

$txt = 'test content';
$file = new \CURLStringFile($txt, 'filename.txt', 'text/plain');

$ch = curl_init('https://example.com/upload');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => $file]);
curl_exec($ch);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM