Digest Authentication using Request PHP or any other in codeigniter - php

I have used
http://requests.ryanmccue.info/ and https://github.com/rmccue/Requests
I am using Request library, but any other library can also be suggested.
My code for CodeIgniter
class Home extends CI_Controller{
public function index(){
$this->load->library('PHPRequest');
$this->rest_client();
}
function rest_client(){
$user = 'myusername';
$pass = 'mypass';
$BaseApiUrl = 'myurl';
$headers = array('Accept' => 'application/json');
$options = array('auth' => new Requests_Auth_Basic(array($user, $pass)));
$request = Requests::get($BaseApiUrl, $headers, $options);
var_dump($request->status_code);
var_dump($request->body);
}
}
But I am getting the following error:
int(401) string(28) "HTTP Digest: Access denied. "

Using Curl PHP Now
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false, // for https
CURLOPT_USERPWD => $username . ":" . $password,
CURLOPT_HTTPAUTH => CURLAUTH_DIGEST
);
$ch = curl_init();
curl_setopt_array( $ch, $options );
try {
$raw_response = curl_exec( $ch );
// validate CURL status
if(curl_errno($ch))
throw new Exception(curl_error($ch), 500);
// validate HTTP status code (user/password credential issues)
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code != 200)
throw new Exception("Response with Status Code [" . $status_code . "].", 500);
} catch(Exception $ex) {
if ($ch != null) curl_close($ch);
throw new Exception($ex);
}
if ($ch != null) curl_close($ch);
return json_decode($raw_response);

Related

cURL fails in PHP, but works in console

Experimenting with webapp with Spotify API. Satisfied that all data settings on Spotify Developer site OK (client_id, client_secret etc).
When I run the following in the console...
curl -H "Authorization: Bearer <the actual access token>" https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V
... it works perfectly. Even running the following url directly in the browser works:
https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V?access_token=<the actual access token>
I've tried tagging on the access token to the url in the method below, but no luck. If I try to use the access token in the header and the url, I get an error telling me to use one or the other.
<?php
session_start();
class SpotifyClientCredentials
{
public $url = 'https://accounts.spotify.com/api/token';
public $client_id = '<the client id>';
public $client_secret = '<the client secret>';
public $token = false;
public function __construct()
{
if(isset($_SESSION['token'])) $this->token = $_SESSION['token'];
}
public function connect()
{
$enc = base64_encode($this->client_id. ':' . $this->client_secret);
$header = "Authorization: Basic $enc";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $this->url,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header],
CURLOPT_POSTFIELDS => 'grant_type=client_credentials'
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result,true);
$this->token = $data['access_token'];
$_SESSION['token'] = $this->token;
}
curl_close($ch);
}
public function request($requestUrl)
{
if(!$this->token) $this->connect();
$header = "Authorization: Bearer {$this->token}";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $requestUrl,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header]
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result, true);
print_r($data);
}
curl_close($ch);
}
}
$spfy = new SpotifyClientCredentials;
$spfy->request('https://api.spotify.com/v1/albums/4aawyAB9vmqN3uQ7FjRGTy');
Getting rid of CURLOPT_POST => true, gives an 502 Bad Gateway.
I get no response / output whatsoever with the code, as is, above.
As mentioned, tagging on the access token to the requestUrl:
CURLOPT_URL => $requestUrl . '?access_token=' . $this->token,
gives the following curl response:
Array ( [error] => Array ( [status] => 400 [message] => Must not use more than one method for including an access token ) )
If I then comment out the CURLOPT_HTTPHEADER, I once again get no response.
The access token seeems valid, as when I don't include it, I get an error message. Truly at a loss - any help gratefully appreciated.

API returns 1 profile data when array is passed

