I am new to cURL and I am setting up a test environment to send a cURL POST request using PHP and then I need to mimic the server (responding) program (PHP also) with a status code and payload. After looking and reading up on cURL and corresponding documentation and pertinent RFC documents there are a lot of examples on the request side but I could find no pertinent examples for the response side. My request code is as follows:
$url = 'http://localhost/curlresponder.php';
$fields = array(
'City' => urlencode('Hokeywaka'),
'State' => urlencode('IL'),
'Zip' => urlencode('60677'),
);
foreach($fields as $key => $value)
{$fields_string .= $key . "=" . $value . '&';}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
if ($result === FALSE)
{echo 'Return failure ' . '<br />';
else
{Process $result;}
Now I need to know what the responding program code is - assuming the request is received and processed successfully the response code of 200 is to be sent back with a payload attached (which I gather is also POST since the request was POST.
You just need the remote page to post back a JSON script. And by Post back I just mean echo a JSON string on the page. You can use that in your $result var. You might want to create an API access key just to make sure nobody else uses it if you think there might be a security issue.
$result = curl_exec($ch);
$result = json_decode($result,true);
if ($result['status']=="ok"){
echo "Good request";
}else{
echo "Bad request";
}
you can use the function curl_getinfo to obtain the info you wanted,and code like this
<?php
// Create a cURL handle
$ch = curl_init('http://www.stackoverflow.com/');
// Execute
curl_exec($ch);
// Check HTTP status code
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
}
}
// Close handle
curl_close($ch);
?>
Related
I don't have much experience here, so pls bear with me. I am good with cURL and sending data to API's - right now I want to set up a testing environment as the API isn't ready, but I know what he responses will be.
I will be sending some data to the API via cURL - no issue there. The main variable is called $src and it is a simple POST value. I want to set up a script on another server and echo back some messaging based on $src value.
On the remote script, that will mimic the API I'm getting returned messages like "Resource id #4" or "Resource id #5" I realize that is a generic message. Here is what I am trying to do
cURL scripting
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string,'& ');
$urlFX = 'http://myserver.com/NTLM/testresponse.php';
$ch = curl_init($urlFX);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo($ch);
Test script to mimic API Response:
<?php
$src = $_GET['src'];
if($src == "nt-fx-data-test") {
echo('foo');
} else {
echo('bar');
}
?>
How can I set up a script that will mimic the API's responses based on the $src var value?
Try to hit
http://goelette.net/NTLM/testresponse.php
With params:
src=nt-fx-data-test
src=xp
dst=nt-fx-data-test
Code:
<?php
foreach($_REQUEST as $param => $value) {
if ($param == 'src' and $value == 'nt-fx-data-test') {
echo 'foo';
} else if ($param == 'src' and $value != 'nt-fx-data-test') {
echo 'bar';
} else {
echo "unknown $param";
}
}
I am trying to senddata to a url by using curl with codeigniter. I have successfully implemented the code for sending the data as below.
function postToURL($reg_no, $data)
{
$url = 'http://localhost/abcSystem/Web_data/viewPage';
$send_array = array(
'reg_no' =>$reg_no,
'data' =>$data,
);
$fields_string = http_build_query($send_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$post_data = 'json='.urlencode(json_encode($send_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if (curl_errno($ch)) {
die('Couldn\'t send request: ' . curl_error($ch));
} else {
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
print_r('success'); // this is outputting
return $output;
} else {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
}
The out put is success. I want to see if this post data can be retrieved. So I tried to change the above url controller file as below.
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
But nothing is printing. I want to get the data of posting. Please help me on this.
Your Written code
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
is not to Print or capture Posted Data . Because you are dealing with Current Page PHP INPUT Streaming , whereas you are posting data on Other URL . So what you need to do is just Put a log of posted data in File. Use below code after $output = curl_exec($ch)
file_put_contents("posted_data.txt", $post_data );
This way you will be able to write your each post in file Posted_data.txt File - Make sure you give proper File Permission. If you want to keep trace of each POST than just make the file name dynamic so per API Call it can write a log.
Another option is to save the $post_data in DATABASE - Which is not suggestable from Security point of view.
Where ever you are calling your postToURL() function, you need to output the result of it.
For example:
$output = postToURL('Example', array());
echo $output;
This is because you are returning the curl output rather outputting it.
I'm developing a solution where I send a POST request from the first server to the second server using cURL.
function sendIcuCurlRequest($identity, $action, $payload){
$url = '-- Removed --';
$data = array(
'identity' => $identity,
'action' => $action,
'payload' => $payload
);
$fields = http_build_query($data);
$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_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
On the second server where the cURL request is picked up, ZeroMQ sends the data using SOCKET_PUSH to the WebSocket server (WebSocket server is on the second server).
if(isset($_POST['identity'], $_POST['action'], $_POST['payload'])){
$identity = $_POST['identity'];
$action = $_POST['action'];
$payload = $_POST['payload'];
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'ICU push');
$socket->connect('tcp://127.0.0.1:21002');
$socket->send(json_encode(array('identity' => $identity, 'message' => formatRequest($action, $payload))));
exit;
} else {
echo "Invalid request";
exit;
}
The WebSocket server then makes a RPC Call to the Client.
public function onNewRequest($request){
$requestData = json_decode($request, true);
echo "Outgoing new request for Charge Point: ".var_export($request, true)."\n";
// Check if is valid Station
if(!array_key_exists($requestData['identity'], $this->stations)){
echo "Identity {$requestData['identity']} not found.\n";
return;
}
$station = $this->stations[$requestData['identity']];
$res = $station->send(json_encode($requestData['message']));
file_put_contents(dirname(__FILE__).'/../../logs/broadcast-'.date('Ymd').'.log', print_r($res, true)."\n\n", FILE_APPEND);
}
The Client after some thinking sends a CallResult to an onCallResult method with the response. (Note: I've modified Ratchet's WAMP core so it would be possible to receive CallResults from the Client)
public function onCallResult(ConnectionInterface $conn, $id, array $params){
$url = $conn->WebSocket->request->getUrl();
echo "URL path -- ".$url."\n";
echo "IP -- ".$conn->remoteAddress."\n";
echo "Incoming call result (ID: $id)\n";
echo "Payload -- ".var_export($params, true)."\n";
}
Now to the fun part
Now that I have the response from the Client, I would like to send that response back with cURL using the same connection the initial request came through.
I am thinking that with cURL alone I wouldn't be able to achieve this (I found that there is a new method like curl_pause but that is for 5.5 and up. Current server is running 5.4).
I did also find that ZeroMQ has a socalled REQ and REP but I can't quite figure out if that will serve the prupose on getting it work like this.
What would be the best for me to send a cURL response back to the initial request that came?
I have the following code for cURL using PHP;
$product_id_edit="Playful Minds (1062)";
$item_description_edit="TEST";
$rank_edit="0";
$price_type_edit="2";
$price_value_edit="473";
$price_previous_value_edit="473";
$active_edit="1";
$platform_edit="ios";
//set POST variables
$url = 'https://www.domain.com/adm_test/phpgen/offline_items.php?operation=insert';
$useragent = 'Mozilla/5.0 (Windows NT 6.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1';
$fields = array(
'product_id_edit'=>urlencode($product_id_edit),
'item_description_edit'=>urlencode($item_description_edit),
'rank_edit'=>urlencode($rank_edit),
'price_type_edit'=>urlencode($price_type_edit),
'price_value_edit'=>urlencode($price_value_edit),
'price_previous_value_edit'=>urlencode($price_previous_value_edit),
'active_edit'=>urlencode($active_edit),
'platform_edit'=>urlencode($platform_edit)
);
$fields_string="";
//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_VERBOSE, 1);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//add useragent
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch,CURLOPT_POST,count($fields));
//execute post
$result = curl_exec($ch);
if(curl_errno($ch)){
print "" . curl_error($ch);
}else{
//print_r($result);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//echo "HTTP Response Code: " . curl_error($ch);
echo $httpCode;
//close connection
curl_close($ch);
I have $httpCode printed; I get the code 200; I presume this is OK as I have read in the Manual Pages, however, when I check against the site, the POSTed values does not exist,
does this have something to do with cross-domains as I am not posting it on the same domain?, I'm doing it on 127.0.0.1/site/scrpt.php but how do I get the response code 200 if its not successful?
I also tried to get a 404 which I did by removing a part on the request URL it did return a 404 (this means that cURL is working properly in my assumption)
Does having the url https://www.domain.com/adm_test/phpgen/offline_items.php?operation=insert with the "?operation=insert" has something to do with it?
Let's presume(tho not implied), I'm from another site and I want post values into the form of another website sort'a a robot. tho my objective does not imply any evil intentions, is it that I have to encode thousand lines of info if this is not doable.
Likewise, I don't need a response from the server (but if one is available, then its just fine)
The operation should be passed with CURLOPT_POSTFIELDS. Along with other paramters.
Cross-domain issue happens in case of browser. And your code seems to be a php server side code so this should not be an issue.
Not sure if this is the solution or the problem is different, but this line:
rtrim($fields_string,'&');
Should be this:
$fields_string = rtrim($fields_string,'&');
curl_setopt($ch,CURLOPT_POST,TRUE);
CURLOPT_POST - boolean, it's not a count of values, it's use post flag.
Code 200 indicates that the connection is set up correctly and received a response from the server, but it does not mean that the requested action has been implemented.
Print $result after request to see the response from a web server.
Hey guys, I am trying to create a script that will pull the log's from DirectAdmin so they can be parsed and submitted to a DB, the problem is the login of DirectAdmin.
I tried lots of script but I cant seem to get it to work...
Current script:
$url = 'http://213.247.000.000:2222/CMD_SHOW_LOG?domain=mydomain.com&type=log';
$username = 'xxx';
$password = 'xxx';
$fields = array(
'username'=>urlencode($username),
'password'=>urlencode($password)
);
$fields_string='';
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string,'&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
$result = curl_exec($ch);
if($result===false) {
echo 'CURL ERROR: '.curl_error($ch);
}
curl_close($ch);
var_dump($result);
I've got it!
Made a little function out of it:
function getlog($ip,$username,$password,$domain) {
$url = 'http://'.$ip.':2222';
// set temp cookie
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
// make list of POST fields
$fields = array(
'referer' =>urlencode('/'),
'username'=>urlencode($username),
'password'=>urlencode($password)
);
$fields_string='';
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string,'&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_URL,$url.'/CMD_LOGIN');
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
$result = curl_exec($ch);
if($result===false) {
die('CURL ERROR: '.curl_error($ch));
} else {
curl_setopt($ch,CURLOPT_URL,$url.'/CMD_SHOW_LOG?domain='.$domain.'&type=log');
curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if($result===false) {
die('CURL ERROR: '.curl_error($ch));
} else {
return $result;
}
}
}
You would probably better use the DirectAdmin PHP API class.
You need to use fiddler and firebug to figure out what is being sent when you login using your browser.
You then run your curl request through fiddler and make sure the exact same thing is posted.
You might need to set a refer, user-agent or cookies. You have too look at the request to tell what you need to send.
Web developer is a useful tool to disable cookies and javascript. See if you can login without cookies or javascript.
Use firebug will let you know if there are any ajax requests going on behind the scenes.
Blindly posting using curl will drive you insane.
You don't have to url-encode your username/password. Just pass the regular array to CURL, and it'll take care of the encoding.
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);