How to switch from POST to GET in PHP CURL

前端 未结 4 1677
-上瘾入骨i
-上瘾入骨i 2020-11-28 22:23

I have tried switching from a previous Post request to a Get request. Which assumes its a Get but eventually does a post.

I tried the following in PHP :



        
4条回答
  •  忘掉有多难
    2020-11-28 23:00

    Make sure that you're putting your query string at the end of your URL when doing a GET request.

    $qry_str = "?x=10&y=20";
    $ch = curl_init();
    
    // Set query data here with the URL
    curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    $content = trim(curl_exec($ch));
    curl_close($ch);
    print $content;
    
    With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
    of passing it in the CURLOPT__URL.
    -------------------------------------------------------------------------
    
    $qry_str = "x=10&y=20";
    curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    
    // Set request method to POST
    curl_setopt($ch, CURLOPT_POST, 1);
    
    // Set query data here with CURLOPT_POSTFIELDS
    curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);
    
    $content = trim(curl_exec($ch));
    curl_close($ch);
    print $content;
    
    

    Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

    [Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
    Since GET is the default, this is only necessary if the request method has been changed.

提交回复
热议问题