PHP Curl: I Need a Simple Post Request and Retrival of Page Example

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

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 ;-)

PHP cURL GET request and request's body

CURLOPT_POSTFIELDS as the name suggests, is for the body (payload) of a POST request. For GET requests, the payload is part of the URL in the form of a query string.

In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.

curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);

//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Post data and retrieve the response using PHP Curl?

You'll have to set the CURLOPT_RETURNTRANSFER option to true.

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

curl_close($ch);

The response to your request will be available in the $result variable.

PHP, cURL, and HTTP POST example?

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");

// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));

// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);

// Further processing ...
if ($server_output == "OK") { ... } else { ... }
?>

How to get response using cURL in PHP

Just use the below piece of code to get the response from restful web service url, I use social mention url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);

$ch = curl_init($url);
curl_setopt_array($ch, $options);

$content = curl_exec($ch);

curl_close($ch);

return $content;
}

Getting content body from http post using php CURL

CURLOPT_VERBOSE should actually show the details. If you're looking for the response body content, you can also use CURLOPT_RETURNTRANSFER, curl_exec() will then return the response body.

If you need to inspect the request body, CURLOPT_VERBOSE should give that to you but I'm not totally sure.

In any case, a good network sniffer should give you all the details transparently.

Example:

$curlOptions = array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_VERBOSE => TRUE,
CURLOPT_STDERR => $verbose = fopen('php://temp', 'rw+'),
CURLOPT_FILETIME => TRUE,
);

$url = "http://stackoverflow.com/questions/tagged/java";
$handle = curl_init($url);
curl_setopt_array($handle, $curlOptions);
$content = curl_exec($handle);
echo "Verbose information:\n", !rewind($verbose), stream_get_contents($verbose), "\n";
curl_close($handle);
echo $content;

Output:

Verbose information:
* About to connect() to stackoverflow.com port 80 (#0)
* Trying 64.34.119.12...
* connected
* Connected to stackoverflow.com (64.34.119.12) port 80 (#0)
> GET /questions/tagged/java HTTP/1.1
Host: stackoverflow.com
Accept: */*

< HTTP/1.1 200 OK
< Cache-Control: private
< Content-Type: text/html; charset=utf-8
< Date: Wed, 14 Mar 2012 19:27:53 GMT
< Content-Length: 59110
<
* Connection #0 to host stackoverflow.com left intact

<!DOCTYPE html>
<html>

<head>

<title>Newest 'java' Questions - Stack Overflow</title>
<link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
<link rel="apple-touch-icon" href="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png">
<link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml">
...

Getting HTTP code in PHP using curl

First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:

if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}

Make sure you only fetch the headers, not the body content:

@curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body

For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):

  • How can I check if a URL exists via PHP?

As a whole:

$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo 'HTTP code: ' . $httpcode;

Using PHP Curl to submit form and get results

See this detailed example, Begin by creating a new connection.

$curl_connection = 
curl_init('http://www.domainname.com/target_url.php');

A new connection is created using curl_init() function, which takes the target URL as parameter (The URL where we want to post our data). The target URL is same as the “action” parameters of a normal form, which would look like this:

<form method="post" action="http://www.domainname.com/target_url.php">

Now let’s set some options for our connection. We can do this using the curl_setopt() function. Go to curl_setopt() reference page for more information on curl_setopt() and a complete list of options.

curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

What options do we set here?

First, we set the connection timeout to 30 seconds, so we don’t have our script waiting indefinitely if the remote server fails to respond.

Then we set how cURL will identify itself to the remote server. Some servers will return different content for different browsers (or agents, such as spiders of the search engines), so we want our request to look like it is coming from a popular browser.

CURLOPT_RETURNTRANSFER set to true forces cURL not to display the output of the request, but return it as a string.

Then we set CURLOPT_SSL_VERIFYPEER option to false, so the request will not trigger an error in case of an invalid, expired or not signed SSL certificate.

Finally, we set CURLOPT_FOLLOWLOCATION to 1 to instruct cURL to follow “Location: ” redirects found in the headers sent by the remote site.

Now we must prepare the data that we want to post. We can first store this in an array, with the key of an element being the same as the input name of a regular form, and the value being the value that we want to post for that field.

For example,if in a regular form we would have:

<input type="text" name="firstName" value="Name">
<input type="hidden" name="action" value="Register">

we add this to our array like this:

$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register'

Do the same for every form field.

Data will be posted in the following format:
key1=value1&key2=value2

In order to format the data like this, we are going to create strings for each key-value pair (for example key1=value1), put them in another array ($post_items) then combine them in one string using PHP function implode() .

  foreach ( $post_data as $key => $value) 
{
$post_items[] = $key . '=' . $value;
}

$post_string = implode ('&', $post_items);

Next, we need to tell cURL which string we want to post. For this, we use the CURLOPT_POSTFIELDS option.

curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
Finally, we execute the post, then close the connection.

$result = curl_exec($curl_connection);
curl_close($curl_connection);

By now, the data should have been posted to the remote URL. Go check this, and if it did not work properly, use curl_getinfo() function to see any errors that might have occurred.

print_r(curl_getinfo($curl_connection));

This line displays an array of information regarding the transfer. This must be used before closing the connection with curl_close();

You can also see number and description of the error by outputting curl_errno($curl_connection) and curl_error($curl_connection).

So let’s put everything together. Here is our code:

<?php

//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';

//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}

//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);

//create cURL connection
$curl_connection =
curl_init('http://www.domainname.com/target_url.php');

//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

//perform our request
$result = curl_exec($curl_connection);

//show information regarding the request
print_r(curl_getinfo($curl_connection));
echo curl_errno($curl_connection) . '-' .
curl_error($curl_connection);

//close the connection
curl_close($curl_connection);

?>


Related Topics



Leave a reply



Submit