cURL - Open files outside server's root directory - apache

I am wondering, how can I access a file outside the root directory of my server?
For example, /home/username/FILE.mp3
The code i am currently using to open a file is the following:
<?php
$location = "ABSOLUTE-PATH/FILE.mp3";
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FILETIME, true);
$data = curl_exec($ch);
$timestamp = curl_getinfo($ch, CURLINFO_FILETIME);
curl_close($ch);
if ($data === false) {
echo 'CURL Failed';
exit;
}
//Get file size
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
$begin = 0;
$end = $contentLength - 1;
if (preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
{
$begin = intval($matches[1]);
if (!empty($matches[2]))
{
$end = intval($matches[2]);
}
}
if (isset($_SERVER['HTTP_RANGE']))
{ header('HTTP/1.1 206 Partial Content'); }
else
{ header('HTTP/1.1 200 OK'); }
header('Accept-Ranges: bytes');
header('Content-Length: ' . $contentLength);
header("Content-Range: bytes $begin-$end/$contentLength");
header('Content-Type: audio/mpeg');
header('Cache-Control: public, must-revalidate, max-age=0');
if ($timestamp != -1) { //otherwise unknown
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $timestamp) . " GMT");
}
ob_clean();
flush();
echo ($data);
exit;
?>
I know as a fact that cURL doesn't work with relative paths and i assume that a file outside the root directory is treated as a relative link.

Why would you use cURL? Typically cURL would be something you would use to communicate with a different server via HTTP. Why not use file, file_get_contents, fopen or similar?

Related

Hello am trying to make an API post request using php curl error code 32601

am new in api trying to see if my Api works once I execute the code am geting Error code 32601 'Method not found' I have gone through the code and though am not sure I think the error is syntax related any guidance will be appreciated
<?php
$key = '';
$secret = '';
$path = 'https://api.cloudtrax.com/voucher/network_id=254281';
$data = array(
"code"=> "b3c34test",
"duration"=> 1,
"max_users"=> 1,
"up_limit"=> 10,
"down_limit"=> 20,
"comment"=> "Free access for guests",
"purge_days"=> 2);
$headers = array(
'nonce' => 'ThisIsANonce',
'authorization' => "key=" . $key . ",timestamp=" . time() . ",nonce=" . $nonce,
'authorization_header' => "Authorization: " . $authorization,
'signature' => hash_hmac('sha256', $authorization . $path . $data, $secret),
);
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch)); }
else
echo "RESULT: \n" . $result . "\n";
?>

One click login to WHM

I'm trying to generate a one-click login URL for WHM.
The code below was one based on a cPanel login (which I was going to change for WHM), but it didn't work at all. Access denied errors.
Here's what I tried:
$whmusername = 'root';
$whmpassword = 'password';
$hostname = 'server.example.com';
$cpanel_user = 'cpaneluser';
$query = "https://$hostname/json-api/create_user_session?api.version=1&user=$cpanel_user&service=cpaneld";
$curl = curl_init(); // Create Curl Object.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // Allow self-signed certificates...
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // and certificates that don't match the hostname.
curl_setopt($curl, CURLOPT_HEADER, false); // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Return contents of transfer on curl_exec.
$header[0] = "Authorization: Basic " . base64_encode($whmusername.":".$whmpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // Set the username and password.
curl_setopt($curl, CURLOPT_URL, $query); // Execute the query.
$result = curl_exec($curl);
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
}
$decoded_response = json_decode( $result, true );
$session_url = $decoded_response['data']['url'];
$cookie_jar = 'cookie.txt';
curl_setopt($curl, CURLOPT_HTTPHEADER, null); // Unset the authentication header.
curl_setopt($curl, CURLOPT_COOKIESESSION, true); // Initiate a new cookie session.
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar); // Set the cookie jar.
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar); // Set the cookie file.
curl_setopt($curl, CURLOPT_URL, $session_url); // Set the query url to the session login url.
$result = curl_exec($curl); // Execute the session login call.
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
// Log an error if curl_exec fails.
}
$session_url = preg_replace( '{/login(?:/)??.*}', '', $session_url );
$query = "$session_url/execute/Ftp/list_ftp";
curl_setopt($curl, CURLOPT_URL, $query); // Change the query url to use the UAPI call.
$result = curl_exec($curl); // Execute the UAPI call.
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
// log error if curl exec fails
}
curl_close($curl);
print $result;
I was able to do this by using this following code. This code was originally used in a WHM API example, but I reapplied it for this purpose.
$user = "root";
$token = "API Token";
$query = "https://server.example.com:2087/json-api/create_user_session?api.version=1&user=root&service=whostmgrd";
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
$header[0] = "Authorization: whm $user:$token";
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_URL, $query);
$result = curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($http_status != 200) {
echo "[!] Error: " . $http_status . " returned\n";
} else {
$json = json_decode($result, true);
$login_url = $json['data']['url'];
echo $login_url;
}
curl_close($curl);
Instead of using WHM user/password, use just the user and login with an API Token which can be created in WHM -> Manage API Tokens.
Then take the json data and output just the URL.

