I'm setting two virtual hosts on my local pc, the first domain is http://dev.local and the other one handles the api request http://api.server.local/. The idea is simple, but not sure how to implement this kind of setup. So here's the actual process. The dev.local will send some important parameters and values which the API server read it first and validate the data sent from dev.local.
For example I have the API key provided from API server and being stored in the database together with the domain that can only use that API. So the most important thing is that I want to make sure that only dev.local can do the request. Here is some illustration.
[illustration] https://i.imgur.com/OKu34TM.png
I already tried cURL functions but for some reasons, the data can be access by anyone if they have a copy of the api key. So I want to make sure where the request come from or the origin of the request.
This is the script I have for my dev.local in order to get access to my api.server.local
<?php
$__apiServer = 'http://api.server.local';
$__apiVersion = '1.0';
$__apikey = '7c4a8d09ca3762af61e59520943dc26494f8941b'; // API Key
$__apiEmail = 'johnsmith99#gmail.com'; // Registered Email Address
$__apiUser = 'johnsmith'; // Username
$__curlURL = "";
$__curlURL = "{$__curlURL}{$__apiServer}/v{$__apiVersion}";
$__curlURL = "{$__curlURL}/bin.php?user={$__apiUser}";
$__curlURL = "{$__curlURL}&email={$__apiEmail}";
$__curlURL = "{$__curlURL}&key=$__apikey";
$__curlURL = "{$__curlURL}&domain=$_SERVER[SERVER_NAME]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $__curlURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if(curl_exec($ch) === FALSE) {
echo "Failed to load resource files from the API Server: $__apiServer";
} else {
$__curlURL = curl_exec($ch);
if($err != 1){
eval(' ?>' . $__curlURL);
}
}
curl_close($ch);
I expect that the value can only be return if the required data are valid. For now the ouput can be read as expected but can be accessible by anyone if they have the copy of api key and other credentials.
I figure it out. I used cURL POST method and it is more secure than using GET. And parse array variables to validate the main parameters.
Related
I have a small php script: domain1.com/script1.php
//my database connections, check functions and values, then, load:
$variable1 = 'value1';
$variable2 = 'value2';
if ($variable1 > 5) {
$variable3 = 'ok';
} else {
$variable3 = 'no';
}
And I need to load the variables of this script on several other sites of mine (different domains, servers and ips), so I can control all of them from a single file, for example:
domain2.com/site.php
domain3.com/site.php
domain4.com/site.php
And the "site.php" file needs to call the variable that is in script1.php (but I didn't want to have to copy this file in each of the 25 domains and edit each of them every day):
site.php:
echo $variable1 . $variable2 . $variable3; //loaded by script.php another domain
I don't know if the best and easiest way is to pass this: via API, Cookie, Javascript, JSON or try to load it as an include even from php, authorizing the domain in php.ini. I can't use get variables in the url, like ?variable1=abc.
My area would be php (but not very advanced either), and the rest I am extremely layman, so depending on the solution, I will have to hire a developer, but I wanted to understand what to ask the developer, or maybe the cheapest solution for this (even if not the best), as they are non-profit sites.
Thank you.
If privacy is not a concern, then file_get_contents('https://example.com/file.php') will do. Have the information itself be passed as JSON text it's the industry standard.
If need to protect the information, make a POST request (using cURL or guzzle library) with some password assuming you're using https protocol.
On example.com server:
$param = $_REQUEST("param");
$result = [
'param' => $param,
'hello' => "world"
];
echo json_encode($data);
On client server:
$content = file_get_contents('https://example.com/file.php');
$result = json_decode($content, true);
print_r ($result);
For completeness, here's a POST request:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/file.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
$result = json_decode($server_output , true);
Could anyone share a working example of how to verify on my PHP server using cURL the Facebook access_token I got from the browser, so that I can verify the login details from the browser are trustworthy then safely create a session for my user on my server?
To review, the steps I want to make work are:
User clicks "Continue with Facebook" on the browser and gets an access_token.
I send this to my PHP server.
The server sends a cURL request to Facebook to validate the user access_token.
If access_token is valid, then create session for the user on my server.
I have my own app with email, Google and Facebook login. I appreciate any help, thanks.
After quite some time, I got a working PHP script.
Just replace the missing variable values and it should work. Also make
sure you have cURL working on your PHP server with phpinfo() or some other means;
<?php
///////////////////////////////////////
// prep Facebook verification
///////////////////////////////////////
// sanitize login data
$_POST['facebook_access_token'] = filter_var($_POST['facebook_access_token'], FILTER_SANITIZE_STRING);
// set variables
$facebook_user_access_token = $_POST['facebook_access_token'];
$my_facebook_app_id = 'REPLACE';
$my_facebook_app_secret = 'REPLACE';
$facebook_application = 'REPLACE'; // in my case 'domain.com', as set up in Facebook
///////////////////////////////////////
// get facebook access token
///////////////////////////////////////
$curl_facebook1 = curl_init(); // start curl
$url = "https://graph.facebook.com/oauth/access_token?client_id=".$my_facebook_app_id."&client_secret=".$my_facebook_app_secret."&grant_type=client_credentials"; // set url and parameters
curl_setopt($curl_facebook1, CURLOPT_URL, $url); // set the url variable to curl
curl_setopt($curl_facebook1, CURLOPT_RETURNTRANSFER, true); // return output as string
$output = curl_exec($curl_facebook1); // execute curl call
curl_close($curl_facebook1); // close curl
$decode_output = json_decode($output, true); // decode the response (without true this will crash)
// store access_token
$facebook_access_token = $decode_output['access_token'];
///////////////////////////////////////
// verify my access was legitimate
///////////////////////////////////////
$curl_facebook2 = curl_init(); // start curl
$url = "https://graph.facebook.com/debug_token?input_token=".$facebook_user_access_token."&access_token=".$facebook_access_token; // set url and parameters
curl_setopt($curl_facebook2, CURLOPT_URL, $url); // set the url variable to curl
curl_setopt($curl_facebook2, CURLOPT_RETURNTRANSFER, true); // return output as string
$output2 = curl_exec($curl_facebook2); // execute curl call
curl_close($curl_facebook2); // close curl
$decode_output2 = json_decode($output2, true); // decode the response (without true this will crash)
// test browser and Facebook variables match for security
if ($my_facebook_app_id == $decode_output2['data']['app_id'] && $decode_output2['data']['application'] == $facebook_application && $decode_output2['data']['is_valid'] == true) {
echo 'Success. Login is valid.';
}
else {
echo 'Error.';
}
?>
Special thanks to https://stackoverflow.com/a/16092226/6252345
I want to convert given postcode to latitude and longitude to integrate in my cart project.
But when I try to grab latitude and longitude with google api they are showing some error like,
"We're sorry... ... but your computer or network may be sending
automated queries. To protect our users, we can't process your request
right now."
What is wrong with my code? My code is shown below.
function getLatLong($code){
$mapsApiKey = 'AIzaSyC1Ky_5LFNl2zq_Ot2Qgf1VJJTgybluYKo';
$query = "http://maps.google.co.uk/maps/geo?q=".urlencode($code)."&output=json&key=".$mapsApiKey;
//---------
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $query);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$data = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//-----------
//$data = file_get_contents($query);
// if data returned
if($data){
// convert into readable format
$data = json_decode($data);
$long = $data->Placemark[0]->Point->coordinates[0];
$lat = $data->Placemark[0]->Point->coordinates[1];
return array('Latitude'=>$lat,'Longitude'=>$long);
}else{
return false;
}
}
print_r(getLatLong('SW1W 9TQ'));
Use useragent
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0');
Also check whether you missed or not to send any HTTP Request header. Also check whether you are using required parameters(GET or POST) with your request.
By the way, If you are using too many requests then you have nothing to do with this error. Just stop sending requests, or limit your requests so that it doesn't upset the server.
the case is: how to upload file through an Html Form in server A and the Uploaded files should be sent to Server B
I read answers related to this topic, but its allow you only to send data in a post method.
HTML/PHP Post method to different server
Ajax POST to another server - overcoming the cross domain restrictions
some answers advice to use the ftp_fput() function, which is risky because your credentials will be online and accessible. (you should use ftp_login ( resource $ftp_stream , string $username , string $password ))
1. Usage of ftp (make sure to use an encrypted connection, not plain ftp) and scp, where you can use ssh public key authentication, which is equally safe as storing your mysql password, just make sure the credentials are not accessible. You will need any kind of authentication anyway (also for html/php)
1a. Rsync + crontab
Isn't it possible to use some kind of cronjob and rsync to do the task?
2. To receieve send a file with curl
<?php
$url = 'http://target-server/accept.php';
//This needs to be the full path to the file you want to send.
$file = realpath('./sample.jpeg');
// the post fields.
// note the "#", to denote that the file path should be evaluated
$post = array(
'extra_post_field' => '123456',
'file_contents' => '#' . $file
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// send the request & close the connection
$result = curl_exec($ch);
curl_close($ch);
// result is the response, this can also be a json response for example
echo $result;
?>
2b. Receive a file (note: this example needs a security/authentication layer)
<?php
// make sure targetFolder is writable by the webserver
$targetFolder = '/your/uploaded/files/folder';
// This will be the target file
$targetFile = $targetFolder . basename($_FILES['file_contents']['name']);
// do your authentication + validation here
echo '<pre>';
if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $targetFile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Something went wrong uploading the file";
}
API integration description
The API needs a form to be posted to the API URL with some input fields and a customer token. The API processes and then posts response to a callback.php file on my server. I can access the posted vals using $_POST in that file. That's all about the existing method and it works fine.
Requirement
To hide the customer token value from being seen from client side. So I started with sending server side post request.
Problem
I tried with many options but the callback is not happening -
1) CURL method
$ch = curl_init(API_URL);
$encoded = '';
$_postArray['customer_token'] = API_CUSTOMER_TOKEN;
foreach($_postArray as $name => $value)
{
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
$resp echoes 1 if the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); is removed but the callback does not happen. I am setting a session variable in the callback script to verify.Is it needed that the API be synchronous in order to use curl method, so that curl_exec returns the response?
2) without CURL as given in Posting parameters to a url using the POST method without using a form
But the callback is not happening.
I tried with the following code too, but looks like my pecl is not installed properly because the HttpRequest() is not defined.
$req = new HttpRequest($apiUrl, HttpRequest::METH_POST);
$req->addQueryData($params);
try
{
$r->send();
if ($r->getResponseCode() == 200)
{
echo "success";
// success!
}
else
{
echo "failure";
// got to the API, the API returned perhaps a RESTful response code like 404
}
}
catch (HttpException $ex)
{
// couldn't get to the API (probably)
}
Please help me out! I just need to easily send a server side post request and get the response in the callback file.
Try to debug your request using the curl_get_info() function:
$header = curl_getinfo($ch);
print_r($header);
Your request might be OK but it my result in an error 404.
EDIT: If you want to perform a post request, add this to your code:
curl_setopt($ch, CURLOPT_POST, true);
EDIT: Something else I mentioned at your code: You used a '1' at the 'CURLOPT_RETURNTRANSFER' but is should be 'true':
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
At least this is how I usually do it, and you never know if the function will also understand a '1' as 'true';
EDIT: The real problem: I copy-pasted your source and used it on one of my pages getting this error:
Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\phptests\test.php on line 8
The error is in this line:
foreach($_postArray as $name => $value)
$_postArray is an array with one value holding the other values and you need either another foreach or you simple use this:
foreach($_postArray['customer_token'] as $name => $value)
As discussed in the previous question, the callback is an entirely separate thing from your request. The callback also will not have your session variables, because the remote API is acting as the client to the callback script and has its own session.
You should really show some API documentation here. Maybe we're misunderstanding each other but as far as I can see, what you are trying to do (get the callback value in the initial CURL request) is futile, and doesn't become any less futile by asking twice.