writing cURL like function in a rails app - php

I'm trying to convert this PHP cURL function to work with my rails app. The piece of code is from an SMS payment gateway that needs to verify the POST paramters. Since I'm a big PHP noob I have no idea how to handle this problem.
$verify_url = 'http://smsgatewayadress';
$fields = '';
$d = array(
'merchant_ID' => $_POST['merchant_ID'],
'local_ID' => $_POST['local_ID'],
'total' => $_POST['total'],
'ipn_verify' => $_POST['ipn_verify'],
'timeout' => 10,
);
foreach ($d as $k => $v)
{
$fields .= $k . "=" . urlencode($v) . "&";
}
$fields = substr($fields, 0, strlen($fields)-1);
$ch = curl_init($verify_url); //this initiates a HTTP connection to $verify_url, the connection headers will be stored in $ch
curl_setopt($ch, CURLOPT_POST, 1); //sets the delivery method as POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //The data that is being sent via POST. From what I can see the cURL lib sends them as a string that is built in the foreach loop above
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //This verifies if the target url sends a redirect header and if it does cURL follows that link
curl_setopt($ch, CURLOPT_HEADER, 0); //This ignores the headers from the answer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //This specifies that the curl_exec function below must return the result to the accesed URL
$result = curl_exec($ch); //It ransfers the data via POST to the URL, it gets read and returns the result
if ($result == true)
{
//confirmed
$can_download = true;
}
else
{
//failed
$can_download = false;
}
}
if (strpos($_SERVER['REQUEST_URI'], 'ipn.php'))
echo $can_download ? '1' : '0'; //we tell the sms sever that we processed the request
I've googled a cURL lib counterpart in Rails and found a ton of options but none that I could understand and use in the same way this script does.
If anyone could give me a hand with converting this script from php to ruby it would be greatly appreciated.

The most direct approach might be to use the Ruby curb library, which is the most straightforward wrapper for cURL. A lot of the options in Curl::Easy map directly to what you have here. A basis might be:
url = "http://smsgatewayadress/"
Curl::Easy.http_post(url,
Curl::PostField.content('merchant_ID', params[:merchant_ID]),
# ...
)

Related

What's the best way to call php variables from an external domain?

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);

simplexml_load_file not working with variable but works with string

