My code is:
<?php
extract($_POST);
$url = "http://www.domain.com/";
$fields = array(
'myparam1' => 'something',
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER, false);
$result = curl_exec($ch);
print_r("+");
curl_close($ch);
?>
The problem is it show the response in the web browse , but i dont want to. any help would be appreciated.
You have a comment on this line:
//curl_setopt($ch,CURLOPT_RETURNTRANSFER, false);
You should enable this line and set the value to true
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
As you can see on the man page here that option is used this way:
TRUE to return the transfer as a string of the return value of
curl_exec() instead of outputting it out directly.
The option CURLOPT_RETURNTRANSFER will return the output rather than printing it.
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
CURLOPT_POSTFIELDS can take array directly and CURLOPT_RETURNTRANSFER should be true
$url = "http://www.php.net";
$fields = array(
'myparam1' => 'something'
);
// open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
I think this url will help you.
Get data or Content from a URL using cURL PHP
Related
I have rest API of Nodejs Server, I'm trying to make a POST call to it using PHP.
My php code is:
function post_url($apiRoute,$data) {
$request_url = 'http://test-app.herokuapp.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
echo $data ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I have tried calling this function with diff forms of data:
$g = array("_id" => "111");
$postapiresponse = post_url('/CCTRequest/get',json_encode($g));
OR
$postapiresponse = post_url('/CCTRequest/get',json_encode(array("_id" => "111"));
But on server side which Node.js, when I console log req.body I get data like this:
{ '{"_id":"111"}': '' }
How should I pass the data in PHP so I can get proper obj in node.js i.e:
{ '_id': '111' }
See the PHP document:
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_POST:
TRUE to do a regular HTTP POST. This POST is the normal
application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS:
If value is an array, the Content-Type header will be set to multipart/form-data.
So you can pass a query string returned by http_build_query() into CURLOPT_POSTFIELDS:
post_url('/CCTRequest/get', http_build_query($g, null, '&'));
and remove curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));. (In fact, the varieble should be $ch, but you typed $curl, so this line doesn't work.)
In the other way, you can replace curl_setopt($ch, CURLOPT_POST, 1); with
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');, it can prevent the data be encoded automaticlly. And then send json_encode() data.
I have solved by using http_build_query($g, null, '&') for making data.
$g = array("_id" => "111");
$g = http_build_query($g, null, '&');
$postapiresponse = post_url('/CCTRequest/get', $g);
You have a typo in the code, which will prevent it setting the header $curl should be $ch:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
You also need CURLOPT_RETURNTRANSFER uncommented.
function post_url($apiRoute, $data) {
$request_url = 'www.example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
A dummy script that reponds with some json..
<?php
$result['code'] = 200;
echo json_encode($result);
?>
However when I make a curl call to this script,trying to fetch json response and then convert it to array..things go wrong.
Usually I do a simple json_decode($json) and it gives me an array,but apparently when I var_dump json_decode($json) , it gives me int(1) as response. I simply want to fetch the code from the json.
This is my code :
public function curlcall($username, $msg)
{
$url = 'someurl.php';
$fields = array('username' => $username, 'message' => $msg);
$fields_string = null;
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);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo '-------------------------';
var_dump($result);
exit;
}
When I directly call the script from rest client, it gives me perfect json response. But when I request the same json via curl, I dont get the desired result while converting that json in to array.
For simplicity sake, I just echoed a string but still when I var_dump it,it gives me int(1).
Try this:
$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);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //NOTICE this line, which says you want a response returned to the calling script
$result = curl_exec($ch);
curl_close($ch);
echo '-------------------------';
var_dump($result);
I'm trying to write some PHPUnit tests for ajax endpoints. I can do this no sweat when the user doesn't have to be logged in. But to test the endpoint in question, the user does have to be logged in and I want to get the cookie programmatically as part of the test. Basically the test I want to run looks like:
$url = "https://example.com/ajax/endpoint";
$fields = array(
'name'=>'test '.rand(),
'host'=>rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255),
'port'=>rand(1,1000)
);
$fields_string = "";
foreach ($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string, '&');
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIE, $userCookie);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
$this->assertEquals(true, $response);
$json = ob_get_contents();
$return = json_decode($json);
$this->assertEquals('false', $return->success);
$this->assertEquals('', $return->data);
ob_end_clean();
But I don't know a good way to get $userCookie other than opening a browser, logging in, and then reading PHPSESSID from the cookies in the browser. How can I get the cookie for this without grabbing it manually? I'd like to be able to get it from a curl request to the login endpoint:
$url = "https://example.com/ajax/login";
$fields = array(
'username'=>$username,
'password'=>$password
);
$fields_string = "";
foreach ($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
Does anything stop you to grab it programmatically?
$ch = curl_init('https://example.com/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "login=root&password=toor");
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
preg_match_all('/^Set-Cookie: PHPSESSID=(.*?);/mi', $result, $matches);
$userCookie = $matches[1];
You're halfway there with your login cURL request. What you need to do is retrieve the cookie from the response headers to get the PHPSESSID.
How to get response headers with cURL has been asked in another question you can find here.
Once you've got the response headers, you'll have to parse it to get the Set-Cookie header. Using the content of that header for your subsequent tests should work from there.
I'm not able to post values to field and process further steps to download a file. Could anyone suggest where I'm going wrong?
extract($_POST);
$url=header("Location: http://gis.lntecc.com/bwssblnt/Scada.aspx? field1=Kathriguppe%2cSW2DM0402%2c235505H073%2c450");
$fields =array(
"TextBoxFromDate" => urlencode("2014-10-01"),
"TextBoxToDate" => urlencode("2014-10-09")
);
foreach($fields as $key => $value)
$fields_string .= $key.'='.$value.'&';
rtrim($fields, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
Where did I make a mistake since I'm not able to post values to the field?
Simply remove that huge space in your URL:
$url=header("Location: http://gis.lntecc.com/bwssblnt/Scada.aspx? field1=Kathriguppe%2cSW2DM0402%2c235505H073%2c450");
Becomes:
$url=header("Location: http://gis.lntecc.com/bwssblnt/Scada.aspx?field1=Kathriguppe%2cSW2DM0402%2c235505H073%2c450");
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' );
}