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";
}
}
Related
I'm doing a project and one of the requests is to automatically submit a form to a random site, which is specified from time to time
This is my cURL code :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dati_post);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Code to get POST parameters :
foreach ($html->find('form[method=post],form[method=POST]') as $forms_post) {
$n_formPOST++;
$formPOST_action = $forms_post->action;
foreach ($forms_post->find('input') as $input) {
if ($input->type == 'text') {
$dati_testo[$input->name] = "text";
} else if ($input->type == 'email' || $input->name == 'email') {
$dati_random[$input->name] = "emailrandom#gmail.com";
} else if ($input->type == 'hidden') {
$dati_random[$input->name] = $input->value;
} else {
$dati_random[$input->name] = "random";
}
}
foreach ($forms_post->find('textarea') as $textarea) {
if ($textarea->disabled != true) {
$dati_testo[$textarea->name] = "text";
}
}
foreach ($forms_post->find('button') as $bottone) {
if ($bottone->type == 'submit') {
$dati_random[$bottone->name] = "random";
}
}
The problem is that in some sites POST is done correctly and I receive the right answer, which corresponds to the answer I would receive by doing it manually.
On other sites, it seems that the form is not submitted.
I have repeatedly checked the URL that I insert in the cURL and also the data that I pass and if I use them manually it works.
I even tried using online tools that perform POST / GET passing the same URL and the same data that I get in my project and it works.
The url_post is made from url host+form action.
I don't understand if there is something wrong in my curl code, considering I'm pretty sure the data I'm passing to the curl are corrects to complete the POST.
Data :
Site URL : http://www.comune.ricigliano.sa.it/
Form Action : index.php?action=index&p=228
Url_post : http://www.comune.ricigliano.sa.it/index.php?action=index&p=228
POST data :
'qs' => 'something to research'
'Submit2' => 'Cerca'
You need to use the curl_exec() function in order to execute the cURL. It takes the $ch param, like such:
// Execute cURL
curl_exec($ch);
// Close cURL
curl_close($ch);
More info here
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);
?>
first time asker, but many times you helped me back in the day. Great job! I ask this because I'm struggling here with and issue I'm unable to solve, and as my PHP (and cURL) knowledge is so scarce, I'm lost.
The Background
I'm developing a Javascript app, that needs to connect to several different servers and make XMLRPC calls to them. The app is working perfectly running it locally (disabling cross-domain security), but to make it run online I knew I had to use a cross-domain proxy, so after several days of searching and investigating, I didn't found one that could make the work, so I managed to make one myself (not without blood and sweat). Know what? It (almost) works!!!
This is my proxy.php:
<?
function readHeader($ch, $header) {
//extracting data to send it to the client
$headers = explode("\n", $header);
foreach ($headers as $item) {
// $string= str_replace($delimiter, $mainDelim, $string);
if (strpos($item, 'Set-Cookie:') !== false) {
$cookie = trim(substr($item,strlen('Set-Cookie:')));
header('X-Set-Cookie:' . $cookie);
} else {
header($item);
}
}
return strlen($header);
}
$allowed_domains = array('domain1.com', 'domain2.com');
header('Content-Type: text/html; charset=iso-8859-1');
$REFERRER = $_SERVER['HTTP_REFERER'];
if ($REFERRER == '') {
// What do you do here?
exit(header('Location: index.html'));
}
$domain = substr($REFERRER, strpos($REFERRER, '://') + 3);
$domain = substr($domain, 0, strpos($domain, '/'));
if (!in_array($domain, $allowed_domains)) {
exit(header('Location: index.html'));
}
$XMLRPC_SERVICE = $_SERVER['HTTP_X_PROXY_URL'];
$xml = $HTTP_RAW_POST_DATA;
$header[] = "Content-type: text/xml; charset=utf-8";
$header[] = "Connection: close";
$header[] = "Accept: text/xml";
if ($_SERVER['HTTP_X_SET_COOKIE'])
$cookie = $_SERVER['HTTP_X_SET_COOKIE'];
if ($_SERVER['HTTP_X_PROXY_URL'] === "other-domain.com")
$header[] = "x-custom-header: value";
$ch = curl_init($XMLRPC_SERVICE);
//URL to post to
curl_setopt($ch, CURLOPT_URL, $XMLRPC_SERVICE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
if ($cookie)
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'readHeader');
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
} else {
curl_close($ch);
echo $response;
}
?>
The Issue
As I've said, I got it working partially. In fact, it works for most of the usual XMLRPC needs.
It gets the remote server address from the HTTP_X_PROXY_URL header of the request, and using cURL makes the call and returns the values to the javascript client without issues.
The problem comes when I need to get/send a session cookie (probably when getting it, because the cookie value is pretty different when I make calls directly from the app locally). In any case, I can't get the cookie stuff to work. As you see, I'm surrounding the Set-Cookie browser protection on AJAX calls with my own X-Set-Cookie header, that the proxy gets to use or translates accordingly, but the issue with cookies is here, and I can't use cookies, that are critical for app functionality.
I'm trying to use curl to do a simple GET with one parameter called redirect_uri. The php file that gets called prints out a empty string for $_GET["redirect_uri"] it shows red= and it seems like nothing is being sent.
code to do the get
//Get code from login and display it
$ch = curl_init();
$url = 'http://www.besttechsolutions.biz/projects/facebook/testget.php';
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_GET,1);
curl_setopt($ch,CURLOPT_GETFIELDS,"redirect_uri=my return url");
//execute post
print "new reply 2 <br>";
$result = curl_exec($ch);
print $result;
// print "<br> <br>";
// print $fields_string;
die("hello");
the testget.php file
<?php
print "red-";
print $_GET["redirect_uri"];
?>
This is how I usually do get requests, hopefully it will help you:
// create curl resource
$ch = curl_init();
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Set maximum redirects
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
// Allow a max of 5 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// set url
if( count($params) > 0 ) {
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, "$url?$query");
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
// $output contains the output string
$output = curl_exec($ch);
// Check for errors and such.
$info = curl_getinfo($ch);
$errno = curl_errno($ch);
if( $output === false || $errno != 0 ) {
// Do error checking
} else if($info['http_code'] != 200) {
// Got a non-200 error code.
// Do more error checking
}
// close curl resource to free up system resources
curl_close($ch);
return $output;
In this code, the $params could be an array where the key is the name, and the value is the value.
Ok I am trying to access some JSON using a PHP proxy as I have been told is the only way to do a cross domain access when you don't control the sites policies.
Here is the code below I am trying to use as a php proxy as shared by a fellow stackoverflow user:
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
problem is when I replace $URL with http://www.nfl.com/liveupdate/scorestrip/ss.json nothing seems to happen. I am not really sure how to use this PHP proxy though either as I don't ever do this type of thing.
Am I suppose to create this in a seperate php file and then send a request to this code? I am kind of against the wall on what exactly to do here to make it so I can access the json from the site above.
Am I suppose to create this in a seperate php file and then send a request to this code?
Yes. The code above should resend your request made from JS to a remote service on another domain. Which is what does the trick - enables crossdomain POST requests from JS.
<?php
$server_url = "http://example.com/";
$options = array
(
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_HTTPGET => 1
);
$service = $_GET["service"];
$request_headers = Array();
foreach($_SERVER as $i=>$val) {
if (strpos($i, 'HTTP_') === 0) {
$name = str_replace(array('HTTP_', '_'), array('', '-'), $i);
if ($name != 'HOST')
{
$request_headers[] = "{$name}: {$val}";
}
}
}
$options[CURLOPT_HTTPHEADER] = $request_headers;
switch (strtolower($_SERVER["REQUEST_METHOD"]))
{
case "post":
$options[CURLOPT_POST] = true;
$url = "{$server_url}/services/".$service;
$options[CURLOPT_POSTFIELDS] = file_get_contents("php://input");
break;
case "get":
unset($_GET["service"]);
$querystring = "";
$first = true;
foreach ($_GET as $key => $val)
{
if (!$first) $querystring .= "&";
$querystring .= $key."=".$val;
$first = false;
}
$url = "{$server_url}/services/".$service."?".$querystring;
break;
default:
throw new Exception("Unsupported request method.");
break;
}
$options[CURLOPT_URL] = $url;
$curl_handle = curl_init();
curl_setopt_array($curl_handle,$options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);
$response = explode("\r\n\r\n",$server_output);
$headers = explode("\r\n",$response[0]);
foreach ($headers as $header)
{
if ( !preg_match(';^transfer-encoding:;ui', Trim($header)) )
{
header($header);
}
}
echo $response[1];
This is a slightly modified version of the script I use, unfortunately not well documented.
Hope it helps.
I would suggest using Ben Almans Simple PHP Proxy
Simple PHP Proxy