如何从curl请求提交远程文件作为表单数据

时间:2015-01-17 23:17:28

标签: php forms curl file-upload

我的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
            )

    )

所以我的问题是如何使脚本可以访问curl ed文件数据,该脚本通常处理来自上述帖子请求的数据?

1 个答案:

答案 0 :(得分:0)

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);