How to make separate config file for sms sending

I have done a sms sending code in codeigniter. It is worked successfully. But actually i want to make a config file so that i will not write the username, password, senderid on each page.
Here is my code below. First i have done a library file for sms sending.
Sms.php
<?php
class SMS
{
function SendSMS($url)
{
if(function_exists('curl_init'))
{
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
$data = curl_exec($ch);
if($data === FALSE){
throw new Exception(curl_errno($ch));
}
curl_close($ch);
return $data;
}
else
{
return false;
}
}
}
?>
Again for sms sending i am writting code in each controller something like this.
$sms_username = "GAPSMS";
$sms_password = "GAPSMS";
$sms_senderid = "GAPSMS";
$sms_mobile = $mobile;
$sms_message = urlencode('Your One Time Password for transaction is: '.$otp);
$sms_api = "http://sendsms.sandeshwala.com/API/WebSMS/Http/v1.0a/index.php?username=$sms_username&password=$sms_password&sender=$sms_senderid&to=$sms_mobile&message=$sms_message&reqid=1&format={json|text}";
$this->sms->SendSMS($sms_api);
This much below code i want to write in a config file in such a way so that i can write this once and then can use in every controller to send sms.
$sms_username = "GAPSMS";
$sms_password = "GAPSMS";
$sms_senderid = "GAPSMS";
UPDATED
In CodeIgniter, libraries can have their own configuration file. Let's change your library a bit:
<?php
class Sms
{
private $_username = 'GAPSMS'; // default value
private $_password = 'GAPSMS'; // default value
private $_senderid = 'GAPSMS'; // default value
/**
* Class constructor so the config
* file is loaded.
*/
public function __construct($config = array())
{
if ( ! empty($config))
{
foreach ($config as $key => $val)
{
$this->{"_".$key} = $val;
}
}
}
function send($mobile, $message)
{
if(function_exists('curl_init'))
{
$url = 'http://sendsms.sandeshwala.com/API/WebSMS/Http/v1.0a/index.php?username='.$this->_username.'&password='.$this->_password.'&sender='.$this->_senderid.'&to='.$mobile.'&message='.$message.'&reqid=1&format={json|text}';
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
$data = curl_exec($ch);
if($data === FALSE){
throw new Exception(curl_errno($ch));
}
curl_close($ch);
return $data;
}
else
{
return false;
}
}
}
Then go create the config file application/config/sms.php inside which you put:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['username'] = 'GAPSMS';
$config['password'] = 'GAPSMS';
$config['senderid'] = 'GAPSMS';
// End of file.
Now whenever the library is loaded, and config file is loaded as well as values are set, everything should work just fine. And the rest of the code would be:
// Load the library and simply pass mobile number and message.
$this->load->library('sms');
$data = $this->sms->send('0123456789', 'Hello, this is the message');

FatSecret API - food.get method invalid signature

