How to read CURL POST on remote server? - php

This is my cURL POST function:
public function curlPost($url, $data)
{
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
$this->curlPost('remoteServer', array(data));
How do I read the POST on the remote server?
The remote server is using PHP... but what var in $_POST[] should I read
for e.g:- $_POST['fields'] or $_POST['result']

You code works but i'll advice you to add 2 other things
A. CURLOPT_FOLLOWLOCATION because of HTTP 302
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
B. return in case you need to output the result
return $result ;
Example
function curlPost($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $result;
}
print(curlPost("http://yahoo.com", array()));
Another Example
print(curlPost("http://your_SITE", array("greeting"=>"Hello World")));
To read your post you can use
print($_REQUEST['greeting']);
or
print($_POST['greeting']);

as a normal POST request ... all data posted can be found in $_POST ... except files of course :) add an &action=request1 for example to URL
if ($_GET['action'] == 'request1') {
print_r ($_POST);
}
EDIT: To see the POST vars use the folowing in your POST handler file
if ($_GET['action'] == 'request1') {
ob_start();
print_r($_POST);
$contents = ob_get_contents();
ob_end_clean();
error_log($contents, 3, 'log.txt' );
}

Related

how to view final url before submission curl php

I want to know final url just before executing curl to check all parameters passing as desired. how to view that.
<?PHP
function openurl($url) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
openurl($sms_url);
?>
desired output to check all params and its values passing correct..
http://remoteserver/plain?user=user123&password=user#user!123&Text=TESThere
You forgot to add the $postvars as parameter to your function.
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
// create a test var which we can display on screen / log
$test_url = sms_url . http_build_query($postvars);
// either send it to the browser
echo $test_url;
// or send it to your log (make sure loggin is enabled!)
error_log("CURL URL: $test_url", 0);
openurl($sms_url, $postvars);

Remote function calling with paramerters

I am using this function for calling method from one server to another in PHP.
function get_url($request_url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
}
$request_url = 'http://second-server-address/listening_page.php?function=somefunction';
$response = get_url($request_url);
Here I am giving a URL with function name. The question is what if the function receives few parameters? How would we pass parameters to the method on another server using CURL.
Just add
$request_url = 'http://second-server-address/listening_page.php?function=somefunction&funcParam1=val&funcParam2.val
Use these passed parameters in your function
If you want to pass parameter as post request then try this.
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
$data = array(
"name" => "c.bavota",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan"
);
post_to_url("http://yoursite.com/post-to-page.php", $data);

How to post file to local file by curl

public function curl($source = null, $type = 'get', $fields = array())
{
$result = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if (strtolower($type) === 'post') {
curl_setopt($ch, CURLOPT_POST, true);
if (count($fields) !== 0) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
}
}
$result = curl_exec($ch);
if ($result === false) {
$result = curl_error($ch);
}
curl_close($ch);
return $result;
}
This is my curl function, I would like to do PHPUnit test to check some other upload file function, therefore I need to simulate form post method with file in PHPUnit, the problem is, curl need to give domain name, of course I can get domain by $_SERVER method, but in command line it won't work, how will you do unitest to test a file upload behavior.

php curl POST not returnning anything

I have the following php Curl code, to submit a form and get the tables of result
<?php
function httpPost($url,$params)
{
//echo 1;
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output=curl_exec($ch);
curl_close($ch);
//return $params;
return $output;
}
$params = array(
"form_hf_0"=>null,
"searchMode:edit"=>"Births",
"searchSwitch:birthContainer:regNumber:regNumber"=>null,
"searchSwitch:birthContainer:regNumber:regYear"=>null,
"searchSwitch:birthContainer:subjectName:familyName:edit"=>"smith",
"searchSwitch:birthContainer:subjectName:givenName:edit"=>null,
"searchSwitch:birthContainer:subjectName:otherNames:edit"=>null,
"searchSwitch:birthContainer:fatherGivenName:edit"=>null,
"searchSwitch:birthContainer:fatherOtherNames:edit"=>null,
"searchSwitch:birthContainer:motherGivenName:edit"=>null,
"searchSwitch:birthContainer:motherOtherNames:edit"=>null,
"searchSwitch:birthContainer:dateOfEvent:range:edit"=>true,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:day"=>01,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:month"=>01,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:year"=>1788,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:day"=>31,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:month"=>12,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:year"=>1913,
"searchSwitch:birthContainer:district:edit"=>null,
"search-button"=>"Search"
);
$param1 = array("username"=>"sa","password"=>"1");
echo httpPost("https://lifelink.bdm.nsw.gov.au/lifelink/familyhistory/search?0-2.IFormSubmitListener-mainContent-form",$params);
?>
The form link is here:https://lifelink.bdm.nsw.gov.au/lifelink/familyhistory/search?0
I have nothing printed.
Can anyone pointed where is wrong?
The result is here http://ec2-54-213-181-25.us-west-2.compute.amazonaws.com/htdocs/lib/CURL/curl.php
Nothing in the table as normal search with family name "smith", range date 1788 to 1914.

