【问题标题】:Attaching get fields to URL using Curl in PHP在 PHP 中使用 Curl 将获取字段附加到 URL
【发布时间】:2015-11-28 06:55:17
【问题描述】:

我能够使用 Curl 执行服务器和客户端重定向,但我无法通过 get 请求将 GET 字段附加到 URL,这是我的代码:

$post = curl_init();
curl_setopt($post,CURLOPT_URL,$url);
curl_setopt($post,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($post, CURLOPT_USERAGENT,'Codular');
curl_setopt($post, CURLOPT_CUSTOMREQUEST,'GET');
curl_exec($post);
curl_close($post);

执行执行时没有附加任何内容,我做错了什么?

我正在使用的新代码:

function curl_req($url, $req, $data='')
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
    if (is_array($data)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
$temp = array("akash"=>"test");
$result = curl_req("http://localhost/test.php", 'POST', $temp);
echo $result;
print_r($result);

test.php:

print_r($_POST);
print_r($_REQUEST);

【问题讨论】:

  • 您不能将 GET 参数附加到 URL 中吗? yoururl.com?param=yourgetparam
  • 是的,没有任何东西附加到 URL
  • 也许你可以在这里使用我的答案:stackoverflow.com/questions/13420952/php-curl-delete-request我已经发送了很多带有该功能的 GET 请求。如果您不想在 json 中发送它,我认为您可以轻松删除 json 编码部分并将您的 GET 数据作为关联数组发送。
  • 我刚刚尝试过,但仍然没有任何内容添加到字符串中。感谢您的回答
  • 你能告诉我你用来构建你的 URL 的代码吗?

标签: php string apache curl lamp


【解决方案1】:

试试这个:

// Fill in your DATA  below. 
$data = array('param' => "datata", 'param2' => "HelloWorld");

/*
* cURL request
* 
* @param    $url      string    The url to post to 'theurlyouneedtosendto.com/m/admin'/something'
* @param    $req      string    Request type. Ex. 'POST', 'GET' or 'PUT'
* @param    $data     array     Array of data to be POSTed
* @return   $result             HTTP resonse 
*/
function curl_req($url, $req, $data='')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
        if (is_array($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


// Fill in your URL  below. 

$result = curl_req("http://yourURL.com/?", "POST", $data)
echo $result;

这对我来说很好。

【讨论】:

  • 您应该使用 http_build_query() 并将其传递给数组,而不是手动执行 GET 查询
  • 不,我得到了这个:你必须通过 CURLOPT_HTTPHEADER 传递一个对象或一个数组
  • @JoelS 我更新了我的答案。现在对你有用吗?
  • 仍然没有附加到 URL
  • 那是httpd配置问题... :P
猜你喜欢
  • 2019-02-27
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
相关资源
最近更新 更多