Jump to content

how do I set curl POST method with PHP?


Go to solution Solved by kicken,

Recommended Posts

Hi, I'm trying to post some data to an API with curl. I always get '1' as response but the endpoint is not being called as my network console doesn't show anything. This is an example of my curl setup code:

   

 function api($url,$data) { 
            //API REST
            
            $fields_string = http_build_query($data);
    
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://proyectodata/api/$url.php");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
            $resp = curl_exec($ch);
            curl_close($ch);
            
            //var_dump($resp).'<br/>';
            print_r($resp);
        }

The `$data` variable contains an array like this one but larger:

     Array ( [0] => Array ( [id] => 6403 [participacion] => 13614 [beneficio] => cine [fecha] => 2018-04-16 12:27:44 [promo] => 33 ) [1] => Array ( [id] => 6404 [participacion] => 13612 [beneficio] => spor [fecha] => 2018-04-16 12:28:11 [promo] => 33 )

And when parsed with `http_build_query()` it converts to this type of data:

    0%5Bid%5D=6653&0%5Bparticipacion%5D=6936&0%5Bbeneficio%5D=cine&0%5Bfecha%5D=2018-04-16+14%3A41%3A59&0%5Bpromo%5D=33&1%5Bid%5D=6654&1%5Bparticipacion%5D=3318&1%5Bbeneficio%5D=payp&1%5Bfecha%5D=2018-04-16+14%

I am getting no errors here but the enpoint is never called as seen in the network console nor the data is being posted. I am printing the post response in the navigator (it shows multiple responses as I am calling the function multiple times)

api_response.png

Link to comment
https://forums.phpfreaks.com/topic/315515-how-do-i-set-curl-post-method-with-php/
Share on other sites

The browser's network console only shows the requests made by the browser.   It will not show requests made by PHP / CURL as it has no idea they even happen since that all happens on the server before the browser gets any of the page's response data.

If you want to get extra debugging info about the request, you can enable CURLOPT_VERBOSE in your code.  CURL will output a bunch of extra info to the browser as it does the request.

 

Hi @kickenwould you mind giving me an example on how to  enable CURLOPT_VERBOSE. I've been trying this way but i get no response:

function api($url,$data) {
        //API REST
        $fields_string = http_build_query($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://lumia.mx/proyectodata/api/$url.php");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        $resp = curl_exec($ch);
        curl_close($ch);    
        //var_dump($resp).'<br/>';

        echo "<p>server response: $resp</p>";

    }

 

If just setting it to true doesn't provide any extra output, then try this:

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $fp = fopen('php://temporary', 'w+'));
curl_exec($ch);

rewind($fp);
fpassthru($fp);

 

Edited by kicken

Great, now I am getting this data from CURLOPT_VERBOSE but it seems there are no errors at the request:

* Trying 2606:4700:3031::6815:4ce7:80... * Connected to lumia.mx (2606:4700:3031::6815:4ce7) port 80 (#0) > POST /proyectodata/api/bulk.php HTTP/1.1 Host: lumia.mx Accept: */* Content-Length: 5947 Content-Type: application/x-www-form-urlencoded * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Thu, 10 Nov 2022 16:25:43 GMT < Content-Type: text/html; charset=UTF-8 < Transfer-Encoding: chunked < Connection: keep-alive < Expires: Thu, 19 Nov 1981 08:52:00 GMT < Cache-Control: no-store, no-cache, must-revalidate < Pragma: no-cache < Set-Cookie: PHPSESSID=ecf9ae840373293c61f7fb0aedd10b12; path=/ < Vary: User-Agent < CF-Cache-Status: DYNAMIC < Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=xWuIst400vHvKPQspvSApJk2f8Lm59TPKyqUdBm0dypSjst3yguydjV7pXMSJndNjMFr84v3EknKr03s77KsYEs%2FknIsdDGltEoVm%2BphykA2qOSPrN1LW%2BGRuEpMSjJWY1hi%2FXuyqQ%3D%3D"}],"group":"cf-nel","max_age":604800} < NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800} < Server: cloudflare < CF-RAY: 76802549bbeaba71-EZE < alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400 < * Connection #0 to host lumia.mx left intact 

Actually yes.. I will try to explain it the best I can.

I made this script becouse I am trying to migrate the registers of the table 'beneficios' to that API through the POST method, and I am doing it by loads of 500 registers per time (you can see an example of the data that I pass to the API REST at the top of this thread) as there are a lot of registers and I don't want to get TimeOut error at navigator.

My client gave me access to his database so I could check if the data is being effectively loaded BUT when i run the script and check the database no data is being loaded and I am getting no errors at the script or at the POST method.

Here is my full script file"index.php" (I commented the code so it is easier to read):

<?php
    include 'config.php';

    function api($url,$data) {
        //API REST
        $fields_string = http_build_query($data);    

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://lumia.mx/proyectodata/api/$url.php");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $resp = curl_exec($ch);
        curl_close($ch);

        echo "<p>server response: $resp</p>";
    }

    //id of the promo
    $promo = 33;
    //number of registers to transfer per load
    $cant = 50; 
 
    //to restart process
    if (isset($_GET['inicio'])) {
        $_SESSION['indexp'] = 0;
        api('clean',array('promo'=>$promo));
    }
   
    if (isset($_SESSION['indexp'])) {
        for ($i=0;$i<10;$i++) {    
            $ini = intval($_SESSION['indexp']);
      
            //registers to process during this load
            $registers = $sql->query("SELECT * FROM beneficios LIMIT $ini,$cant");
            $_SESSION['indexp'] = $ini+$cant;

            //printing migration info
            echo "<p>ini: $ini / users: $registers->num_rows</p>";
      
            $todos = array();
            while ($user = $registers->fetch_object()) {

                //set of general data
                $data = array('id' => $user->id, 'participacion' => $user->participacion, 'beneficio' => $user->beneficio,'fecha' => $user->fecha, 'promo' => $promo);
                echo $sql->error;

                //added to an array for the data load
                array_push($todos,$data);
            }
            //call to API
            api('bulk',$todos);
        }
    ?>
    <script>
        //script for automatic reload
        setTimeout(function() {
            window.location.reload();
        },10000);
</script>
<?php
} else {
   echo 'session out';
}

And this is my config.php file:

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "golalazo_sites_golalazo";

    // Create connection
    global $sql;
    $sql = new mysqli($servername, $username, $password, $dbname);
    session_start();

    // Check connection
    if ($sql->connect_error) {
       die("Connection failed: " . $sql->connect_error);
    }else {
        echo "<p>Welcome to PHP</p>";
    }
?>

I will also attach an image of the database my client gave me (it is the one with id = 33). The column 'usuarios' should show the number of registers uploaded and there is only 1 at the moment (I really don't know why).

Really sorry for the long post but I wanted you to see the big picture of what I am trying to do here.
 

db_client.png

  • Solution

Probably you should talk to the company hosting the API as it seems your request is going through fine so if there's a problem it's likely with the data you are sending not being what they expect.  They are the only ones that can really tell you for sure if there is a problem with the data.

 

If I had to take a guess, it would be that you seem to be trying to post multiple records when they probably only expect one.  If you decide you're query string, you'll see you are posting data like this:

0[id]=6653&0[participacion]=6936&0[beneficio]=cine&0[fecha]=2018-04-16+14:41:59&0[promo]=33&1[id]=6654&1[participacion]=3318&1[beneficio]=payp

That seems unusual to me.  What would seem more likely is that you'd send one at a time with data such as this:

id=6653&participacion=6936&beneficio=cine&fecha=2018-04-16+14:41:59&promo=33

 

  • Thanks 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.