Hi I am new to FatSecret Platform API and i developed a PHP script to access food details using foods.search method Here is the foods.search method Api call example,used Curl and works perfect. <?php $consumer_key = "xxxxxxx"; $secret_key = "xxxxxxx"; //Signature Base String //<HTTP Method>&<Request URL>&<Normalized Parameters> $base = rawurlencode("GET")."&"; $base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver. api&"; //sort params by abc....necessary to build a correct unique signature $params = "method=foods.search&"; $params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key $params .= "oauth_nonce=123&"; $params .= "oauth_signature_method=HMAC-SHA1&"; $params .= "oauth_timestamp=".time()."&"; $params .= "oauth_version=1.0&"; $params .= "search_expression=".urlencode($_GET['pasVar']); $params2 = rawurlencode($params); $base .= $params2; //encrypt it! $sig= base64_encode(hash_hmac('sha1', $base, "$secret_key&", true)); // replace xxx with Consumer Secret //now get the search results and write them down $url = "http://platform.fatsecret.com/rest/server.api?". $params."&oauth_signature=".rawurlencode($sig); //$food_feed = file_get_contents($url); list($output,$error,$info) = loadFoods($url); echo '<pre>'; if($error == 0){ if($info['http_code'] == '200') echo $output; else die('Status INFO : '.$info['http_code']); } else die('Status ERROR : '.$error); function loadFoods($url) { // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, $url); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); $error = curl_error($ch); $info = curl_getinfo($ch); // close curl resource to free up system resources curl_close($ch); return array($output,$error,$info); } ?> the above script working perfect and retrieves food details using search method.But when i use food.get method to retrieve data using food_id it says invalid signature error,Here's the food.get method api call example,I have given correct keys and passed food_id parameter.Can someone help me to solve the issue,I am really struck on this code.It says invalid signature error. <?php $consumer_key = "xxxxxxxxx"; $secret_key = "xxxxxxxxxx"; //Signature Base String //<HTTP Method>&<Request URL>&<Normalized Parameters> $base = rawurlencode("GET")."&"; $base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&"; //sort params by abc....necessary to build a correct unique signature $params = "method=food.get&"; $params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key $params .= "oauth_nonce=".rand()."&"; $params .= "oauth_signature_method=HMAC-SHA1&"; $params .= "oauth_timestamp=".time()."&"; $params .= "oauth_version=1.0&"; $params .= "food_id=".urlencode($_GET['pasVar']); $params2 = rawurlencode($params); $base .= $params2; //encrypt it! $sig= base64_encode(hash_hmac('sha1', $base, "$secret_key&", true)); // replace xxx with Consumer Secret //now get the search results and write them down $url = "http://platform.fatsecret.com/rest/server.api?". $params."&oauth_signature=".rawurlencode($sig); //$food_feed = file_get_contents($url); list($output,$error,$info) = loadFoods($url); echo '<pre>'; if($error == 0){ if($info['http_code'] == '200') echo $output; else die('Status INFO : '.$info['http_code']); } else die('Status ERROR : '.$error); function loadFoods($url) { // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, $url); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); $error = curl_error($ch); $info = curl_getinfo($ch); // close curl resource to free up system resources curl_close($ch); return array($output,$error,$info); } ?> Help me what's the error in the code and help me to solve the issue as i have to use this API in my project Thanks waiting for your replies....
You should order you params by alpha.
So you should do it in this order:
$params = "food_id=".urlencode($_GET['pasVar'])."&";
$params .= "method=food.get&";
$params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key
$params .= "oauth_nonce=".rand()."&";
$params .= "oauth_signature_method=HMAC-SHA1&";
$params .= "oauth_timestamp=".time()."&";
$params .= "oauth_version=1.0";

Facebook API call- "This API version is deprecated"

I'm trying to call to Photo.upload on the the Facebook API server. As far as I can tell the code to construct the call is good but I can't understand the responce I'm getting back from the server. As far as I can see, this call is ment to work and other people don't get this problem. I can only reason that something is wrong with the code. The commented stuff is an artifact of me trying different things to get a different responce from the server. The original code that I've changed was in part taken from an example of how to do this which I couldn't get to work either really:
http://www.jaisenmathai.com/blog/2008/11/27/using-the-facebook-api-to-upload-photos/
Server Responce:
12 This API version is deprecated method photos.upload api_key b92cee19a33c861275bfce4695896e44 call_id 1250194789.61 garden_jpg /var/www/vivaladan/pictureyourselfhull/garden.jpg v 0 sig 896ee95339cad24ce7e64a05ca764123
Code:
$key = b92cee19a33c861275bfce4695896e44;
$ver = 1.0;
$cid = microtime(true);
$uid = BIGINT;
$file= "garden.jpg";
$args = array(
//amethod => photos.upload,
v => $ver,
api_key => $key,
//uid => $uid,
call_id => $cid,
//format => XML
);
$args[basename($file)] = realpath($file);
signRequest($args,$sec);
$postString = "";
foreach($args as $index => $value) {
$postString .= $index ."=".$value."&";
}
$postString = trim($postString, '&');
$ch = curl_init();
$url = "http://api.facebook.com/restserver.php?method=photos.upload";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$data = curl_exec($ch);
echo $data;
function signRequest(&$args, $secret){
ksort($args);
$sig = "";
foreach($args as $k => $v){
$sig .= $k . '=' . $v;
}
$sig .= $secret;
$args[sig] = md5($sig);
}
Rest API call is not working anymore.
Try GraphApi
I'm guessing it's because you're using $ver = 0.0; - there's no 0.0 version of the API.
try using api.new.facebook.com API URL instead