从dropbox注销时请求在api中重新进行身份验证

时间:2014-08-22 07:03:18

标签: php dropbox-api dropbox-php

我使用dropbox提供的php sdk来获取用户的图片。 一切都很好。当用户访问我的网站并点击保管箱按钮时,它首先要求进行身份验证,然后导入用户的图像。由于此过程,用户也会自动登录dropbox.com。这是预期的行为。

但是在完成所有这个过程后,如果用户从dropbox.com注销,然后再次点击我网站上的保管箱按钮,我相信我的应用程序会要求进行身份验证,但它不会要求身份验证但会提供图像来自用户保管箱帐户。

请询问更多细节如果我不清楚。

提前谢谢。

修改

的index.php

<?php 
/***********************************************************************
 * Plugin Name: Dropbox Plugin
 * Plugin URI: http://www.picpixa.com/
 * Version: 1.0
 * Author: Ashish Shah
 * Description: Plugin To Import Images From User's Dropbox Account
 **********************************************************************/

session_start();
include_once '/home/picpixa/wp-config.php';
//ini_set("display_errors",1);
?>

<!-- Bootstrap -->
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>

<style>
    .loader {
        position: fixed;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        z-index: 9999;
        background: url('https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
    }
</style>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(window).load(function() {
        $(".loader").fadeOut("slow");
    });

    //creating dynamic back button 
    //var docRef = document.referrer;
    //$('#backBtn').html('<a href="' + docRef + '">Go Back</a>');
    //alert('<a href="' + docRef + '">Go Back</a>');

    /* Not in use
    //This function will call on the click event of <div class='row'>
    function loadBackBtn()
    {
        $('#backBtn').html('<a class="btn btn-primary" href="' + document.referrer + '">Back</a>');
    } 
    //document.write('<a class='btn btn-primary' href="' + document.referrer + '">Back</a>');*/
</script>
<script>
    function loader(){
        $('#load').show();
    }
    /*function loadExistingImages(){
        window.opener.$('#loader_img').show();
        result=null;
        window.opener.$('#fileupload').each(function () {
            var that = this;
            window.opener.$.getJSON(this.action, function (result) {
                if (result && result.length) {
                    window.opener.$(that).fileupload('option', 'done')
                        .call(that, null, {result: result});
                    //console.log('ss='+$('.table-striped tbody').find('.btn-danger').length);
                    if(window.opener.$('.table-striped .files').find('.btn-danger').length>0){
                        window.opener.$('.coo-images-other-buttons').show();
                    }else{
                        window.opener.$('.coo-images-other-buttons').hide();
                    }
                }
                window.opener.$('#loader_img').hide();

                if (window.opener.$('.table-striped.files').children().length > 0)
                {
                    window.opener.$('.table_tagline').show();
                }
            });
        });
    }*/
</script>

<!-- Adding this block to allow to see the login page like other social media -->
<!-- Login Block Start -->
<?php /*
    if(isset($_SESSION['comingFirstTime']) && $_SESSION['comingFirstTime']==true)
    {
?>
        <div id="load" class="loader"></div>
        <div id="wrap">
            <div class="header">
                <h4>Dropbox</h4>
            </div>
            <div class="cl"></div>
            <div id="middal_part">
                <div class="left_side">
                    <img src="Images/dropbox.jpg"/>
                </div>
                <div class="right_side">
                    <a class='btn btn-primary' href="<?php echo $loginUrl ?>" onclick="loader()">Login</a><br><br>
                    <button class="btn btn-primary close_window" type="button"  onClick="window.close();">Close</button>
                </div>
                <div class="cl"></div>
            </div>
        </div>
<?php
        $_SESSION['comingFirstTime'] = false;
        die;
    }*/
?>
<!-- Login Block End -->

<script type="text/javascript">$('#load').hide();</script>

<?php

if(isset($_POST['copy']) && $_POST['dropbox'])
{
    $imgArray = $_POST['dropbox'];

    $current_user = wp_get_current_user();

    if(isset($current_user->ID) && trim($current_user->ID)!='' && trim($current_user->ID)!=0){
        $extraSessionStr = 'usr-'.md5($current_user->ID).'/';
        $user = $current_user->ID;
    }else{
        $sesstionId = session_id();
        $user = $sesstionId;
        $extraSessionStr = $sesstionId.'/';
    }

    foreach ($imgArray as $img)
    {
        //Getting a file name
        $imgInfo = pathinfo($img); //This will become an array with keys ('dirname','basename','extension','filename')

        $oriFileName=$imgInfo['filename'];//Getting a file name without extension
        $fileName = (string) $oriFileName.".".$imgInfo['extension'];//Creating a file name with extension

        //Check weather the file is exists or not rename the file if exists
        $i=1;
        if(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
            while(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
                $fileName = (string) $oriFileName."(".$i.").".$imgInfo['extension'];
                $i++;
            }
        }

        // Read file content
        $file_content = file_get_contents($img);
        file_put_contents('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName, $file_content);
        //file_put_contents('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName, $file_content);

        /* To create thumbnail */

        // Max vert or horiz resolution
        $maxsize=80;

        // create new Imagick object
        $image = new Imagick($img); //"input_image_filename_and_location"

        // Resizes to whichever is larger, width or height
        if($image->getImageHeight() <= $image->getImageWidth())
        {
            // Resize image using the lanczos resampling algorithm based on width
            $image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
        }
        else
        {
            // Resize image using the lanczos resampling algorithm based on height
            $image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
        }

        // Set to use jpeg compression
        $image->setImageCompression(Imagick::COMPRESSION_JPEG);
        // Set compression level (1 lowest quality, 100 highest quality)
        $image->setImageCompressionQuality(75);
        // Strip out unneeded meta data
        $image->stripImage();
        // Writes resultant image to output directory
        $image->writeImage('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName); //"output_image_filename_and_location"
        // Destroys Imagick object, freeing allocated resources in the process
        $image->destroy();
    }
    ?>
        <script type="text/javascript">

                window.opener.$('tbody.files').find('tr').remove();
                //loadExistingImages();
                    var myVar;
                    if (/(MSIE\ [0-9]{1})/i.test(navigator.userAgent)) {
                        window.opener.$(window.opener.loadExistingFiles());
                        myVar = setTimeout(function(){
                            window.opener.$('tbody.files').find('tr .preview a[title="<?php echo $fileName;?>"]').click();
                        },1000);
                    }
                    else{
                        window.opener.$.when(window.opener.loadExistingFiles()).done(function(){
                            myVar = setTimeout(function(){
                                window.opener.$('tbody.files').find('tr .preview a[title="<?php echo $fileName;?>"]').click();
                            },1000);
                        });
                    }

            </script>
    <?php
        echo "<h2>The selected images have been uploaded successfully.</h2>";
        //echo "<h3>Please click on \"Proceed With Uploaded Images\" button to Proceed OR ";
        //echo "Click on the \"Upload More Images\" Button to upload more images.</h3>";
    ?>
        <div class="modal-footer">
            <input type='button' name='continue' value='Upload More Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";'>
            <!-- <input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick="window.close();"> -->
        </div>
        <?php
            die();          
        }
        elseif (isset($_POST['copy']))
        {
            echo "<h2>You have not selected any image(s) to move.</h2><br><br>";
            //echo "<h3>Please click on \"Close\" button to Close the window OR ";
            //echo "Click on the \"Upload Images\" Button to upload images.</h3>";
        ?>
            <div class="modal-footer">
                <input type='button' name='continue' value='Upload Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";'>
                <!-- <input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick="window.close();"> -->
            </div>
        <?php
            die();
        }

require_once __DIR__.'/dropbox-sdk/Dropbox/strict.php';

$appInfoFile = __DIR__."/AppInfo.json";

// NOTE: You should be using Composer's global autoloader. But just so these examples
// work for people who don't have Composer, we'll use the library's "autoload.php".
require_once __DIR__.'/dropbox-sdk/Dropbox/autoload.php';

use \Dropbox as dbx;
$requestPath = init();

if ($requestPath === "/") {
    $dbxClient = getClient();

    if ($dbxClient === false) {

        $loginUrl = getPath("dropbox-auth-start");
        /*$loginPage = <<<login
            <div id="load" class="loader"></div>
            <div id="wrap">
                <div class="header">
                    <h4>Dropbox</h4>
                    <p>Display Your Photo Stream</p>
                </div>
                <div class="cl"></div>
                <div id="middal_part">
                    <div class="left_side">
                        <img src="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/dropbox.jpg"/>
                    </div>
                    <div class="right_side">
                        <a class='btn btn-primary' href="$loginUrl" onclick="loader()">Login</a>
                        <button class="btn btn-primary close_window" type="button"  onClick="window.close();">Close</button>
                    </div>
                    <div class="cl"></div>
                </div>
            </div>
login;*/
        $loginPage = <<<login
            <div id="load" class="loader"></div>
            <div id="wrap">
                <div class="header">
                    <h4>Dropbox</h4>
                    <p>Display Your Photo Stream</p>
                </div>
                <div class="cl"></div>
                <div id="middal_part">
                    <div class="left_side">
                        <img src="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/dropbox.jpg"/>
                    </div>
                    <div class="right_side">
                        <a class='btn btn-primary' href="$loginUrl" onclick="loader()">Login</a>
                    </div>
                    <div class="cl"></div>
                </div>
            </div>
login;
        echo $loginPage;

        //header("Location: ".getPath("dropbox-auth-start"));
        exit;
    }

    $path = "/";
    if (isset($_GET['path'])) $path = $_GET['path'];

    $entry = $dbxClient->getMetadataWithChildren($path);
    if ($entry['is_dir']) {
        echo renderFolder($entry);
    }
    else {
        echo renderFile($entry);
    }
}
else if ($requestPath == "/download") {
    $dbxClient = getClient();

    if ($dbxClient === false) {
        header("Location: ".getPath("dropbox-auth-start"));
        exit;
    }

    if (!isset($_GET['path'])) {
        header("Location: ".getPath(""));
        exit;
    }
    $path = $_GET['path'];

    $fd = tmpfile();
    $metadata = $dbxClient->getFile($path, $fd);

    header("Content-Type: $metadata[mime_type]");
    fseek($fd, 0);
    fpassthru($fd);
    fclose($fd);
}
else if ($requestPath === "/upload") {
    if (empty($_FILES['file']['name'])) {
        echo renderHtmlPage("Error", "Please choose a file to upload");
        exit;
    }

    if (!empty($_FILES['file']['error'])) {
        echo renderHtmlPage("Error", "Error ".$_FILES['file']['error']." uploading file. See <a href='http://php.net/manual/en/features.file-upload.errors.php'>the docs</a> for details");
        exit;
    }

    $dbxClient = getClient();

    $remoteDir = "/";
    if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];

    $remotePath = rtrim($remoteDir, "/")."/".$_FILES['file']['name'];

    $fp = fopen($_FILES['file']['tmp_name'], "rb");
    $result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
    fclose($fp);
    $str = print_r($result, TRUE);
    echo renderHtmlPage("Uploading File", "Result: <pre>$str</pre>");
}
else if ($requestPath === "/dropbox-auth-start") {
    $authorizeUrl = getWebAuth()->start();
    header("Location: $authorizeUrl");
}
else if ($requestPath === "/dropbox-auth-finish") {
    try {
        list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET);
        // We didn't pass in $urlState to finish, and we're assuming the session can't be
        // tampered with, so this should be null.
        assert($urlState === null);
    }
    catch (dbx\WebAuthException_BadRequest $ex) {
        respondWithError(400, "Bad Request");
        // Write full details to server error log.
        // IMPORTANT: Never show the $ex->getMessage() string to the user -- it could contain
        // sensitive information.
        error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
        exit;
    }
    catch (dbx\WebAuthException_BadState $ex) {
        // Auth session expired. Restart the auth process.
        header("Location: ".getPath("dropbox-auth-start"));
        exit;
    }
    catch (dbx\WebAuthException_Csrf $ex) {
        respondWithError(403, "Unauthorized", "CSRF mismatch");
        // Write full details to server error log.
        // IMPORTANT: Never show the $ex->getMessage() string to the user -- it contains
        // sensitive information that could be used to bypass the CSRF check.
        error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
        exit;
    }
    catch (dbx\WebAuthException_NotApproved $ex) {
        echo renderHtmlPage("Not Authorized?", "Why not?");
        exit;
    }
    catch (dbx\WebAuthException_Provider $ex) {
        error_log("/dropbox-auth-finish: unknown error: " . $ex->getMessage());
        respondWithError(500, "Internal Server Error");
        exit;
    }
    catch (dbx\Exception $ex) {
        error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
        respondWithError(500, "Internal Server Error");
        exit;
    }

    // NOTE: A real web app would store the access token in a database.
    $_SESSION['access-token'] = $accessToken;

    echo renderHtmlPage("Authorized!",
        "Authorization complete, <a href='".htmlspecialchars(getPath(""))."' onclick='loader()'>click here</a> to browse.");
}
else if ($requestPath === "/dropbox-auth-unlink") {
    // "Forget" the access token.
    unset($_SESSION['access-token']);
    //$_SESSION = array();

    /*echo renderHtmlPage("Logged Out",
        "<div class='modal-footer'>
            You have been logged out.<br>
            <input type='button' name='login' value='Login Again' class='btn btn-primary' onClick='location.href = \"https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/\";'>
            <input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick='window.close();'>
        </div>"
    );*/
    echo renderHtmlPage("Logged Out",
            "<div class='modal-footer'>
            You have been logged out.<br>
            <input type='button' name='login' value='Login Again' class='btn btn-primary' onClick='location.href = \"https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/\";'>
        </div>"
    );
}
else {
    echo renderHtmlPage("Bad URL", "No handler for $requestPath");
    exit;
}

function renderFolder($entry)
{
    /*echo "entry:<pre>";
    print_r($entry);
    echo "</pre>entry end.<br>Session:<pre>";
    print_r($_SESSION);
    echo "</pre>Session end.";
    die;*/
    $dbxClient = getClient();//Using to use the createTemporaryDirectLink() function

    // TODO: Add a token to counter CSRF attacks.
   // $upload_path = htmlspecialchars(getPath('upload'));
    //$path = htmlspecialchars($entry['path']);
    //$form = <<<HTML <form action='$upload_path' method='post' enctype='multipart/form-data'> <label for='file'>Upload file:</label> <input name='file' type='file'/> <input type='submit' value='Upload'/> <input name='folder' type='hidden' value='$path'/> </form> HTML;
    //$form =   <<<HTML HTML;

    $listing_folder = '';
    $listing_folder .= "<div class='container'>
        <div class='row'>
        <div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
        <div style='clear: both;'></div>
        <div class='modal-body'>";
    $listing = "<div id='load' class='loader'></div>
    <div class='container'>
        <div class='row'>
            <div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
                <div style='clear: both;'></div>";
                /*//This section is to display logout button    
                 if(isset($entry['contents']) && $entry['contents']){
                        $listing .= "<div class='modal-footer'>
                            <script>
                                function goDirect(){
                                    window.location.href='dropbox-auth-unlink';
                                }
                            </script>
                            <input type='button' name='logout' value='Logout' class='btn btn-primary' onclick='goDirect()'>
                        </div>";
                    }*/
                $listing .= "<form method='POST' action=''>
                    <div class='modal-body imgAlignment'>";
                        $i=0;
                        $showBtn=False;
                        foreach($entry['contents'] as $child) {
                            $type='Folder';
                            $cp = $child['path'];
                            $cn = basename($cp);
                            if (!$child['is_dir']){
                                $type=$child['mime_type'];
                            }
                            $cp = htmlspecialchars($cp);
                            $link = getPath("?path=".htmlspecialchars($cp));
                            if ($child['is_dir']){
                                $listing_folder .= "<div class='baby_img'>
                                    <a style='text-decoration: none' href='$link'>
                                        <img src='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/folder.jpeg' style='margin: 0px 5px 0 10px !important; width:100px !important; height:100px !important; padding: 0 5px 10px 10px !important;display: block !important;clear: left !important;float: left !important;'>
                                        <div style='clear: both;'></div>
                                        <p style='margin: 0px 5px 0 10px !important; padding: 0 0 0 0 !important;'>$cn</p>
                                    </a>
                                </div>";
                                $cn .= '/';
                            }
                            else{
                                if(strcmp($type,'image/*')==1){
                                    $img = $dbxClient->createTemporaryDirectLink($cp);
                                    $listing .= "<div class='baby_img'>
                                        <input type='checkbox' id='dropbox_".$i."' name='dropbox[]'  value='".$img[0]."' class='styled' />";
                                        $listing .= "<img src='".$img[0]."' class='img-responsive' style='width:100px !important; height:100px !important;'/>";
                                    $listing .= '</div>';
                                    $i++;
                                    $showBtn=true;
                                }
                            }
                        }
                        $listing .= '<div class="clearfix"></div>
                        <div class="modal-footer btnAlignment">';
                            if($showBtn){
                                $listing .= "<input type='submit' name='copy' value='Copy Selected Files' class='btn btn-primary' onclick='loader();'>";
                            }
                            //$listing .= "<input type='button' name='closeWindow' value='Close This Window' class='btn btn-primary pading' onClick='window.close();'>";
                        $listing .= '</div>
                    </div>';
                $listing .= "</form>
            </div>
        </div>
    </div>";

    $listing_folder .= "</div>
    </div>
    </div>
    </div>";
    return renderHtmlPage("App/picpixa$entry[path]", $listing_folder.$listing);
}

function getAppConfig()
{
    global $appInfoFile;

    try {
        $appInfo = dbx\AppInfo::loadFromJsonFile($appInfoFile);
    }
    catch (dbx\AppInfoLoadException $ex) {
        throw new Exception("Unable to load \"$appInfoFile\": " . $ex->getMessage());
    }

    $clientIdentifier = "examples-web-file-browser";
    $userLocale = null;

    return array($appInfo, $clientIdentifier, $userLocale);
}

function getClient()
{
    if(!isset($_SESSION['access-token'])) {
        return false;
    }

    list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
    $accessToken = $_SESSION['access-token'];
    return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}

function getWebAuth()
{
    list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
    $redirectUri = getUrl("dropbox-auth-finish");
    $csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
    return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}

function renderFile($entry)
{
    $metadataStr = htmlspecialchars(print_r($entry, true));
    $downloadPath = getPath("download?path=".htmlspecialchars($entry['path']));
    $body = <<<HTML
<pre>$metadataStr</pre>
<a href="$downloadPath">Download this file</a>
HTML;

    return renderHtmlPage("File: ".$entry['path'], $body);
}

function renderHtmlPage($title, $body)
{
    $output =  <<<HTML
        <html>
            <head>
                <meta charset='utf-8'>
                <meta http-equiv='X-UA-Compatible' content='IE=edge'>
                <meta name='viewport' content='width=device-width, initial-scale=1'>
                <title>$title</title>

                <!-- Bootstrap -->
                <link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
                <link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>
            </head>
            <body>
HTML;

    $permLink = "https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";
    if(isset($_GET) && $_GET['path'] && $_GET != "/")
    {

        $path = $_GET['path'];
        $filename = substr(strrchr($path, "/"), 1);
        $newPath = $permLink."?path=".str_replace('/'.$filename,'',$path);

        if($newPath == $permLink."?path="){
            //Setting the newPath to the root path if there there is first folder  
            $newPath = $permLink;
        }

        $output .= "<br><div class='container'>
            <div class='row'>
                <div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
                    <a href = '".$newPath."' class='btn btn-primary pading'>Back</a>
                </div>
            </div>
        </div>";

    }
    $output .= <<<HTML
                $body
            </body>
        </html>
HTML;
    return $output;
}

function respondWithError($code, $title, $body = "")
{
    $proto = $_SERVER['SERVER_PROTOCOL'];
    header("$proto $code $title", true, $code);
    echo renderHtmlPage($title, $body);
}

function getUrl($relative_path)
{
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        $scheme = "https";
    } else {
        $scheme = "http";
    }
    $host = $_SERVER['HTTP_HOST'];
    $path = getPath($relative_path);
    return $scheme."://".$host.$path;
}

