Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php curl: I need a simple post request and retrival of page example

Tags:

php

curl

I would like to know how to send a post request in curl and get the response page.

like image 700
ufk Avatar asked Mar 13 '10 22:03

ufk


People also ask

What is cURL in PHP with example?

cURL is a PHP extension that allows you to use the URL syntax to receive and submit data. cURL makes it simple to connect between various websites and domains. Obtaining a copy of a website's material. Submission of forms automatically, authentication and cookie use.

How does PHP handle cURL request?

php file with the following contents. $url = 'https://www.example.com' ; $curl = curl_init(); curl_setopt( $curl , CURLOPT_URL, $url );


2 Answers

What about something like this :

$ch = curl_init(); $curlConfig = array(     CURLOPT_URL            => "http://www.example.com/yourscript.php",     CURLOPT_POST           => true,     CURLOPT_RETURNTRANSFER => true,     CURLOPT_POSTFIELDS     => array(         'field1' => 'some date',         'field2' => 'some other data',     ) ); curl_setopt_array($ch, $curlConfig); $result = curl_exec($ch); curl_close($ch);  // result sent by the remote server is in $result 


For a list of options that can be used with curl, you can take a look at the page of curl_setopt.

Here, you'll have to use, at least :

  • CURLOPT_POST : as you want to send a POST request, and not a GET
  • CURLOPT_RETURNTRANSFER : depending on whether you want curl_exec to return the result of the request, or to just output it.
  • CURLOPT_POSTFIELDS : The data that will be posted -- can be written directly as a string, like a querystring, or using an array


And don't hesitate to read the curl section of the PHP manual ;-)

like image 90
Pascal MARTIN Avatar answered Sep 28 '22 09:09

Pascal MARTIN


$url = "http://www.example.com/"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true);  $data = array(     'username' => 'foo',     'password' => 'bar' );   curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); $contents = curl_exec($ch); curl_close($ch); 
like image 26
areeb Avatar answered Sep 28 '22 09:09

areeb