我的PHP应用程序设置为用户可以通过表单保存/上传文件。我正在尝试编写一个 shell 脚本(由 cron 作业运行),该脚本重用相同的模型方法,但用于未通过表单提交的文件。我目前正在使用 curl 来获取文件,但我对其他解决方案持开放态度。
以下是我目前获取文件的方式:
$ch = curl_init($image_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$photo_data = curl_exec($ch);
curl_close($ch);
这似乎返回了 base64 编码的数据...
Hâ6#Ý^¦Ó¾ÊiAM¸¤¨q±´°jîÍrÓÄ¥!dqh/J°ØÉ(þ}ZKóܧóµßÅÑ .JÍWE-uXؤu!¢
±IãJT 浯utÞfåã6MGâYØUL:ÑÆZS÷'5Óç;ªåÓÒâbmlLKsô«ÄT
±üåûü_ĦSSM"ºlDAº¦Ë]Xcç[)X©¬oÞÃîIöÁB]aR+%+å@_·]³
...
这是我的应用程序期望的帖子数据的格式:
[Photo] => Array
(
[file] => Array
(
[name] => desert2.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/php65uUCk
[error] => 0
[size] => 96573
)
)
所以我的问题是,如何使通常处理上述 post 请求数据的脚本可以访问 curl
ed 文件数据?
http://php.net/manual/en/function.fsockopen.php
<?php
// cURL
$ch = curl_init($image_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$photo_data = curl_exec($ch);
curl_close($ch);
// Create Image Array
$imageData = array(
"name"=>"IMAGE NAME",
"type"=>"image/jpeg",
"tmp_name"=>"TEMP NAME",
"error"=>0,
"size"=>str_len($photo_data),
"photo"=>$imageData // Add this line as there is nothing in the data structure given that will pass the image data
);
// URL
$url = parse_url("http://www.wherethisisgoing.com/page.php");
$host = $url["host"];
$path = $url["path"];
$httpData = http_build_query($imageData); // Converts array to URL Parameters
$socket = fopensock($host, 80, $errno, $error, 30); // 80 is the port and 30 is the timeout length
if($socket) {
fputs($socket, "POST " . $path . " HTTP/1.1'r'n");
fputs($socket, "Host: " . $host . "'r'n");
fputs($socket, "Referrer: PUT SENDING URL HERE'r'n");
fputs($socket, "Content-type: application/x-www-form-urlencoded'r'n");
fputs($socket, "Content-length " . strlen($imageData) . "'r'n");
fputs($socket, "Connection: close'r'n'r'n");
fputs($socket, $imageData);
while(feof($socket)) {
// Get Results
$result .= fgets($socket, 128); // 128 should be enough to receive the response from the script
}
} else {
return array(
"status"=>"error",
"error"=>$error . " (" . $errno . ")"
);
}
//Do some type of checking to verify the image was uploaded
fclose($socket);