I am stuck on this for past 1 days and can't seem to get it to work. When I pass the array of userIds to profilesearch I only get 1 result back from the APi.
Please advise what am I doing wrong?
class Players{
public $username = "username";
public $password = "password";
public $base_url = "https://www.example.com/api/v1";
public $userIds = [];
//This is the first method that fires of to get the userId
public function usersearch(){
$url = $this->base_url . '/usersearch?informat=json&format=json';
$request = '{"identification":[]}';
$username = $this->username;
$password = $this->password;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array("Content-Type: UTF-8"),
CURLOPT_USERPWD => "$username:$password",
CURLOPT_TIMEOUT => 60,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $request,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_UNRESTRICTED_AUTH => true,
CURLOPT_FORBID_REUSE => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
var_dump(curl_error($ch), 'cURL Errors');
curl_close($ch);
} else {
$result = array();
$result = json_decode($response, true);
$result = $result['results'][0]['results'];
//Now that we have the list of users, loop over it and get their userId and save it in the userIds property as in array
foreach($result as $key => $item){
$this->userIds[] = $item['userId'];
}
}
curl_close($ch);
//Let's go and grab the profile data
$this->profilesearch();
}
public function profilesearch(){
//Make a local variable of the property userIds which contains list of userIds in array format
$userIds = $this->userIds;
$userIds = implode(',', $userIds); //This becomes "101,239,240"
$url = $this->base_url . '/profilesearch?informat=json&format=json';
$request = '{"formNames":["Athlete Summary"],"userIds":[' . $userIds . ']}'; //This becomes {"formNames":["Athlete Summary"],"userIds":[101,239,240]}
$username = $this->username;
$password = $this->password;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array("Content-Type: UTF-8"),
CURLOPT_USERPWD => "$username:$password",
CURLOPT_TIMEOUT => 60,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $request,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_UNRESTRICTED_AUTH => true,
CURLOPT_FORBID_REUSE => false,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
var_dump(curl_error($ch), 'cURL Errors');
} else {
$result = array();
$result = json_decode($response, true);
var_dump( $result ); //I get only one user data
}
curl_close($ch);
}
}
I think the API probably expects another JSON format. But I would recommend to
not craft a JSON string by hand you should use instead json_encode to build the
JSON string i.e.:
$request = json_encode([
'formNames' => ['Athlete Summary'],
'userIds' => $userIds,
]);

php curl throwing 500 error

The curl is giving me 500 error. How to fix 500 error ?
$msg='Phone:'.$_POST['phone'].',Email:'.$_POST['email'].',Message:'.$_POST['query'].''; // This is dynamic msg.
$urlpara="http://xxx.xxx.xxx.xx:8080/sendsms/bulksms?username=xxx&password=xxxx&type=0&dlr=1&destination=xxxx&source=xxxx&message=".$msg."";
$response = sentSmS($urlpara);
if($response){
header('Location: thankyou.html');
exit;
}else{
header('Location: thankyou.html');
exit;
}
function sentSmS($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
return true;
}
You return $content in sentSmS function, from where you get it? maybe you want to return curl_exec($ch) ?
try debug it:
function sentSmS($url) {
$ch = curl_init();
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'cUrl',
CURLOPT_CONNECTTIMEOUT => 10, // timeout on connect
CURLOPT_TIMEOUT => 400, // timeout on response - after 400s
CURLOPT_FRESH_CONNECT => true,
CURLOPT_VERBOSE => true,
CURLOPT_URL => $url,
CURLOPT_HEADER => 0
];
curl_setopt_array( $ch, $options);
$result = curl_exec($ch);
if (empty($result)){
$error = curl_error($ch);
$errorNumber = curl_errno($ch);
$exception = new \Exception('curl call error: '.$error, $errorNumber);
throw $exception;
}
curl_close($ch);
return $result;
}

How can I ingest an image into Fedora Commons using PHP?

