【问题标题】:Send cURL request from URL?从 URL 发送 cURL 请求?
【发布时间】:2011-05-26 03:13:30
【问题描述】:

您好,

我正在寻找一种在给定完整 url 的情况下发送 curl 请求的方法。我能找到的所有示例和文档都如下所示:

$fullFilePath = 'C:\temp\test.jpg';
$upload_url = 'http://www.example.com/uploadtarget.php';
$params = array(
    'photo'=>"@$fullFilePath",
    'title'=>$title
);      

$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);

问题在于文件“test.jpg”实际上是由服务器上的脚本动态生成的(因此它在文件系统上不存在)。

如何发送请求,而不是使用 $file = "http://www.mysite.com/generate/new_image.jpg"

想到的一个解决方案是使用 fopen 或 file_get_contents() 将“new_image.jpg”加载到内存中,但是一旦我到了这一点,我就不确定如何将其作为 POST 发送到另一个站点

【问题讨论】:

    标签: php curl dynamic-image-generation


    【解决方案1】:

    到目前为止,最简单的解决方案是将文件写入临时位置,然后在 cURL 请求完成后将其删除:

    // assume $img contains the image file
    $filepath = 'C:\temp\tmp_image_' . rand() . '.jpg'
    file_put_contents($filepath, $img);
    $params = array(
        'photo'=>"@$filepath",
        'title'=>$title
    );    
    // do cURL request using $params...
    
    unlink($filepath);
    

    请注意,我插入了一个随机数以避免竞争条件。如果您的图片不是特别大,最好在文件名中使用md5($img) 而不是rand(),这可能仍然会导致冲突。

    【讨论】:

    • 此方法有效,我希望避免保存副本,但这似乎是我唯一的选择。感谢您的帮助-
    • @pws5068 有可能,但基本上需要手动构建帖子。你可能不想这样做。
    猜你喜欢
    • 2022-01-06
    • 2020-04-05
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多