2014-03-03 92 views
0

我正在尝试创建一个cURL帖子,其中一个参数包含一个以'@'符号为前缀的字符串。通常对于cURL文章,'@'表示我正在尝试发布文件,但在这种情况下,我只想传递带有“@”前缀的字符串。有没有办法,或者解决这个问题的最好方法是什么?PHP cURL:绕过'@'表示文件POST

这里是我的参数数组:

$params = array(
     'UserID'  => $this->username, 
     'Password'  => $this->password, 
     'Type'   => $type, 
     'Symbol'  => $symbol, // this will look something like @CH14 
     'Market'  => '', 
     'Vendor'  => '', 
     'Format'  => 'JSN' 
); 

而以下是我的卷曲后正在发生(网址是无关的实际问题。):

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 

// Return the transfer as a string 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 

$response = curl_exec($ch); 

if($response === FALSE) 
{ 
    $error = curl_error($ch); 
    $error_code = curl_errno($ch); 
    throw new Exception("CURL ERROR: #$error_code\n$error\n"); 
} 

curl_close($ch); 

return $response; 

这适用于我需要的一切它除了当我需要在前面传递一个符号'@'时才做。任何帮助将不胜感激。谢谢。

回答

3

按照curl_setopt() manual entry

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile.

因此,我们可以简单地将其转换为使用http_build_query()字符串:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); 
+0

我给这个一杆,并在命令行运行我的剧本,我收到错误: 异常:卷曲错误:#26 失败创建表格数据 这恰好与我在不包括http_build_query()时得到的错误相同。我在PHP 5.2.4版本为这个特定的项目。有没有其他信息可以帮助我? – RedJesper

+0

@ user3375552'var_dump(http_build_query($ params))'输出了什么? (在你原来的问题中发布内容) – h2ooooooo

+0

啊,我很抱歉。我正在运行相同脚本的较旧版本。 http_build_query()运行得非常漂亮。它使用正确的字符串并输出正确的结果。非常感谢你。 – RedJesper

1

使用http_build_query()打造的查询字符串。

从该函数的文档:

Generates a URL-encoded query string from the associative (or indexed) array provided.

如上所述,它将正确根据需要编码所有的特殊字符。它可以如下使用:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); 

Online demo