I am trying to ingest an image into a Fedora Commons repository using PHP. Here is the code I'm using:
$queryArgs = array(
"label" => "label goes here",
"format" => "info:fedora/fedora-system:METSFedoraExt-1.1",
"namespace" => $prefix,
"ownerID" => $fedoraUsername,
"logMessage" => "log message goes here"
);
$url = sprintf(
"%s://%s:%d/%s/objects/%s?%s",
"http",
$host,
$port,
"fedora",
$prefix . ":" . $identifier,
http_build_query($queryArgs)
);
$headers = array("Accept: text/xml", "Content-Type: image/jpg");
$userPassword = $fedoraUsername . ":" . $fedoraPassword;
$verifyPeer = false;
$fileContents = file_get_contents("http://localhost/path/to/image.jpg");
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userPassword,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_SSL_VERIFYPEER => $verifyPeer,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fileContents
);
$curlHandle = curl_init();
curl_setopt_array($curlHandle, $curlOptions);
curl_exec($curlHandle);
error_log(print_r(curl_getinfo($curlHandle), true));
At the end I print out whatever curl_getinfo has to say, notably [http_code] => 415.
HTTP Error 415 Unsupported media type
What am I doing wrong here?
I finally figured it out. I ended up making two different requests: one to create a new empty object in Fedora, the other to attach a datastream to that object. Here is the code (I put all this in a class named Fedora, but this is not necessary and might not fit your needs):
<?php
class Fedora {
// Use cURL with the provided functions and return the result if the HTTP Code recieved matches the expected HTTP Code
private function curlThis($curlOptions, $expectedHttpCode) {
$returnValue = false;
try {
$curlHandle = curl_init();
if ($curlHandle === false) {
throw new Exception(
"`curl_init()` returned `false`"
);
}
$settingOptionsSucceeded = curl_setopt_array($curlHandle, $curlOptions);
if ($settingOptionsSucceeded === false) {
throw new Exception(
sprintf(
"`curl_setopt_array(...)` returned false. Error: %s. Info: %s",
curl_error($curlHandle),
print_r(curl_getinfo($curlHandle), true)
),
curl_errno($curlHandle)
);
}
$curlReturn = curl_exec($curlHandle);
if ($curlReturn === false) {
throw new Exception(
sprintf(
"`curl_exec(...)` returned false. Error: %s. Info: %s",
curl_error($curlHandle),
print_r(curl_getinfo($curlHandle), true)
),
curl_errno($curlHandle)
);
}
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if ($httpCode === false) {
throw new Exception(
sprintf(
"`curl_getinfo(...)` returned false. Error: %s.",
curl_error($curlHandle)
),
curl_errno($curlHandle)
);
}
if ($httpCode !== $expectedHttpCode) {
throw new Exception(
sprintf(
"`curl_getinfo(...)` returned an unexpected http code (expected %s, but got %s). Error: %s. Complete info: %s",
$expectedHttpCode,
$httpCode,
curl_error($curlHandle),
print_r(curl_getinfo($curlHandle), true)
),
curl_errno($curlHandle)
);
}
$returnValue = $curlReturn;
} catch (Exception $e) {
trigger_error(
sprintf(
"(%d) %s",
$e->getCode(),
$e->getMessage()
),
E_USER_ERROR
);
}
return $returnValue;
}
// Create a new empty object in Fedora Commons and return its pid
private function createNewEmptyObject($prefix, $id) {
$returnValue = false;
// Build URL
$protocol = variable_get("fedora_protocol"); // 'http'
$host = variable_get("fedora_host");
$port = variable_get("fedora_port"); // '8082'
$context = variable_get("fedora_context"); // 'fedora'
$pid = $prefix . ":" . $id;
$url = sprintf(
"%s://%s:%d/%s/objects/%s",
$protocol,
$host,
$port,
$context,
$pid
);
// Build cURL options
$userPassword = variable_get("fedora_username") . ":" . variable_get("fedora_password"); // username:password
$verifyPeer = false; // false for ignoring self signed certificates
$headers = array("Accept: text/xml", "Content-Type: text/xml");
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userPassword,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_SSL_VERIFYPEER => $verifyPeer,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true
);
// Try `cURL`ing
$result = $this->curlThis($curlOptions, 201);
if ($result === $pid) {
$returnValue = $result;
}
return $returnValue;
}
private function attachDatastream ($pid, $file, $datastreamID) {
$returnValue = false;
// Build URL
$protocol = variable_get("fedora_protocol"); // "http"
$host = variable_get("fedora_host");
$port = variable_get("fedora_port"); // 8082
$context = variable_get("fedora_context"); // fedora
$url = sprintf(
"%s://%s:%d/%s/objects/%s/datastreams/%s?controlGroup=M", // M stands for 'Managed Content'
$protocol,
$host,
$port,
$context,
$pid,
$datastreamID
);
// Build cURL options
$userPassword = variable_get("fedora_username") . ":" . variable_get("fedora_password"); // username:password
$verifyPeer = false; // false for ignoring self signed certificates
$headers = array("Accept: text/xml", "Content-Type: " . $file->filemime);
$fileContents = file_get_contents("sites/default/files/images/" . $file->filename);
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userPassword,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_SSL_VERIFYPEER => $verifyPeer,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fileContents
);
// Try `cURL`ing
$result = $this->curlThis($curlOptions, 201);
if ($result === $pid) {
$returnValue = $result;
}
return $returnValue;
}
public function ingest($namespace, $identifier, $file) {
$pid = $this->createNewEmptyObject($namespace, $identifier);
if ($pid) {
$result = $this->attachDatastream($pid, $file, "IMAGE");
if ($result) {
error_log("Successfully ingested a file!");
} else {
error_log("FAILED ATTACHING DATASTREAM TO NEW OBJECT");
}
} else {
error_log("FAILED CREATING NEW EMPTY OBJECT");
}
}
}
$fedora = new Fedora();
/*
* $file is an object obtained by uploading a file into a drupal file system (at /drupal/sites/default/files/images/singe.jpg). It has the following attributes:
* $file->filemime === "image/jpeg"
* $file->filename === "singe.jpg"
*/
$fedora->ingest('namespace', 'identifier', $file);
?>

