Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

php - CURLOPT_POST vs. CURLOPT_POSTFIELDS: Is CURLOPT_POST option required?

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

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

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...