PHP curl方法可以在同一个请求中上传一个文件和一个带有前导@字符的字符串吗? [英] Can PHP curl methods upload a file and a string with a leading @ character in the same request?

查看:208
本文介绍了PHP curl方法可以在同一个请求中上传一个文件和一个带有前导@字符的字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PHP curl_ *方法来构建一个POST请求,该方法执行以下操作:

I'd like to construct a POST request using PHP curl_* methods that does the following:


  1. 上传文件请求必须以multipart / form-data提交)

  2. 发送一个文本字符串,其中字符串以@字符开头

例如,以下代码工作,因为在文本字符串中没有前导@字符:

For example, the following code works because there is no leading "@" character in the string of text:

<?php

$postfields = array(
    'upload_file' => '@file_to_upload.png',
    'upload_text' => 'text_to_upload'
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);

?>

但是,如果字符串以@字符开头导致curl寻找非文件名为text_to_upload(请注意,唯一的变化是在upload_text字段中添加一个前导@字符):

But, it breaks if the string starts with an "@" character which causes curl looks for a non-existent file named "text_to_upload" (Note that the only change is the addition of a leading "@" character in the upload_text field):

<?php

$postfields = array(
    'upload_file' => '@file_to_upload.png',
    'upload_text' => '@text_to_upload'
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);

?>

所以...可以在上传文件时发送带有前导@字符的文本同时在PHP中使用curl_ *方法?

So... is it possible to send text with a leading "@" character while uploading a file at the same time using the curl_* methods in PHP?

最终结果(如果可能)应该等同于此命令行使用curl:

The end result (if possible) should be the equivalent of this command line use of curl:

curl -F 'upload_=@file_to_upload.png' --form-string 'upload_text=@text_to_upload' 'http://example.com/upload-test'

谢谢!

推荐答案

在前面加上空字符\0的字符串

<?php
    $postfields = array(
        'upload_file' => '@file_to_upload.png',
        'upload_text' => sprintf("\0%s", '@text_to_upload')
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
    curl_exec($curl);
    curl_close($curl);
?>

这篇关于PHP curl方法可以在同一个请求中上传一个文件和一个带有前导@字符的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