I am trying to check when users log into my dashboard if they have a connected Dropbox account. I can do this fine, but, I also want to check if the App folder exists in the Dropbox, otherwise users can start uploading files and fail because the path doesn't exist because there is no root. I'd rather catch this at the start then during the upload process.
I was trying to use findErrorNonRoot but the obviously doesn't accept the root.
$pathError = dbx\Path::findErrorNonRoot($dropboxPath);
I also tried isValid
$pathError = dbx\Path::isValid("/");
In case if the user has removed their "App" folder, Dropbox API throws Dropbox\Exception_InvalidAccessToken exception. So you should only handle this exception properly. For example:
use \Dropbox as dbx;
define ('API_CONF_FILE', '/path/to/api-conf.json');
define ('CLIENT_ID', 'Your Upload App/1.0');
$accessToken = obtain_the_access_token();
$appInfo = dbx\AppInfo::loadFromJsonFile(API_CONF_FILE);
for (;;) {
echo "Connecting to Dropbox...\n";
$dbxClient = new dbx\Client($accessToken, CLIENT_ID);
try {
// This call will also throw `Dropbox\Exception_InvalidAccessToken`
//$folderMetadata = $dbxClient->getMetadataWithChildren("/");
$f = fopen("/path/to/test.txt", "r");
$result = $dbxClient->uploadFile("/test.txt", dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);
break;
} catch (Dropbox\Exception_InvalidAccessToken $e) {
$message = $e->getMessage();
if ($brace_pos = strpos($message, '{')) {
$error_title = substr($message, 0, $brace_pos);
if ($json_error = json_decode(substr($message, $brace_pos), true)) {
$error_description = $json_error['error'] ?? 'N/A';
}
fprintf(STDERR, "Error: %s\nDescription: %s\n",
$error_title, $error_description ?? 'N/A');
$webAuth = new dbx\WebAuthNoRedirect($appInfo, CLIENT_ID);
$authorizeUrl = $webAuth->start();
echo "1. Go to: $authorizeUrl\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = \trim(\readline("Enter the authorization code here: "));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
echo "Access Token: $accessToken\n";
}
} catch (Exception $e) {
fprintf(STDERR, "Unknown exception: %s\n", $e->getMessage());
exit(1);
}
}
Note, I've used PHP7 Null coalescing operator.
Sample output (when the folder is initially removed)
Connecting to Dropbox...
Error: HTTP status 401
Description: User has removed their App folder.
1. Go to: https://www.dropbox.com/1/oauth2/authorize?locale=&client_id=2deadbeef2ofaft&response_type=code
2. Click "Allow" (you might have to log in first).
3. Copy the authorization code.
Enter the authorization code here: IugIByIMdKkAAAAAAAAAhVTH02dF7LW70_fFEHHohXo
Access Token: IugIByIMdKkAAAAAAAAAhtPGKSoVOBs557XXrq-zX57L4QRAmqiUTagktS7YDmg1
Connecting to Dropbox...
Array
(
[revision] => 1
[bytes] => 10
[thumb_exists] =>
[rev] => 14ef8952b
[modified] => Tue, 04 Oct 2016 09:02:31 +0000
[mime_type] => text/plain
[path] => /working-draft.txt
[is_dir] =>
[size] => 10 bytes
[root] => app_folder
[id] => id:rmvcpq3LHlAAAAAAAAAAAw
[client_mtime] => Tue, 04 Oct 2016 09:02:31 +0000
[icon] => page_white_text
)
Sample output (when the folder initially exists)
Connecting to Dropbox...
Array
(
[revision] => 2
[bytes] => 10
[thumb_exists] =>
[rev] => 24ef8b68e
[modified] => Tue, 04 Oct 2016 09:18:20 +0000
[mime_type] => text/plain
[path] => /test.txt
[is_dir] =>
[size] => 10 bytes
[root] => app_folder
[id] => id:VMaySA3Ug5AAAAAAAAAABA
[client_mtime] => Tue, 04 Oct 2016 09:18:20 +0000
[icon] => page_white_text
)
The root App folder is created when the user follows the link and clicks on "Allow" button.
Related
I'm trying to check if url is image, so I did use getheader; the getheader is working on localhost but not working on hosting server. I also tried to use getimagesize also it's working on localhost but not working on web hosting server even my php.ini is set to
allow_url_fopen = On
allow_url_include = On
for get_header my code is
$url = "https://hgtvhome.sndimg.com/content/dam/images/hgtv/fullset/2016/2/16/2/Orig-Paul-Schultz_Toybox-Home-kitchen-1.jpg.rend.hgtvcom.616.411.suffix/1455654217545";
$url_headers=get_headers($url, 1);
if(isset($url_headers['Content-Type'])){
$type=strtolower($url_headers['Content-Type']);
$valid_image_type=array();
$valid_image_type['image/png']='';
$valid_image_type['image/jpg']='';
$valid_image_type['image/jpeg']='';
$valid_image_type['image/jpe']='';
$valid_image_type['image/gif']='';
$valid_image_type['image/tif']='';
$valid_image_type['image/tiff']='';
$valid_image_type['image/svg']='';
$valid_image_type['image/ico']='';
$valid_image_type['image/icon']='';
$valid_image_type['image/x-icon']='';
if(isset($valid_image_type[$type])){
echo "Yes it's Images";
}
else
{
echo "no image";
}
}
var_dump of getheader on localhost display
array (size=11)
0 => string 'HTTP/1.0 200 OK' (length=15)
'Content-Type' => string 'image/jpeg' (length=10)
'Server' => string 'Apache' (length=6)
'X-Content-Type-Options' => string 'nosniff' (length=7)
'X-Frame-Options' => string 'SAMEORIGIN' (length=10)
'Content-Length' => string '38885' (length=5)
'Cache-Control' => string 'max-age=2522004' (length=15)
'Expires' => string 'Fri, 03 May 2019 08:55:29 GMT' (length=29)
'Date' => string 'Thu, 04 Apr 2019 04:22:05 GMT' (length=29)
'Connection' => string 'close' (length=5)
'Vary' => string 'User-Agent' (length=10)
But var_dump on web hosting server display
Array
(
[server] => AkamaiGHost, Apache
[content-length] => 0, 2077
[location] => https://www.foodnetwork.com/not-available.html
[cache-control] => max-age=0, max-age=433
[expires] => Thu, 04 Apr 2019 05:16:02 GMT, Thu, 04 Apr 2019 05:23:15 GMT
[date] => Thu, 04 Apr 2019 05:16:02 GMT, Thu, 04 Apr 2019 05:16:02 GMT
[connection] => keep-alive, keep-alive
[vary] => User-Agent, User-Agent, Accept-Encoding
[content-type] => text/html; charset=UTF-8
[access-control-allow-method] => GET
[server-timing] => edge; dur=0, cdn-cache; desc=HIT
[x-akamai-transformed] => 9 - 0 pmb=mRUM,3
[access-control-allow-origin] => *
[content-encoding] => gzip
)
and for getimagesize my code is
if (#getimagesize($url)) {
echo "image exists ";
} else {
echo "image does not exist ";
}
also is working on localhost but not working on web host server the var_dump of #getimagesize($url) is displaying :
bool(false)
As per you comment, You image url is wrong. Is should be : https://hgtvhome.sndimg.com/content/dam/images/hgtv/fullset/2016/2/16/2/Orig-Paul-Schultz_Toybox-Home-kitchen-1.jpg
You should remove image caching and image versioning at the time of checking.
Best solution to check weather file is image or not
Solution 1
if(#is_array(getimagesize($mediapath))){
$image = true;
} else {
$image = false;
}
Solution 2
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
Solution 3
$supported_image = array('gif','jpg','jpeg','png','bmp');
$src_file_name = 'https://hgtvhome.sndimg.com/content/dam/images/hgtv/fullset/2016/2/16/2/Orig-Paul-Schultz_Toybox-Home-kitchen-1.jpg';
$ext = strtolower(pathinfo($src_file_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_image)){
echo "it's image";
}
else {
echo 'not image';
}
You should follow redirect headers (codes 30x)
In this case the image seems 'not available' because the redirect is to a not available page, it seems. Maybe the URL is wrong?
What you should also watch out for: many content providers check at least for a HTTP referrer header or they deny access to images (to make crawling a bit harder). Others check for a previously set cookie. And finally some can use some complex token-based authentication (which I will not get into). But for the first issues and also following redirects, you should use Curl: https://www.php.net/manual/en/book.curl.php
Content-type headers are very often unreliable. I would recommend using the exif image type returned by getimagesize in result index 2, which you seem to be calling anyway.
So to recap: use Curl to set referrer and follow redirects and maybe propagate cookies from a previous referrer page that you might browse, and once you get the content use getimagesize to determine type.
#getimagesize function take much time to respond. use below code for quick respond
function image_urlexists($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($code == 200); // verifica se recebe "status OK"
}
$url = 'https://www.example.com/static/cs/img/pages/home/security-card-xl.png';
if (image_urlexists($url))
echo "valid Url of image";
else
echo "Not valid url image";
I am getting 502 Bad Gateway error when I try to send email using Sendgrid's PHP library. I have attached the error log below,
502 Array (
[0] => HTTP/1.1 502 Bad Gateway
[1] => Server: nginx
[2] => Date: Thu, 27 Dec 2018 19:30:14 GMT
[3] => Content-Type: text/html
[4] => Content-Length: 166
[5] => Connection: keep-alive
[6] => Access-Control-Allow-Origin: https://sendgrid.api-docs.io
[7] => Access-Control-Allow-Methods: POST
[8] => Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
[9] => Access-Control-Max-Age: 600
[10] => X-No-CORS-Reason:
https://sendgrid.com/docs/Classroom/Basics/API/cors.html
[11] =>
[12] => )
I don't know where I am wrong and I followed as per the documentation in SendGrid's website (Github as well). I have attached the code below what I used.
I have already tried possible troubleshooting found in other questions and issues in the GitHub repository of sendgrid-php.
<?php
require("sendgrid/sendgrid-php.php");
$email = new \SendGrid\Mail\Mail();
$email->setFrom("noreply#mydomain.com", "Leads");
$email->setSubject($_POST['school'] . " - Appointment");
$tos = [
"support#mydomain.com" => "Support",
$_POST['email'] => $_POST['name']
];
$email->addTos($tos);
$email->addContent("text/html", "<p><strong>Name:</strong> {$_POST['name']}</p>");
$email->addContent("text/html", "<p><strong>Email:</strong> {$_POST['email']}</p>");
$email->addContent("text/html", "<p><strong>Mobile:</strong> {$_POST['mobile']}</p>");
$email->addContent("text/html", "<p><strong>School:</strong> {$_POST['school']}</p>");
$email->addContent("text/html", "<p><strong>Count:</strong> {$_POST['count']}</p>");
$email->addContent("text/html", "<p><strong>Gender:</strong> {$_POST['gender']}</p>");
$sendgrid = new \SendGrid('xxxxxxxxxxxxxxAPIKEYxxxxxxxxxxxxxxxx');
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
?>
The email should be sent when the code is executed.
There is some weird issue with SendGrid. Sometimes, the API gets soft deleted automatically in the backend. To make the code work, I had to create a new API key and retry. And the solution worked.
Note - Some issues in GitHub instructed to initialize a constructor with a from address, but that was not the actual issue.
The workaround is to create a new API key in the dashboard till
SendGrid investigates why the API is soft deleted so that the API call
returns an error.
I'm attempting to authenticate a user through Vimeo in order to view a list of their videos on the website.
I'm using the Vimeo php library https://github.com/vimeo/vimeo.php with no errors when including it in my code.
I get the authentication URL and am able to navigate to the Allow APP Access page on Vimeo and when I click "Allow" I'm getting the "invalid_client" error on my redirect page, even though they send back a code in the $_GET.
I'm thoroughly confused at this point since I've got the official API library and the APP is set up correctly as far as I can tell. I'm hoping someone might be able to point me in the right direction as to why I'm getting this error and how to fix it!
My Code:
//init Vimeo
require_once("modules/classes/Vimeo/autoload.php");
$lib = new \Vimeo\Vimeo($vimeo_id, $vimeo_secret, $vimeo_access);
if(!isset($_SESSION['vstate'])){
$_SESSION['vstate'] = base64_encode(openssl_random_pseudo_bytes(30));
}
$vimeo_authurl = $lib->buildAuthorizationEndpoint($redirecturi,'public private',$_SESSION['vstate']);
if(isset($_GET['code'])){
echo "Code returned: ".$_GET['code'];
if ($_SESSION['vstate'] != $_GET['state']) {
echo 'Something is wrong. Vimeo sent back a different state than this script was expecting. Please let an administrator know that this has happened.';
}
$tokens = $lib->accessToken($_GET['code'], $redirecturi);
if ($tokens['status'] == 200) {
echo 'Vimeo account successfully connected!';
$_SESSION['access_token'] = $tokens['body']['access_token'];
$lib->setToken($token['body']['access_token']);
} else {
echo 'Sorry, we were unable to connect to your Vimeo account due to the following error:<br/>{'.$tokens['body']['error']."} ".$tokens['body']['error_description'];
}
echo "<br/><br/><pre>";
print_r($tokens);
echo "</pre>";
exit();
}
The print_r($tokens) gives this:
Array
(
[body] => Array
(
[error] => invalid_client
[error_description] => A valid client ID must be provided along with any request made to Vimeo's API
)
[status] => 400
[headers] => Array
(
[Server] => nginx
[Content-Type] => application/json
[Expires] => Fri, 10 Mar 2017 03:11:17 GMT
[Cache-Control] => no-store
[Strict-Transport-Security] => max-age=15552000; includeSubDomains; preload
[Pragma] => no-cache
[X-UA-Compatible] => IE=edge
[X-XSS-Protection] => 1; mode=block
[X-Content-Type-Options] => nosniff
[X-Frame-Options] => sameorigin
[Content-Security-Policy-Report-Only] => default-src https: data: blob: 'unsafe-inline' 'unsafe-eval'; report-uri /_csp
[Accept-Ranges] => bytes
[Via] => 1.1 varnish
[Fastly-Debug-Digest] => 5da2a3ac863afd5f2ad0963779e0dbc4c54c7d97d19f87fd227c5eb8c92bd621
[Content-Length] => 126
[Date] => Fri, 10 Mar 2017 15:11:17 GMT
[Connection] => keep-alive
[X-Served-By] => cache-iad2146-IAD, cache-ord1731-ORD
[X-Cache] => MISS, MISS
[X-Cache-Hits] => 0, 0
[X-Timer] => S1489158677.346607,VS0,VE55
[Vary] => Accept,Vimeo-Client-Id,Accept-Encoding,User-Agent
)
)
So I'm not exactly sure why, but I created a new APP with the same details and this new APP seemed to authenticate fine.
The first APP I was having troubles with I had originally sent a request for Upload Access, but was denied (due to local testing links), so perhaps that was the underlying issue with the "invalid_client" error.
I am trying to create a page that will display the contents of a dropbox folder, in a presentable sandbox fashion, and allow the browsing user (who is logged into a website I have been developing) to be able to click and download the various files within the folders.
Here is the code I'm using:
This is the file bootstrap.php...
<?php
// Prevent calling this script directly
if ($_SERVER["SCRIPT_FILENAME"] == __FILE__) {
exit("Access denied!");
}
// app settings
$config = array();
$config["dropbox"]["app_key"] = "***";
$config["dropbox"]["app_secret"] = "***";
// ACCESS_TYPE should be "dropbox" or "app_folder"
$config["dropbox"]["access_type"] = "dropbox";
$config["app"]["root"] = ((!empty($_SERVER["HTTPS"])) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . "/";
$config["app"]["datadir"] = dirname(__FILE__) . "/data";
$config["app"]["authfile"] = $config["app"]["datadir"] . "/auth.php";
// turn on error reporting for development
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", true);
// environment check
if (!is_dir($config["app"]["datadir"]) || !is_writable($config["app"]["datadir"])) {
exit("The data directory is not writeable!");
}
if (file_exists($config["app"]["authfile"]) && !is_writable($config["app"]["authfile"])) {
exit("The auth storage file is not writeable!");
}
// Load libraries and start a new session
require_once "lib/dropbox/rest.php";
require_once "lib/dropbox/session.php";
require_once "lib/dropbox/client.php";
if(!isset($_SESSION)){session_start();}
// Search for a previously obtained access token
$access_token = null;
if (file_exists($config["app"]["authfile"])) {
include_once $config["app"]["authfile"];
}
This is the file authorize.php...
<?php
require_once "bootstrap.php";
if (isset($access_token)) {
header("Location: ./");
exit;
}
try {
// Start a new Dropbox session
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"]
);
// The user is redirected here by Dropbox after the authorization screen
if (!empty($_GET["oauth_token"]) && !empty($_GET["uid"])) {
$uid = $_GET["uid"];
$token = array(
"oauth_token" => $_GET["oauth_token"],
"oauth_token_secret" => ""
);
if (!empty($_SESSION["request_token"])) {
$token["oauth_token_secret"] = $_SESSION["request_token"]["oauth_token_secret"];
}
/**
* The access token is all you'll need for all future API requests on
* behalf of this user, so you should store it away for safe-keeping
* (even though we don't for this article). By storing the access
* token, you won't need to go through the authorization process again
* unless the user revokes access via the Dropbox website.
*/
if ($access_token = $session->obtainAccessToken($token)) {
parse_str($access_token, $token);
$access_token = $token;
unset($token);
// The output ov var_export is similar to:
// array("oauth_token_secret" => "aaaa", "oauth_token" => "bbbb", "uid" => "123456")
$data = '<?php $access_token = ' . var_export($access_token, true) . ";";
if (file_put_contents($config["app"]["authfile"], $data) === false) {
throw new Exception("Unable save access token");
}
// Authorized, redirect to index
//header("Location: index_inside.php");
echo "Authorized, click here to redirect!";
exit;
}
// The access token should be stored somewhere to be reused until
// it expires or is revoked by the user
}
else {
// We must start a new authorization cycle
if ($request_token = $session->obtainRequestToken()) {
// The request token must be subdivided in the two components
// oauth_token_secret and oauth_token and kept in the session
// because is needed in the next step
parse_str($request_token, $token);
$_SESSION["request_token"] = $token;
$url = $session->buildAuthorizeURL(
$token,
$config["app"]["root"] . basename($_SERVER["SCRIPT_NAME"]),
"en-US");
// Display or redirect to auth URL
echo '<p>Please visit Dropbox and authorize this application.</p>';
exit;
}
else {
throw new Exception("Unable to get request token");
}
}
}
catch (Exception $e) {
echo $e->getMessage();
}
This is the file list_inside.php...which is what is eventually included to present the list of folders (and ideally files with download links)...
<?php
require_once "bootstrap.php";
if (!isset($access_token)) {
header("Location: authorize.php");
exit;
}
try {
// Start a new Dropbox session
// The access token should be defined
// The session should verify if the token is valid and throw an exception
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"],
$access_token
);
$client = new DropboxClient($session);
$path = (!empty($_GET["path"])) ? $_GET["path"] : "/Apps/Tools/";
// List contents of home directory
if ($home = $client->metadata($path)) {
echo "<p>Metadata content for <code>" . $path . "</code></p>";
echo "<pre>" . print_r($home, true) . "</pre>";
}
}
catch (Exception $e) {
echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
if ($e->getCode() == 401) {
// Remove auth file
unlink($config["app"]["authfile"]);
// Re auth
echo '<p>Click Here to re-authenticate</p>';
}
}
Here is the output on the above code using metadata() :
Metadata content for /Apps/Tools/ Array (
[hash] => fa7f3577894553ffeb70ac0d96e49b99
[revision] => 71425
[rev] => 1170104ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools
[is_dir] => 1
[icon] => folder
[root] => dropbox
[contents] => Array
(
[0] => Array
(
[revision] => 71426
[rev] => 1170204ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Dry Creek Valley Cabernet Sauvignon
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
[1] => Array
(
[revision] => 71436
[rev] => 1170c04ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Dry Creek Valley Sauvignon Blanc
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
[2] => Array
(
[revision] => 71445
[rev] => 1171504ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Mendocino County Zinfandel
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
[3] => Array
(
[revision] => 71454
[rev] => 1171e04ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Pinot Noir California
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
)
[size] => 0 bytes )
I apologize for the choppy code, I am not extremely skilled at this, however, my friend needs help with the site, and I jumped in to help get dropbox working.
The problem is...It displays an array of information about the folders, but no files are visible with links for downloading.
Added info..here is another page code i try: (i list output for this directly below the php)
<?php
require_once "bootstrap.php";
if (!isset($access_token)) {
header("Location: authorize.php");
exit;
}
try {
// Start a new Dropbox session
// The access token should exist
// The session should verify if the token is valid and throw an exception
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"],
$access_token
);
$client = new DropboxClient($session);
$path = (!empty($_GET["path"])) ? $_GET["path"] : "/webs.pdf";
$dest = $config["app"]["datadir"] . "/" . basename($path);
// Download a file
if ($file = $client->getFile($path, $dest)) {
if (!empty($dest)) {
unset($file["data"]);
echo "<p>File saved to: <code>" . $dest . "</code></p>";
echo "<pre>" . print_r($file, true) . "</pre>";
}
else {
header("Content-type: " . $file["mime"]);
echo $file["data"];
exit;
}
}
}
catch (Exception $e) {
echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
if ($e->getCode() == 401) {
// Remove auth file
unlink($config["app"]["authfile"]);
// Re auth
echo '<p>Click Here to re-authenticate</p>';
}
}
Here is the output for the above code:
File saved to: /home/thisisyo/public_html/data/webs.pdf Array (
[name] => /home/thisisyo/public_html/data/webs.pdf
[mime] => application/pdf
[meta] => stdClass Object
(
[revision] => 35075
[rev] => 890304ef29f8
[thumb_exists] =>
[bytes] => 703289
[modified] => Thu, 20 Jun 2013 23:39:10 +0000
[client_mtime] => Wed, 20 Feb 2013 19:19:42 +0000
[path] => /webs.pdf
[is_dir] =>
[icon] => page_white_acrobat
[root] => dropbox
[mime_type] => application/pdf
[size] => 686.8 KB
)
)
Also, here is the class defined in client.php:
public function metadata($path, $list = true, $fileLimit = 10000, $hash = null, $revision = null, $includeDeleted = false) {
// Prepare argument list
$args = array(
"file_limit" => $fileLimit,
"hash" => $hash,
"list" => (int) $list,
"include_deleted" => (int) $includeDeleted,
"rev" => $revision
);
// Prepend the right access string to the desired path
if ("dropbox" == $this->accessType) {
$path = "dropbox" . $path;
}
else {
$path = "sandbox" . $path;
}
// Execute
$response = $this->Session->fetch("GET", $this->dropboxAPIURL, "/metadata/" . $path, $args);
return $response["body"];
}
This is the getFile() class define...
public function getFile($path, $outFile = null, $revision = null) {
$args = array();
if (!empty($revision)) {
$args["rev"] = $revision;
}
// Prepend the right access string to the desired path
if ("dropbox" == $this->accessType) {
$path = "dropbox" . $path;
}
else {
$path = "sandbox" . $path;
}
// Get the raw response body
$response = $this->Session->fetch("GET", $this->dropboxContentAPIURL, "/files/" . $path, $args, true);
if ($outFile != null) {
if (file_put_contents($outFile, $response["body"]) === false) {
throw new Exception("Unable to write file '$outfile'");
}
}
return array(
"name" => ($outFile) ? $outFile : basename($path),
"mime" => $response["headers"]["content-type"],
"meta" => json_decode($response["headers"]["x-dropbox-metadata"]),
"data" => $response["body"]
);
}
For your list_inside.php page, all you need to do is loop through your $client->metadata() array and print the HTML. Here's a sample for that page:
<?php
require_once "bootstrap.php";
if (!isset($access_token)) {
header("Location: authorize.php");
exit;
}
try {
// Start a new Dropbox session
// The access token should be defined
// The session should verify if the token is valid and throw an exception
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"],
$access_token
);
$client = new DropboxClient($session);
$path = (!empty($_GET["path"])) ? $_GET["path"] : "/Apps/Tools/";
// List contents of home directory
if ($home = $client->metadata($path)) {
echo <<<EOF
<h1>Index of $index</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Last Modified</th>
<th>Size</th>
<th>Type</th>
</tr>
</thead>
<tbody>
EOF;
foreach($home as $list) {
$link = ($list[is_dir] == 1 ? "list_inside" : "download").".php?path=".$list[path];
$file = explode("/", $list[path]);
$path = $file[count($file)-1];
$size = ($list[bytes] == 0 ? "-" : $list[size]);
echo <<<EOF
<tr>
<td>$path</td>
<td>$list[modified]</td>
<td>$size</td>
<td>$list[type]</td>
</tr>
EOF;
}
echo <<<EOF
</tbody>
</table>
EOF;
}
} catch (Exception $e) {
echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
if ($e->getCode() == 401) {
// Remove auth file
unlink($config["app"]["authfile"]);
// Re auth
echo '<p>Click Here to re-authenticate</p>';
}
}
?>
you just need to call a function to download the file .
require_once 'dropbox/DropboxClient.php';
$dropbox = new DropboxClient(array(
'app_key' => DROPBX_API_KEY,
'app_secret' => DROPBX_API_SECRET,
'app_full_access' => TRUE,
),'en');
$fileMetadata = $dropbox->DownloadFile($value->path,'download/'.$file);
check this if it can help you
The specific 401 error message I get is:
"error":"invalid_client","error_description":"The client credentials are invalid"}"
This error isn't listed anywhere in the PayPal documentation. I am certain I am using the test credentials and using the correct sandbox endpoint. The error occurs when I attempt to get an access token.
This is the class where the access token is retrieved:
private function _generateAccessToken($config) {
$base64ClientID = base64_encode($this->clientId . ":" . $this->clientSecret);
$headers = array(
"User-Agent" => PPUserAgent::getValue(RestHandler::$sdkName, RestHandler::$sdkVersion),
"Authorization" => "Basic " . $base64ClientID,
"Accept" => "*/*"
);
$httpConfiguration = $this->getOAuthHttpConfiguration($config);
$httpConfiguration->setHeaders($headers);
$connection = PPConnectionManager::getInstance()->getConnection($httpConfiguration, $config);
//print_r($connection); die;
$res = $connection->execute("grant_type=client_credentials");
$jsonResponse = json_decode($res, true);
if($jsonResponse == NULL ||
!isset($jsonResponse["access_token"]) || !isset($jsonResponse["expires_in"]) ) {
$this->accessToken = NULL;
$this->tokenExpiresIn = NULL;
$this->logger->warning("Could not generate new Access token. Invalid response from server: " . $jsonResponse);
} else {
$this->accessToken = $jsonResponse["access_token"];
$this->tokenExpiresIn = $jsonResponse["expires_in"];
}
$this->tokenCreateTime = time();
return $this->accessToken;
}
This is the $connection variable I have when I print_r (I removed the authorization string):
PayPal\Core\PPHttpConnection Object( [httpConfig:PayPal\Core\PPHttpConnection:private] => PayPal\Core\PPHttpConfig Object ( [headers:PayPal\Core\PPHttpConfig:private] => Array ( [User- Agent] => PayPalSDK/rest-sdk-php 0.6.0 (lang=PHP;v=5.4.21;bit=64;os=Linux_2.6.18- 308.16.1.el5;machine=x86_64;openssl=0.9.8e-fips-rhel5;curl=7.24.0) [Authorization] => Basic REMOVED AUTHORIZATION STRING == [Accept] => */* ) [curlOptions:PayPal\Core\PPHttpConfig:private] => Array ( [32] => 3 [78] => 30 [19913] => 1 [13] => 60 [10018] => PayPal-PHP-SDK [10023] => Array ( ) [81] => 2 [64] => 1 ) [url:PayPal\Core\PPHttpConfig:private] => https://api.sandbox.paypal.com/v1/oauth2/token [method:PayPal\Core\PPHttpConfig:private] => POST [retryCount:PayPal\Core\PPHttpConfig:private] => 1 ) [logger:PayPal\Core\PPHttpConnection:private] => PayPal\Core\PPLoggingManager Object ( [loggerName:PayPal\Core\PPLoggingManager:private] => PayPal\Core\PPHttpConnection [isLoggingEnabled:PayPal\Core\PPLoggingManager:private] => 1 [loggingLevel:PayPal\Core\PPLoggingManager:private] => 3 [loggerFile:PayPal\Core\PPLoggingManager:private] => PayPal.log ))
As far I can tell, I have correct credentials, correct endpoint, not sure what else it could be?
A HTTP401 on /token is returned if the client_id/secret aren’t recognized (either the wrong credentials for the environment, or the credentials aren’t active).
Can you run a test via cURL to rule out any environment / code-specific issues?
curl -v -u "client_id:secret" "https://api.sandbox.paypal.com/v1/oauth2/token" -X POST -d "response_type=token&grant_type=client_credentials"
(Replace client_id and secret above with your own)
Make sure payment $config mode is Sandbox and clientId and clientSecret keys are Sandbox same time.