Search code examples
phpstringapachecurllamp

Attaching get fields to URL using Curl in PHP


I am able to perform server and client side redirects using Curl but I am unable to attach GET fields to the URL via a get request, here is my code:

$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);

Nothing gets attached when I perform the execution, what am I doing wrong?

New code I am using:

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

Solution

  • Try this:

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

    This works fine for me.