Post to another page within a PHP script Post to another page within a PHP script php php

Post to another page within a PHP script


Possibly the easiest way to make PHP perform a POST request is to use cURL, either as an extension or simply shelling out to another process. Here's a post sample:

// where are we posting to?$url = 'http://foo.com/script.php';// what post fields?$fields = array(   'field1' => $field1,   'field2' => $field2,);// build the urlencoded data$postvars = http_build_query($fields);// open connection$ch = curl_init();// set the url, number of POST vars, POST datacurl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POST, count($fields));curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);// execute post$result = curl_exec($ch);// close connectioncurl_close($ch);

Also check out Zend_Http set of classes in the Zend framework, which provides a pretty capable HTTP client written directly in PHP (no extensions required).

2014 EDIT - well, it's been a while since I wrote that. These days it's worth checking Guzzle which again can work with or without the curl extension.


Assuming your php install has the CURL extension, it is probably the easiest way (and most complete, if you wish).

Sample snippet:

//set POST variables$url = 'http://domain.com/get-post.php';$fields = array(                      'lname'=>urlencode($last_name),                      'fname'=>urlencode($first_name),                      'email'=>urlencode($email)               );//url-ify the data for the POSTforeach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }rtrim($fields_string,'&');//open connection$ch = curl_init();//set the url, number of POST vars, POST datacurl_setopt($ch,CURLOPT_URL, $url);curl_setopt($ch,CURLOPT_POST, count($fields));curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);//execute post$result = curl_exec($ch);//close connectioncurl_close($ch);

Credits go to http://php.dzone.com.Also, don't forget to visit the appropriate page(s) in the PHP Manual


For PHP processing, look into cURL. It will allow you to call pages on your back end and retrieve data from it. Basically you would do something like this:

$ch = curl_init();curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt ($ch, CURLOPT_URL,$fetch_url);curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);curl_setopt ($ch,CURLOPT_USERAGENT, $user_agent;curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,60);$response = curl_exec ( $ch );curl_close($ch);

You can also look into the PHP HTTP Extension.