使用PHP中的Curl将get字段附加到URL

时间:2015-09-02 16:44:48

标签: php string apache curl lamp

我可以使用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);

1 个答案:

答案 0 :(得分:2)

试试这个:

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

这对我来说很好。