php curl multi init HTTP 401 Unauthorized

I have used a curl single init to issue an HTTP Get and all worked fine.
Now I tried to use a multi init (as I need to get multiple URLs) and I get a 401 message with "This request requires HTTP authentication" on the response to the Get.
Same Curl options where used on both cases.
Here is the code for th multi init and below it the single init function.
protected function _multiQueryRunkeeper($uri, $subscribersInfo,$acceptHeader) {
$curlOptions = array(
CURLOPT_URL => 'https://api.runkeeper.com' . $uri,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_HTTPGET => true
);
$curl_array = array();
$mh = curl_multi_init();
foreach ($subscribersInfo as $i => $subscriber) {
$curl_array[$i] = curl_init();
curl_setopt_array($curl_array[$i],$curlOptions);
curl_setopt($curl_array[$i], CURLOPT_HEADER,
array('Authorization: Bearer '.$subscriber['token'],
'Accept: application/vnd.com.runkeeper.' . $acceptHeader));
curl_multi_add_handle($mh,$curl_array[$i]);
}
$running = NULL;
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while($running > 0);
$subscribersWorkoutFeed = array();
foreach($subscribersInfo as $i => $subscriber)
{
$subscribersWorkoutFeed[$i] = curl_multi_getcontent($curl_array[$i]);
curl_multi_remove_handle($mh, $curl_array[$i]);
}
curl_multi_close($mh);
return $subscribersWorkoutFeed;
}
protected function _singleQueryRunkeeper($uri, $subscriberToken,$acceptHeader) {
try{
// get fitness user's fitness activities from Runkeeper
$this->_curl = isset($this->_curl)? $this->_curl : curl_init();
$curlOptions = array(
CURLOPT_URL => 'https://api.runkeeper.com' . $uri,
CURLOPT_HTTPHEADER => array('Authorization: Bearer '.$subscriberToken,
'Accept: application/vnd.com.runkeeper.' . $acceptHeader),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPGET => true
);
curl_setopt_array($this->_curl,$curlOptions);
$response = curl_exec($this->_curl);
if($response == false) {
if (Zend_Registry::isRegistered('logger')) {
$logger = Zend_Registry::get('logger');
$logger->log('Curl error on _singleQueryRunkeeper: '
. curl_error($this->_curl), Zend_Log::INFO);
}
return null;
}
$data = Zend_Json::decode($response);
return($data);
} catch(Exception $e){
if (Zend_Registry::isRegistered('logger')) {
$logger = Zend_Registry::get('logger');
$logger->log('exception occured on getUsersLatestWorkoutsFromRK. Curl error'
. curl_error($this->_curl), Zend_Log::INFO);
}
}
}

Categories