function getPath($relative_path)
{
    if (PHP_SAPI === 'cli-server') {
        return "/".$relative_path;
    } else {
        return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
    }
}

function init()
{
    global $argv;

    // If we were run as a command-line script, launch the PHP built-in web server.
    if (PHP_SAPI === 'cli') {
        launchBuiltInWebServer($argv);
        assert(false);
    }

    if (PHP_SAPI === 'cli-server') {
        // For when we're running under PHP's built-in web server, do the routing here.
        return $_SERVER['SCRIPT_NAME'];
    }
    else {
        // For when we're running under CGI or mod_php.
        if (isset($_SERVER['PATH_INFO'])) {
            return $_SERVER['PATH_INFO'];
        } else {
            return "/";
        }
    }
}

function launchBuiltInWebServer($argv)
{
    // The built-in web server is only available in PHP 5.4+.
    if (version_compare(PHP_VERSION, '5.4.0', '<')) {
        fprintf(STDERR,
            "Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")<br>".
            "doesn't have a built-in web server. You need PHP 5.4 or newer.<br>".
            "<br>".
            "You can still run this example if you have a web server that supports PHP 5.3.<br>".
            "Copy the Dropbox PHP SDK into your web server's document path and access it there.<br>");
        exit(2);
    }

    $php_file = $argv[0];
    if (count($argv) === 1) {
        $port = 5000;
    } else if (count($argv) === 2) {
        $port = intval($argv[1]);
    } else {
        fprintf(STDERR,
            "Too many arguments.<br>".
            "Usage: php $argv[0] [server-port]<br>");
        exit(1);
    }

    $host = "localhost:$port";
    $cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
    $descriptors = array(
        0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
        1 => STDOUT, // Relay process' stdout to ours.
        2 => STDERR, // Relay process' stderr to ours.
    );
    $proc = proc_open($cmd, $descriptors, $pipes);
    if ($proc === false) {
        fprintf(STDERR,
            "Unable to launch PHP's built-in web server. Used command:<br>".
            " $cmd<br>");
        exit(2);
    }
    fclose($pipes[0]); // Close the process' stdin.
    $exitCode = proc_close($proc); // Wait for process to exit.
    exit($exitCode);
}
?>

1 个答案:

答案 0 :(得分:0)

&#34;但在完成所有这一过程后,如果用户从dropbox.com注销,然后再次点击我网站上的保管箱按钮,我相信我的应用程序将要求进行身份验证&#34;。

您的网站正在记住该用户,因为您正在使用会话来执行此操作。如果您不想记住用户,请停止操作。 : - )

通常,退出一个网站的用户对其他网站的会话没有影响。因此,退出dropbox.com的用户不会影响他们在您网站上的登录状态。也许您想在会话上设置到期时间,以便用户在一段时间后被迫重新进行身份验证?或者根本不能使用会话(即不存储访问令牌),在这种情况下,用户必须在每次加载页面时重新进行身份验证?

修改

以下是您共享的用于记住用户的代码:

if ($requestPath === "/") {
    $dbxClient = getClient();

    if ($dbxClient === false) {

        $loginUrl = getPath("dropbox-auth-start");

...

function getClient()
{
    if(!isset($_SESSION['access-token'])) {
        return false;
    }

    list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
    $accessToken = $_SESSION['access-token'];
    return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}