I am trying to connect to a CRM (Pardot).
I have this to create the URL necessary to call the XML:
//this will log in and print your API Key (good for 1 hour) to the console
$rz_key = callPardotApi('https://pi.pardot.com/api/login/version/3',
array(
'email' => 'myemail#email.com',
'password' => 'password',
'user_key' => '032222222222222b75a192daba28d'
)
);
$number_url = 'https://pi.pardot.com/api/prospect/version/3/do/query';
$number_url .= '?user_key=032222222222222b75a192daba28d';
$number_url .= '&api_key=';
$number_url .= trim($rz_key);
$number_url .= '&list_id=97676';
$ike = simplexml_load_file($number_url);
print_r($ike);
Now this code returns :
SimpleXMLElement Object ( [#attributes] => Array ( [stat] => fail [version] => 1.0 ) [err] => Invalid API key or user key )
However, if I echo $number_url, and copy and paste that URL into my browser, it loads wonderfully. If I copy and paste the same echoed URL into simplexml_load_file it works wonderfully also. I MUST use a variable, because the API key is only good for one hour. Any ideas?
The rest of the code is here, which was provided by Pardot :
<?php
/**
* Call the Pardot API and get the raw XML response back
*
* #param string $url the full Pardot API URL to call, e.g. "https://pi.pardot.com/api/prospect/version/3/do/query"
* #param array $data the data to send to the API - make sure to include your api_key and user_key for authentication
* #param string $method GET", "POST", "DELETE"
* #return string the raw XML response from the Pardot API
* #throws Exception if we were unable to contact the Pardot API or something went wrong
*/
function callPardotApi($url, $data, $method = 'GET')
{
// build out the full url, with the query string attached.
$queryString = http_build_query($data, null, '&');
if (strpos($url, '?') !== false) {
$url = $url . '&' . $queryString;
} else {
$url = $url . '?' . $queryString;
}
$curl_handle = curl_init($url);
// wait 5 seconds to connect to the Pardot API, and 30
// total seconds for everything to complete
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl_handle, CURLOPT_TIMEOUT, 30);
// https only, please!
curl_setopt($curl_handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
// ALWAYS verify SSL - this should NEVER be changed. 2 = strict verify
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
// return the result from the server as the return value of curl_exec instead of echoing it
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
if (strcasecmp($method, 'POST') === 0) {
curl_setopt($curl_handle, CURLOPT_POST, true);
} elseif (strcasecmp($method, 'GET') !== 0) {
// perhaps a DELETE?
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, strtoupper($method));
}
$pardotApiResponse = curl_exec($curl_handle);
if ($pardotApiResponse === false) {
// failure - a timeout or other problem. depending on how you want to handle failures,
// you may want to modify this code. Some folks might throw an exception here. Some might
// log the error. May you want to return a value that signifies an error. The choice is yours!
// let's see what went wrong -- first look at curl
$humanReadableError = curl_error($curl_handle);
// you can also get the HTTP response code
$httpResponseCode = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
// make sure to close your handle before you bug out!
curl_close($curl_handle);
throw new Exception("Unable to successfully complete Pardot API call to $url -- curl error: \"".
"$humanReadableError\", HTTP response code was: $httpResponseCode");
}
// make sure to close your handle before you bug out!
curl_close($curl_handle);
return $pardotApiResponse;
}
//this will log in and print your API Key (good for 1 hour) to the console
$rz_key = callPardotApi('https://pi.pardot.com/api/login/version/3',
array(
'email' => 'myemail#email.com',
'password' => 'myPassword',
'user_key' => '********************'
)
);
$number_url = 'https://pi.pardot.com/api/prospect/version/3/do/query';
$number_url .= '?user_key=****************';
$number_url .= '&api_key=';
$number_url .= $rz_key;
$number_url .= '&list_id=97676';
$number_url = preg_replace('/\s+/', '', $number_url);
$ike = simplexml_load_file($number_url);
print_r($ike);
?>

curl is not working in Yii

when i am using curl in my core php file it's working fine for me and getting expected result also... my core php code is...
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://stage.auth.stunnerweb.com/index.php?r=site/getUser");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
echo $data; //here i am getting respond proper
here in above i am making call to getUser function and i am getting respond from that function...
but now my problem is when i am using this same code in my any Yii controller (tried to use it in SiteController & Controller) but it's not working...
public function beforeAction()
{
if(!Yii::app()->user->isGuest)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL ,"http://stage.auth.stunnerweb.com/index.php?r=site/kalpit");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
echo $data;
}
else
return true;
}
in yii can't we use curl like this?
Can you please suggest me how to use curl in yii?
Thanks in advance
Better use yii-curl
Setup instructions
Place Curl.php into protected/extensions folder of your project
in main.php, add the following to 'components':
php
'curl' => array(
'class' => 'ext.Curl',
'options' => array(/.. additional curl options ../)
);
Usage
to GET a page with default params
php
$output = Yii::app()->curl->get($url, $params);
// output will contain the result of the query
// $params - query that'll be appended to the url
to POST data to a page
php
$output = Yii::app()->curl->post($url, $data);
// $data - data that will be POSTed
to PUT data
php
$output = Yii::app()->curl->put($url, $data, $params);
// $data - data that will be sent in the body of the PUT
to set options before GET or POST or PUT
php
$output = Yii::app()->curl->setOption($name, $value)->get($url, $params);
// $name & $value - CURL options
$output = Yii::app()->curl->setOptions(array($name => $value))->get($get, $params);
// pass key value pairs containing the CURL options
You are running your code inside a beforeAction() method which is not supposed to render any data at all. On top of that, you do not let the method return anything if the current user is a guest. Please read the API docs concerning this.

Can I Send URL with Parameters via PHP and retrieve the data?

I'm starting to help a friend who runs a website with small bits of coding work, and all the code required will be PHP. I am a C# developer, so this will be a new direction.
My first stand-alone task is as follows:
The website is informed of a new species of fish. The scientific name is entered into, say, two input controls, one for the genus (X) and another for the species (Y). These names will need to be sent to a website in the format:
http://www.fishbase.org/Summary/speciesSummary.php?genusname=X&speciesname=Y&lang=English
Once on the resulting page, there are further links for common names and synonyms.
What I would like to be able to do is to find these links, and call the URL (as this will contain all the necessary parameters to get the particular data) and store some of it.
I want to save data from both calls and, once completed, convert it all into xml which can then be uploaded to the website's database.
All I'd like to know is (a) can this be done, and (b) how difficult is it?
Thanks in advance
Martin
If I understand you correctly you want your script to download a page and process the downloaded data. If so, the answers are:
a) yes
b) not difficult
:)
Oke... here some more information: I would use the CURL extension, see:
http://php.net/manual/en/book.curl.php
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
?>
I used a thing called snoopy (http://sourceforge.net/projects/snoopy/) 4 years a go.
I took about 500 customers profiles from a website that published them in a few hours.
a) Yes
b) Not difficult when have experience.
Google for CURL first, or allow_url_fopen.
file_get_contents() will do the job:
$data = file_get_contents('http://www.fishbase.org/Summary/speciesSummary.php?genusname=X&speciesname=Y&lang=English');
// Отправить URL-адрес
function send_url($url, $type = false, $debug = false) { // $type = 'json' or 'xml'
$result = '';
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
} else {
if (($content = #file_get_contents($url)) !== false) $result = $content;
}
if ($type == 'json') {
$result = json_decode($result, true);
} elseif ($type == 'xml') {
if (($xml = #simplexml_load_file($result)) !== false) $result = $xml;
}
if ($debug) echo '<pre>' . print_r($result, true) . '</pre>';
return $result;
}
$data = send_url('http://ip-api.com/json/212.76.17.140', 'json', true);

Callback from API not happening after posting parameters to API URL from server side

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.

Categories