Accessing the SPtrans API, authorization failing on information requests

I'm trying to use the SPtrans API (http://www.sptrans.com.br/desenvolvedores/APIOlhoVivo.aspx), which is supposed to provide public transport information for the Sao Paulo (Brazil) area.
I'm trying to get in using PHP and curl.
I'm able to put in the requests and can authenticate myself (with a post request to /Login/Autenticar?token={token}. The post request returns a 'true' (and only a 'true').
(It seems that I need to put the token both as a GET and a POST.)
However, if I then put in an information (GET) request, for example to /Linha/Buscar?termosBusca={termosBusca}, I get a consistent return of "Authorization has been denied for this request." message.
You can see this (not) working at:
http://00qq.com/sptrans/index.php
Any thoughts or ideas on this would be extremely helpful.
Here's the code that picks up the data:
function getResult($accesspoint, $page, $postData, $post = true) {
$ch = curl_init();
$t = http_build_query($postData);
$url = $accesspoint.$page."?".$t;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post == true) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
$output = object_to_array(json_decode($output));
return $output;
}
Update
#chesterbr put me on the right track: I had to create, collect and store cookies upon authentication and then use those upon subsequent requests. Below is a proof of concept.
$site["sptrans"]["accesspoint"] = "http://api.olhovivo.sptrans.com.br/v0";
$site["sptrans"]["page"]["Login"] = "/Login/Autenticar";
$site["sptrans"]["page"]["Parada"] = "/Parada/Buscar";
$site["sptrans"]["page"]["Linha"] = "/Linha/Buscar";
$site["sptrans"]["token"] = ""; //This should contain your token.
error_reporting(E_ALL);
ini_set('display_errors', 1);
function object_to_array($data) {
if (is_array($data) || is_object($data)) {
$result = array();
foreach ($data as $key => $value)
$result[$key] = object_to_array($value);
return $result;
}
return $data;
}
function getResult($accesspoint, $page, $postData, $cookie, $post = true) {
$ch = curl_init();
$t = http_build_query($postData);
$url = $accesspoint.$page."?".$t;
// print $url."<br />";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
// curl_setopt($ch, CURLOPT_COOKIESESSION, true);
if ($post == true) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
$output = object_to_array(json_decode($output));
return $output;
}
//Create a cookie for the duration of the page.
$ckfile = tempnam ("cache/cookies", "spt.");
print "Authentication<br />";
$postData["token"] = $site["sptrans"]["token"];
$output = getResult($site["sptrans"]["accesspoint"], $site["sptrans"]["page"]["Login"], $postData, $ckfile);
print_r ($output);
unset($postData);
print "<hr />";
print "Linha<br />";
$postData["termosBusca"] = "8000";
$output = getResult($site["sptrans"]["accesspoint"], $site["sptrans"]["page"]["Linha"], $postData, $ckfile, false);
print_r ($output);
unset($postData);
print "<hr />";
print "Parada<br />";
$postData["termosBusca"] = "Afonso";
$output = getResult($site["sptrans"]["accesspoint"], $site["sptrans"]["page"]["Parada"], $postData, $ckfile, false);
print_r ($output);
unset($postData);
print "<hr />";
//Delete the cookie
unlink($ckfile);
You can see this work at http://00qq.com/sptrans/index.php
The API requires you to store the cookies from the authentication call and include them in subsequent ones (otherwise, the server can't know those calls belong to the same session, since HTTP is stateless by default).
You can make that in PHP by configuring the cURL library as described in: https://stackoverflow.com/a/12885587. See also http://www.php.net/manual/en/function.curl-setopt.php for more information on such options (search for "COOKIE" options).

Categories