Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to cURL in PHP. I have a question regarding usage of curl options.

Consider two script files: test1.php and test2.php both present in root www. I'm using Ubuntu 12.04 LTS. The libcurl version for PHP is 7.22.0.

Contents of test1.php

<?php
    $ch = curl_init();
    $post_data = array(
        'firstname' => 'John',
        'lastname' => 'Doe'
    );
    curl_setopt($ch, CURLOPT_URL, 'localhost/test2.php');
    curl_setopt($ch, CURLOPT_POST, TRUE);   //is it optional?
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_exec($ch);
    curl_close($ch);
?>

Contents of test2.php

<?php 
    var_dump($_POST);
?>

When I execute test1.php via browser, I can see results posted. Now if I remove curl option containing CURLOPT_POST, the example still works. Even if I set CURLOPT_POST to false, post is performed and result is displayed. So, is that CURLOPT_POST not required at all? It looks option CURLOPT_POSTFIELDS takes care of sending data via POST without use of CURLOPT_POST option. When I print $_SERVER in test2.php, request method is always set to POST (with or without option CURLOPT_POST).

Could anyone please let me know the exact use of CURLOPT_POST option? Is it neccessary required for sending data via POST?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
454 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are correct. CURLOPT_POSTFIELDS implies CURLOPT_POST. You don't need to use CURLOPT_POST while using CURLOPT_POSTFIELDS. The request method will always be set to POST in this case.

Note that this is in your case as long as you want it to be a POST request.

If you don't want to be it a POST request but set CURLOPT_POSTFIELDS, please see this related Q&A:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...