How can I make a post request to a different php page within a php script? I have one front end computer as the html page server, but when the user clicks a button, I want a backend server to do the processing and then send the information back to the front end server to show the user. I was saying that I can have a php page on the back end computer and it will send the information back to the front end. So once again, how can I do a POST request to another php page, from a php page?
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 data
curl_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 connection
curl_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 POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_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 connection
curl_close($ch);
Credits go to http://php.dzone.com.
Also, don't forget to visit the appropriate page(s) in the PHP Manual
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
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.
Like the rest of the users say it is easiest to do this with CURL.
If curl isn't available for you then maybe
http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
If that isn't possible you could write sockets yourself
http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html
For those using cURL, note that CURLOPT_POST option is taken as a boolean value, so there's actually no need to set it to the number of fields you are POSTing.
Setting CURLOPT_POST to TRUE (i.e. any integer except zero) will just tell cURL to encode the data as application/x-www-form-urlencoded, although I bet this is not strictly necessary when you're passing a urlencoded string as CURLOPT_POSTFIELDS, since cURL should already tell the encoding by the type of the value (string vs array) which this latter option is set to.
Also note that, since PHP 5, you can use the http_build_query function to make PHP urlencode the fields array for you, like this:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
Solution is in target="_blank" like this:
http://www.ozzu.com/website-design-forum/multiple-form-submit-actions-t25024.html
edit form like this:
<form method="post" action="../booking/step1.php" onsubmit="doubleSubmit(this)">
And use this script:
<script type="text/javascript">
<!--
function doubleSubmit(f)
{
// submit to action in form
f.submit();
// set second action and submit
f.target="_blank";
f.action="../booking/vytvor.php";
f.submit();
return false;
}
//-->
</script>
Although not ideal, if the cURL option doesn't do it for you, may be try using shell_exec();
CURL method is very popular so yes it is good to use it. You could also explain more those codes with some extra comments because starters could understand them.
Related
Im a newbie im trying to get a script to trigger another script with Curl in PHP but it dosent seem to be sending the paramaters.
Is there a seperate function to append parameters?
<?php
$time = time();
$message = "hello world";
$urlmessage = urlencode( $message );
$ch = curl_init("http://mysite.php?message=$urlmessage&time=$time");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Could anyone point me in the right direction??
The accepted answer is good for POST, but what if OP wanted specifically to GET? Some REST APIs specify the http method and often it's no good POSTing when you should be GETting.
Here is a fragment of code that does GET with some params:
$endpoint = 'http://example.com/endpoint';
$params = array('foo' => 'bar');
$url = $endpoint . '?' . http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
This will cause your request to be made with GET to http://example.com/endpoint?foo=bar. This is the default http method, unless you set it to something else like POST with curl_setopt($ch, CURLOPT_POST, true) - so don't do that if you specifically need to GET.
If you need to use one of the other http methods (DELETE or PUT for example) then use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method). This also works for GET and POST.
You need curl_setopt() along with the CURLOPT_POSTFIELDS param.
That'll POST the given params to the target page.
curl_setopt($ch, CURLOPT_POSTFIELDS, 'foo=1&bar=2&baz=3');
PS: also check http_build_query() which is handy when sending many variables.
you need set CURLOPT_POST as true and CURLOPT_POSTFIELDS => parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
a suggestion,set 'CURLOPT_RETURNTRANSFER', as true to return the transfer as a string of the return value of curl_exec($ch) instead of outputting it out directly
Here is A Simple Solution for this.
$mobile_number = $_POST['mobile_number'];
$sessionid = $_POST['session_id'];
CURLOPT_URL => 'https://xxyz.jkl.com/v2.0/search?varible_that_you_want_to_pass='.$mobile_number.'&requestId=1616581154955&locale=en-US&sessionId='.$sessionid,
I am using PHP (WAMPServer) to receive a form submission, and then CURL to pass the file to another server for processing.
Here is an example to illustrate (not the actual code):
$data = array(
'file' => '#'.$_FILES['key']['tmp_name']
);
Here's what I'm using for CURL... and as I was pasting the code I noticed that I still have http_build_query() in my code... so, that must be the problem.
$CURL = curl_init();
curl_setopt($CURL, CURLOPT_URL, $operation['callback']);
$query_string = http_build_query($arguments);
curl_setopt($CURL, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($CURL, CURLOPT_POST, TRUE);
curl_setopt($CURL, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($CURL);
curl_close($CURL);
return $result;
My problem is that the last server isn't receiving the file. Instead, the data is passed as a key-value pair.
$_POST contains 'file' => '#c:\wamp\tmp\xyz.tmp'
What I would prefer, is that the files was transferred, and $_FILES has information about it.
Don't build an http query for the CURLOPT_POSTFIELDS. Curl can directly accept an array of fields and do its own encoding/mangling.
By building your own query, you're 'hiding' the # that indicates a file upload and CURL will not trigger its upload mechanisms.
In other words, this will fix things:
$data = array(
'file' => '#'.$_FILES['key']['tmp_name']
);
curl_setopt($CURL, CURLOPT_POSTFIELDS, $data);
if you add your CURL method code, we could better answer you...
Try to transfer the file as binary, and add the filesize in the header in your curl.
Well title says all I guess.
I've tried to print_r($_SERVER) but my 'post-request' I made with fiddler doesn't show up.
I'm really out of my mind after trying about 1 hour now :S
What I actually want is to send a POST request with JSON in the request-body. Then I want to json_decode(request-body); This way I can use the variables to reply. So I don't need to put my variables in the URL
Edit:
This is my POST
$url = 'http.........jsonAPI/jsonTestAPI.php';
$post = array("token" => "923874657382934857y32893475y43829ufhgjdkfn");
$jsonpost = json_encode($post);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);
$response = curl_exec($ch);
curl_close($ch);
Try file_get_contents('php://input'); or PHP global $HTTP_RAW_POST_DATA.
the easiest way to get that done would be to put your json into a hidden input-field and then have the containing form being submitted using POST.
Im a newbie im trying to get a script to trigger another script with Curl in PHP but it dosent seem to be sending the paramaters.
Is there a seperate function to append parameters?
<?php
$time = time();
$message = "hello world";
$urlmessage = urlencode( $message );
$ch = curl_init("http://mysite.php?message=$urlmessage&time=$time");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Could anyone point me in the right direction??
The accepted answer is good for POST, but what if OP wanted specifically to GET? Some REST APIs specify the http method and often it's no good POSTing when you should be GETting.
Here is a fragment of code that does GET with some params:
$endpoint = 'http://example.com/endpoint';
$params = array('foo' => 'bar');
$url = $endpoint . '?' . http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
This will cause your request to be made with GET to http://example.com/endpoint?foo=bar. This is the default http method, unless you set it to something else like POST with curl_setopt($ch, CURLOPT_POST, true) - so don't do that if you specifically need to GET.
If you need to use one of the other http methods (DELETE or PUT for example) then use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method). This also works for GET and POST.
You need curl_setopt() along with the CURLOPT_POSTFIELDS param.
That'll POST the given params to the target page.
curl_setopt($ch, CURLOPT_POSTFIELDS, 'foo=1&bar=2&baz=3');
PS: also check http_build_query() which is handy when sending many variables.
you need set CURLOPT_POST as true and CURLOPT_POSTFIELDS => parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
a suggestion,set 'CURLOPT_RETURNTRANSFER', as true to return the transfer as a string of the return value of curl_exec($ch) instead of outputting it out directly
Here is A Simple Solution for this.
$mobile_number = $_POST['mobile_number'];
$sessionid = $_POST['session_id'];
CURLOPT_URL => 'https://xxyz.jkl.com/v2.0/search?varible_that_you_want_to_pass='.$mobile_number.'&requestId=1616581154955&locale=en-US&sessionId='.$sessionid,
I'm new to using cURL, but from what I have read, the following should post the variables to the page, then print the result. The result prints, but it doesn't seem like the POST variables went because no results are generated. FireBug doesn't show anything going either. Any ideas what I'm doing wrong?
Thanks for your help!
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://butlercountyclerk.org/bcc-11112005/ForeclosureSearch.aspx");
$data = array(
'Search:btnSearch' => 'Search',
'Search:ddlMonth' => '1',
'Search:ddlYear' => '2011'
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
echo $output;
Based on the coding of the site, it appears that you're missing a number of variables. Take for example, the actual post request made to the search page:
__VIEWSTATE=dDwtMjk2Mjk5NzczO3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDE+Oz47bDx0PDtsPGk8Mz47aTwxOT47PjtsPHQ8dDw7cDxsPGk8MD47aTwxPjtpPDI+O2k8Mz47aTw0PjtpPDU+Oz47bDxwPDIwMDY7MjAwNj47cDwyMDA3OzIwMDc+O3A8MjAwODsyMDA4PjtwPDIwMDk7MjAwOT47cDwyMDEwOzIwMTA+O3A8MjAxMTsyMDExPjs+Pjs+Ozs+O3Q8QDA8Ozs7Ozs7Ozs7Oz47Oz47Pj47Pj47Pj47PmVlaXw5JK161vti9TC+QMdeTNQI&Search:ddlMonth=1&Search:ddlYear=2011&Search:txtCompanyName=&Search:txtLastName=&Search:txtCaseNumber=&Search:btnSearch=Search
This is post-feeding though URLDecode by the way. What this means though, is that your array of 3 values is missing data. At the very least, I'd suspect that Search:btnSearch=Search is missing, and would suggest that you implement all fields into your POST request.