I am using php sdk provided by dropbox to fetch user's images.
All is working fine. When user comes to my website and clicks on the dropbox button, it is asking for the authentication first and then imports the user's images. Because of this process user automatically logs in the dropbox.com as well. It is expected behavior.
But after all this process, if user logs out from dropbox.com, and then again clicks on the dropbox button in my website, I believe my app shall ask for authentication but it does not ask for the authentication but provides the images from the user dropbox account.
Please ask for more details If I was not clear.
Thank you in advance.
Edit:
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('Go Back');
//alert('Go Back');
/* 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>
Download this file
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);
}
?>
"But after all this process, if user logs out from dropbox.com, and then again clicks on the dropbox button in my website, I believe my app shall ask for authentication".
Your website is remembering the user because you're using a session to do so. If you don't want to remember the user, stop doing it. :-)
In general, a user logging out of one website has no impact on their sessions at other websites. So a user logging out of dropbox.com has no effect on their logged in status on your website. Perhaps you want to set an expiration time on the session so the user is forced to reauthenticate after a while? Or you could not use a session at all (i.e. not store the access token), in which case the user would have to reauthenticate on every page load?
EDIT
Here's the code you shared that remembers the user:
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());
}
Related
I have a problem my delete function does not work he does not delete the organisation. When I press the button it show the text if I want to delete it I say yes but it only refreshes the site. I am not an advanced programmer and some of the code I did not write myself someone else worked on the project before me so idk why he some codes are written this way and he did not use any framework.
My code
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_FILES['croppedImage'])) logoChange();
// change organisation information is not made yet
if (isset($_POST['update'])) echo "This function is not made yet!";
if (isset($_POST['deleteOrganisation'])) DeleteOrganisations();
}
//this is the logoChange function
function logoChange() {
include '../../../include/db_conn.php';
//get organisation_id
$organisation_id = $_POST['organisation_id'];
//blob file info
$fileName = $_FILES['croppedImage']['name'];
$fileTmpName = $_FILES['croppedImage']['tmp_name'];
$fileSize = $_FILES['croppedImage']['size'];
$fileError = $_FILES['croppedImage']['error'];
//change blob to png
$fileType = 'png';
//check if image is able to upload
if ($fileError === 0) {
//check if file is not too big change number to needs!
if ($fileSize < 1000000) {
//make new random filename
$fileNameNew = uniqid('', true).".".$fileType;
$fileDesination = '../../../img/uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDesination);
//check if organisation already has a logo
$get_organisation_stmt = $conn->prepare('SELECT `organisation_logo` FROM `organisations` WHERE `organisation_id` = ?');
$get_organisation_stmt->bind_param('s', $organisation_id);
$get_organisation_stmt->execute();
$result_organisation = $get_organisation_stmt->get_result();
$row = mysqli_fetch_assoc($result_organisation);
if (is_null($row['organisation_logo'])) {
//if not inserted it
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image inserted';
} else {
//else replace it
unlink('../../../img/uploads/'.$row['organisation_logo']);
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image replaced';
}
}
else {
echo "File to big";
}
} else {
echo "Error in file";
}
}
// here i made the delete function
function DeleteOrganisations() {
include '../../../include/db_conn.php';
//delete the organisation
$getDeleteOrganisation = $_POST['deleteOrganisation'];
$delete_organisation_stmt = $conn->prepare('DELETE FROM `organisations` WHERE `organisation_id`= ?');
$delete_organisation_stmt->bind_param('i', $getDeleteOrganisation);
$delete_organisation_stmt->execute();
$delete_organisation_stmt->close();
}
here are the functions and here is JavaScript
//link for datatable functions
$(document).ready(function(){
$('#organisations').DataTable({
"columnDefs": [
{ "orderable": false, "targets": [0, 5] }
],
"order": [[ 1, "asc" ]]
});
});
//open edit modal for logo
$(document).on("click", ".btnopenEditLogo", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenLogoid': organisationId},
success: function (data) {
$('#myLogoEditModal').modal('show');
$("#myLogoEditModal .modal-body").html(data);
}
});
});
//open modal with info of user for editing
$(document).on("click", ".btnopenEditOrganisation", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenOrganisationid': organisationId},
success: function (data) {
$('#myOrganisationEditModal').modal('show');
$("#myOrganisationEditModal .modal-body").html(data);
}
});
});
//delete organisation
$(document).on("click", ".btnRemoveOrganisation", function(e) {
event.preventDefault();
var remove = $(this).val();
var url = "../cms/organisations/functions/postOrganisationActions.php";
Swal.fire({
title: 'Delete this test?',
text: "If you delete the test the questions and all statistics will be lost!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'POST',
url : url,
data: {'deleteOrganisation': remove},
success: function (data) {
Swal.fire({
title: 'Deleted!',
text: "You deleted the survey!",
type: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then((result) => {
if (result.value) {
window.location.reload();
}
});
}
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire (
'Cancelled',
'Your test is safe :)',
'error'
)
}
});
});
this is the index
<?php
session_start();
if (!isset($_SESSION["userId"])) {
header('Location: ../../auth/login');
die();
}
$activePage = "cms";
$activeCMSTab = "organisations";
?>
<!doctype html>
<html lang="en">
<head>
<title>Admin CMS | Organisations</title>
<!-- include header -->
<?php require '../../include/header.php'; ?>
</head>
<body class="d-flex flex-column">
<!-- include navbar -->
<?php require '../../include/navbar.php'; ?>
<!-- include organisation functions -->
<?php require 'functions/getOrganisationsActions.php'; ?>
<div id="main">
<div class="container">
<div class="row">
<div id="sidenav-border" class="col-lg-3 d-none d-md-none d-lg-block">
<?php require '../../include/cms_sidenav.php'; ?>
</div>
<div class="col-lg-9">
<div class="card-theme mt-3">
<div class="clearfix">
<h5 class="card-title-theme float-left"><i class="fas fa-building"></i> Organisation list:</h5>
<i class="fas fa-info-circle fa-fw mt-2 mr-2"></i>
</div>
<hr class="hr-theme" />
<div class="card-body">
<?php getOrganisations(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- footer -->
<?php require '../../include/footer.php'; ?>
<!-- logo modal -->
<?php require 'logo-edit-modal.php'; ?>
<!-- organisation modal -->
<?php require 'organisation-edit-modal.php'; ?>
<!-- logout modal -->
<?php require '../../auth/logout-modal.php'; ?>
<!-- include js scripts -->
<script src="js/organisationFunctions.js"></script>
</body>
</html>
you need get organisation where the button is made the button is at
<?php
function getOrganisations() {
//include DataBase connection
include '../../include/db_conn.php';
//show every organisation that is approved
$sqlCollectAllOrganisations = "SELECT * FROM `organisations` WHERE `approval_admin`='1'";
$resultAllOrganisations = mysqli_query($conn, $sqlCollectAllOrganisations);
echo '<div class="table-responsive">';
echo '<table id="organisations" class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
echo '<th>Logo</th>';
echo '<th>Organisation</th>';
echo '<th>Parent</th>';
echo '<th>type</th>';
echo '<th>Users</th>';
echo '<th>Tools</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
//Show organisations
if ($resultAllOrganisations->num_rows > 0) {
while ($row = $resultAllOrganisations-> fetch_assoc()) {
echo '<tr>';
//organisation logo
if ($row['organisation_logo'] == '')
echo '<td class="align-middle" align="center"><img src="../../img/stock/no-image-icon.png" class="rounded d-inline mr-1" width="30px"></img><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
else
echo '<td class="align-middle" align="center"><img src="../../img/uploads/'. $row['organisation_logo'] .'" class="rounded border d-inline mr-1" width="30px"><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
//organisation name
echo '<td class="align-middle">' .$row['organisation_name']. '</td>';
//organisation parent
if ($row['organisation_parent'] != null) {
$sqlCollectparent = "SELECT * FROM `organisations` WHERE `organisation_id`='".$row['organisation_parent']."'";
$resultparent = mysqli_query($conn, $sqlCollectparent);
if ($parent = $resultparent-> fetch_assoc()) echo '<td class="align-middle">'.$parent['organisation_name'].'</td>';
} else {
echo '<td class="align-middle"><i class="fas fa-times" style="font-size: 16px;"></i></td>';
}
//organisation type
echo '<td class="align-middle">' . $row['organisation_type'] . '</td>';
//count users
$sqlCountUsers = "SELECT COUNT(organisation_id) AS `count` FROM `users` WHERE `organisation_id`='".$row['organisation_id']."'";
$resultcount = mysqli_query($conn, $sqlCountUsers);
if ($count = $resultcount-> fetch_assoc()) echo '<td class="align-middle">'.$count['count'].'</td>';
//buttons
echo '<td class="align-middle text-center">';
echo '<div class="btn-group">';
echo '<button class="btn-theme btn-theme-success btn-theme-sm mr-1">Add user</button>';
echo '<button class="btn-theme btn-theme-primary btn-theme-sm mr-1 btnopenEditOrganisation" value="'. $row['organisation_id'] .'"><i class="fas fa-edit fa-fw"></i></button>';
if ($_SESSION['organisation_id'] != $row['organisation_id']) echo '<button type="button" class="btn-theme btn-theme-danger btn-theme-sm btnRemoveOrganisation" value=""><i class="fas fa-trash-alt fa-fw"></i></button>';
echo '</div>';
echo '</td>';
echo '</tr>';
}
} else {
//do nothing
}
echo '</tbody>';
echo '</table>';
echo '</div>';
}
?>
I am trying to make youtube clone website in php. I am stuck at a stage where i want to insert video that i am trying to upload into mysql database but it says error code 1. My project structure is as follows in below image
Screenshot of my website when i upload the entry as below
When click on upload button, i get the error as below image
Here is my upto date code that i have tried.
index.php File:
<?php require_once("includes/header.php"); ?>
<?php require_once("includes/footer.php"); ?>
header.php file:
<?php require_once("includes/config.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>VideoTube</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="assets/js/commonActions.js"></script>
</head>
<body>
<div id="pageContainer">
<!-- Master Head Container -->
<div id="mastHeadContainer">
<!-- Hamburger Menu Button -->
<button class="navShowHide">
<img src="assets/images/icons/menu.png">
</button> <!--End of Hamburger Menu Button -->
<!-- Site Logo -->
<a class="logoContainer" href="index.php">
<img src="assets/images/icons/VideoTubeLogo.png" title="logo" alt="Site logo">
</a> <!-- End of Site Logo -->
<!-- Search Bar -->
<div class="searchBarContainer">
<form action="search.php" method="GET">
<input type="text" class="searchBar" name="term" placeholder="Search...">
<button class="searchButton">
<img src="assets/images/icons/search.png">
</button>
</form>
</div> <!-- End of Search Bar -->
<!-- Right Icons Area -->
<div class="rightIcons">
<a href="upload.php">
<img class="upload" src="assets/images/icons/upload.png">
</a>
<a href="#">
<img class="upload" src="assets/images/profilePictures/default.png">
</a>
</div> <!-- End of Right Icons Area -->
</div> <!-- End of Master Head Container -->
<div id="sideNavContainer" style="display:none;">
</div>
<div id="mainSectionContainer">
<div id="mainContentContainer">
footer.php file:
</div>
</div>
</div>
</body>
</html>
config.php file:
<?php
ob_start(); // turns on output buffering
date_default_timezone_set("Asia/Calcutta");
try {
$con = new PDO("mysql:dbname=VideoTube;host=localhost", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
VideoDetailsFormProvider.php file:
<?php
class VideoDetailsFormProvider {
private $con;
public function __construct($con) {
$this->con = $con;
}
public function createUploadForm() {
$fileInput = $this->createFileInput();
$titleInput = $this->createTitleInput();
$descriptionInput = $this->createDescriptionInput();
$privacyInput = $this->createPrivacyInput();
$categoriesInput = $this->createCategoriesInput();
$uploadButton = $this->createUploadButton();
return "<form action='processing.php' method='POST' enctype='multipart/form-data'>
$fileInput
$titleInput
$descriptionInput
$privacyInput
$categoriesInput
$uploadButton
</form>";
}
private function createFileInput() {
return "<div class='form-group'>
<input type='file' class='form-control-file' id='exampleFormControlFile1' name='fileInput' required>
</div>";
}
private function createTitleInput() {
return "<div class='form-group'>
<input class='form-control' type='text' placeholder='Title' name='titleInput'>
</div>";
}
private function createDescriptionInput() {
return "<div class='form-group'>
<textarea class='form-control' placeholder='Description' name='descriptionInput' rows='3'></textarea>
</div>";
}
private function createPrivacyInput() {
return "<div class='form-group'>
<select class='form-control' name='privacyInput'>
<option value='0'>Private</option>
<option value='1'>Public</option>
</select>
</div>";
}
private function createCategoriesInput() {
$query = $this->con->prepare("SELECT * FROM categories");
$query->execute();
$html = "<div class='form-group'>
<select class='form-control' name='categoryInput'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row["id"];
$name = $row["name"];
$html .= "<option value='$id'>$name</option>";
}
$html .= "</select>
</div>";
return $html;
}
private function createUploadButton() {
return "<button type='submit' class='btn btn-primary' name='uploadButton'>Upload</button>";
}
}
?>
VideoProcessor.php file:
<?php
class VideoProcessor {
private $con;
private $sizeLimit = 500000000;
private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");
public function __construct($con) {
$this->con = $con;
}
public function upload($videoUploadData) {
$targetDir = "uploads/videos/";
$videoData = $videoUploadData->videoDataArray;
$tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
//uploads/videos/5aa3e9343c9ffdogs_playing.flv
$tempFilePath = str_replace(" ", "_", $tempFilePath);
$isValidData = $this->processData($videoData, $tempFilePath);
if(!$isValidData) {
return false;
}
if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
$finalFilePath = $targetDir . uniqid() . ".mp4";
if(!$this->insertVideoData($videoUploadData, $finalFilePath)) {
echo "Insert query failed";
return false;
}
}
}
private function processData($videoData, $filePath) {
$videoType = pathInfo($filePath, PATHINFO_EXTENSION);
if(!$this->isValidSize($videoData)) {
echo "File too large. Can't be more than " . $this->sizeLimit . " bytes";
return false;
}
else if(!$this->isValidType($videoType)) {
echo "Invalid file type";
return false;
}
else if($this->hasError($videoData)) {
echo "Error code: " . $videoData["error"];
return false;
}
return true;
}
private function isValidSize($data) {
return $data["size"] <= $this->sizeLimit;
}
private function isValidType($type) {
$lowercased = strtolower($type);
return in_array($lowercased, $this->allowedTypes);
}
private function hasError($data) {
return $data["error"] != 0;
}
private function insertVideoData($uploadData, $filePath) {
$query = $this->con->prepare("INSERT INTO videos(title, uploadedBy, description, privacy, category, filePath)
VALUES(:title, :uploadedBy, :description, :privacy, :category, :filePath)");
$query->bindParam(":title", $uploadData->title);
$query->bindParam(":uploadedBy", $uploadData->uploadedBy);
$query->bindParam(":description", $uploadData->description);
$query->bindParam(":privacy", $uploadData->privacy);
$query->bindParam(":category", $uploadData->category);
$query->bindParam(":filePath", $filePath);
return $query->execute();
}
}
?>
VideoUploadData.php File:
<?php
class VideoUploadData {
public $videoDataArray, $title, $description, $privacy, $category, $uploadedBy;
public function __construct($videoDataArray, $title, $description, $privacy, $category, $uploadedBy) {
$this->videoDataArray = $videoDataArray;
$this->title = $title;
$this->description = $description;
$this->privacy = $privacy;
$this->category = $category;
$this->uploadedBy = $uploadedBy;
}
}
?>
processing.php File:
<?php
require_once("includes/header.php");
require_once("includes/classes/VideoUploadData.php");
require_once("includes/classes/VideoProcessor.php");
if(!isset($_POST["uploadButton"])) {
echo "No file sent to page.";
exit();
}
// 1) create file upload data
$videoUploadData = new VideoUploadData(
$_FILES["fileInput"],
$_POST["titleInput"],
$_POST["descriptionInput"],
$_POST["privacyInput"],
$_POST["categoryInput"],
"REPLACE-THIS"
);
// 2) Process video data (upload)
$videoProcessor = new VideoProcessor($con);
$wasSuccessful = $videoProcessor->upload($videoUploadData);
// 3) Check if upload was successful
?>
upload.php File:
<?php
require_once("includes/header.php");
require_once("includes/classes/VideoDetailsFormProvider.php");
?>
<div class="column">
<?php
$formProvider = new VideoDetailsFormProvider($con);
echo $formProvider->createUploadForm();
?>
</div>
<?php require_once("includes/footer.php"); ?>
Per https://www.php.net/manual/en/features.file-upload.errors.php:
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
You should be able to increase upload_max_filesize in php.ini to resolve the issue.
kindly help me to sort this out
i just need to upload an excel file to upload folder same time export data to the mysql database.
currently uploading is successfully happen and if i give excel file location and file name manually data within it will export to the database.
kindly tell me what method should it used to do this same time.
code set used to upload excel file to the 'uploads' folder
<?php
require_once './config/MainConfig.php';
include './config/dbc.php';
$uploadedStatus = 0;
if (isset($_POST["submit"])) {
if (isset($_FILES["file"])) {
// $_SESSION['date_ss'] = $_POST['date_ss'];
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
if (file_exists($_FILES["file"]["name"])) {
unlink($_FILES["file"]["name"]);
$uploadedStatus = 2;
}
$name = basename($_FILES['file']['name']);
$name1 = explode('.', $name);
if ($name1[count($name1) - 1] == 'csv' || $name1[count($name1) - 1] == 'xlsx') {
$target_path = "uploads/";
$target_location = $target_path . basename($_FILES['file']['name']);
$_SESSION['target_location'] = $target_location;
// $datess = $_POST['date_ss'];
move_uploaded_file($_FILES["file"]["tmp_name"], $target_location);
$uploadedStatus = 1;
}
}
} else {
echo "No file selected <br />";
}
}
?>
<html>
<head>
<style>
.file-upload {
max-width: 580px;
height: 200px;
padding: 25px 35px 45px;
margin: 0 auto;
background-color: #fff;
border: 1px solid rgba(0,0,0,0.1);
}
</style>
</head>
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'sendManualFileUpoadingData') {
$Manual_note_No=$_POST['Manual_note_No'];
$Phone_amount= $_POST[' Phone_amount'];
echo $Manual_note_No;
}
}
?>
<div class="container">
<div class="wrapper">
<div class="file-upload">
<div class="row">
<div class="col-md-4">Transfer Note Number :</div>
<div class="col-md-4"><?php echo'' ?></div>
</div>
<div class="row">
<div class="col-md-4">Phone quantity:</div>
<div class="col-md-4"><?php echo '' ?></div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form action="fileuploadexecution.php" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file" multiple="multiple" />
<p style="text-align: right; margin-top: 20px;">
<input type="submit" value="Upload Files" name="submit" class= "btn btn-success" />
</p>
</form>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<?php
if ($uploadedStatus == 1) {
echo 'file uploaded successfully';
} elseif ($uploadedStatus == 2) {
echo 'file already available';
}
?>
</div>
</div>
</div>
</div>
<!-- you need to include the ShieldUI CSS and JS assets in order for the Upload widget to work -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
</html>
code set used to export excel file data into mysql table
<?php
session_start();
//all save,update,delete
require_once './config/dbc.php';
//db connectin
require_once './class/database.php';
require_once './class/systemSetting.php';
$system = new setting();
//calling the class setting from systemsetting.php
$database = new database();
// MainConfig::connectDB();
// $datess = $_SESSION['date_ss'];
// $q = mysql_fetch_array(mysql_query("SELECT MAX(commission.num_of_session +1)AS commax FROM commission"));
// $sess = $q['commax'];
set_include_path(get_include_path() . PATH_SEPARATOR . 'ex_class/');
include './xl_upload/ex_class/PHPExcel/IOFactory.php';
// This is the file path to be uploaded.
//
//echo $_SESSION['target_location'];
//$inputFileName = $target_path . basename($_FILES['file']['name']);
$inputFileName = 'testFile.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
$count = 1;
for ($count; $count <= $arrayCount; $count++) {
$Doc_No = trim($allDataInSheet[$count]["A"]);
$ESN = trim($allDataInSheet[$count]["B"]);
$insertTable = mysql_query("INSERT INTO `test_table` (`Doc_No`, `ESN`) VALUES ('".$Doc_No."','".$ESN."');") or die(mysql_error());
}
$msg = 'Record has been added. <div style="Padding:20px 0 0 0;">Go Back</div>';
?>
excel file that going to upload
Try the this
Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:
$tableName = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
To restore the backup you just need to run LOAD DATA INFILE query like this:
$tableName = 'yourtable';
$backupFile = 'yourtable.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
I use a google api in PHP provided by google (google-api-php-client).
However, I face a problem that the api asks twice for the login. When I click on "Log In To Your Google Account" link for the first time, it redirects me to the google login page (which is correct). Then, after logging in, it redirects me back the page at the url I have given the api, but it asks me again to click on "Log In To Your Google Account" link instead of showing the result of the login action.
When I click on the login link again, it doesn't go to the login page again, but it gives me the result of the login action (after checking of the login status I guess) which should have been done in the first click.
My Code Below:
<?php
/************************************************************************
* Plugin Name: Google Drive Plugin *
* Plugin URI: http://www.picpixa.com/ *
* Version: 1.0 *
* Author: Ashish Shah *
* Description: Plugin To Import Images From User's Google Drive Account *
************************************************************************/
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
session_start();
ini_set("display_errors",1);
?>
<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>Google Drive Images</title>
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<style>
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('Images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
});
</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>
<script type="text/javascript">$('#load').hide();</script>
</head>
<body>
<div id="load" class="loader"></div>
<?php
include_once "templates/base.php";
//ini_set("display_errors",0);
include_once '/home/picpixa/wp-config.php';
set_include_path("src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Http/MediaFileDownload.php';
require_once 'Google/Service/Drive.php';
if(isset($_POST['copy']) && $_POST['gDrive'])
{
$imgArray = $_POST['gDrive'];
$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)
{
$getName = explode ("(OR)",$img);
$imgInfo = pathinfo($getName[1]); //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($getName[0]);
//Putting the main file into the directory
file_put_contents('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName, $file_content);
//Putting the thumbnail in the directory
//Get the image size
$imgsize=get_headers($getName[0],1);
$imgsize = number_format(($imgsize["Content-Length"]/1024),2);
/* To create thumbnail */
// Max vert or horiz resolution
$maxsize=80;
// create new Imagick object
$image = new Imagick($getName[0]); //"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"
/*Problem is in above line ($image->writeImage) otherwise all is working fine because of it Networkerror 500 occurs
* Need to find solution
*/
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();
}
?>
<script type="text/javascript">
//window.opener.$("#fileupload").append(div);
window.opener.$('tbody.files').find('tr').remove();
loadExistingImages();
</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-google-drive/index.php";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary' 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-google-drive/index.php";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary' onClick="window.close();">
</div>
<?php
die();
}
?>
<?php
/************************************************
ATTENTION: Fill in these values!
************************************************/
$client_id = 'YOUR_APP_ID';
$client_secret = 'YOUR_API_SECRET';
$redirect_uri = 'YOUR_REDIRECT_URI';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
/*echo "Client:<pre>";
print_r($client);
echo "</pre>Client End.<br>Service:<pre>";
print_r($service);
echo "</pre>Service End.<br>";
*/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['download_token']);
echo "You are logged out.";
echo "<br>";
}
if (isset($_GET['code'])) {
//echo "Entered get_code<br>";
$client->authenticate($_GET['code']);
$_SESSION['download_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
//It never gets into this section
//echo "Redirect: $redirect<br>";
//echo "Header: ".filter_var($redirect, FILTER_SANITIZE_URL)."<br>";
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/*echo "Session:<pre>";
print_r($_SESSION);
echo "</pre>Session End.<br>";
*/
if (isset($_SESSION['download_token']) && $_SESSION['download_token']) {
//echo "Entered Session download token<br>";
$client->setAccessToken($_SESSION['download_token']);
if ($client->isAccessTokenExpired()) {
//echo "Entered Session download token expire<br>";
unset($_SESSION['download_token']);
}
} else {
//echo "Not Entered Session download token. Entered else part.<br>";
$authUrl = $client->createAuthUrl();
//echo "Auth url: $authUrl<br>";
}
/*echo "Session 2:<pre>";
print_r($_SESSION);
echo "</pre>Session 2 End.<br>";
*/
/********************************************************
If we're signed in then lets try to download our file.
********************************************************/
if ($client->getAccessToken()) {
//echo "Entered getAccessToken<br>";
// This is downloading a file directly, with no metadata associated.
$file = new Google_Service_Drive_DriveFile();
$result = $service->files->listFiles(
$file,
array('downloadType' => 'media')
);
/*echo "File:<pre>";
print_r($file);
echo "</pre>File End.<br>";
echo "Result:<pre>";
print_r($result);
echo "</pre>Result End.<br>";
*/
}
/*echo "File 1:<pre>";
print_r($file);
echo "</pre>File 1 End.<br>";
echo "Result 1:<pre>";
print_r($result);
echo "</pre>Result 1 End.<br>";
*/
?>
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php
if (isset($authUrl)){ ?>
<a class='login' href='<?php echo $authUrl; ?>'>Log In To Your Google Account!</a>
<?php }else{ ?>
<a class='logout' href='?logout'>Log Out</a>
<?php } ?>
<?php
if (isset($result)){
$i=0;
$temp=0;
$showBtn=False;
?>
<form method='post' action='index.php'>
<div class='modal-body'>
<?php
/*echo "Result:<pre>";
print_r($result);
echo "</pre>Result End.<br>";
die;*/
foreach ($result as $key => $value){
if(strcmp($result['modelData']['items'][$i]['mimeType'],'image/jpeg') == 0
|| strcmp($result['modelData']['items'][$i]['mimeType'],'image/jpg') == 0
|| strcmp($result['modelData']['items'][$i]['mimeType'],'image/png') == 0)
{
if(isset($result['modelData']['items'][$i]['thumbnailLink'])){
//echo $result['modelData']['items'][$i]['thumbnailLink']."(OR)".$result['modelData']['items'][$i]['title']."<br>";
?>
<div class="baby_img">
<input type="checkbox" id="gDrive_<?=$temp;?>" name="gDrive[]" value="<?php echo $result['modelData']['items'][$i]['thumbnailLink']."(OR)".$result['modelData']['items'][$i]['title'];?>" class="styled" />
<input type="hidden" id="fileName_<?=$temp;?>" name="fileName[]" value="<?php echo $result['modelData']['items'][$i]['title'];?>" class="styled" />
<img src="<?php echo $result['modelData']['items'][$i]['thumbnailLink'];?>" class="img-responsive" style="width:100px !important; height:100px !important;"/>
</div>
<?php
}
$temp++;
}
$i++;
$showBtn=True;
}
?>
</div>
<div class="clearfix"></div>
<div class="modal-footer">
<?php
if($showBtn){
?>
<input type='submit' name='copy' value='Copy Selected Files' class="btn btn-primary" onclick="loader()">
<?php
}
?>
<input type='button' name='closeWindow' value='Close This Window' class='btn btn-primary' onClick="window.close();">
</div>
</form>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
Note: I have put echo and print_r to understand better the code behavior. You can freely remove them.
I found the solution.
It was the stupid problem. I have added header() in the index.php and it was redirecting to the same file (index.php). So I removed the header() and now it is working perfectly.
I solved this by placing my php at the very top of the page before everything...
if (isset($_POST['login'])) {
//whatever you got
}
if (isset($_POST['register'])) {
//whatever you got
}
<?php
session_start();
if(!$_SESSION['Admin']) {
header('Location: login.php'); exit();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> ticketExpress | Admin </title>
<link rel='stylesheet' href='../assets/css/style.css'>
</head>
<body>
<div id='containerAdmin'>
<h1> <img class='logo' src='../assets/images/logo.png' width='200' height='43'> </h1> <a href='?logout' class='logout'> Logout </a>
<h3> Open Tickets </h3>
<hr />
<?php
require("../configuration/config.php");
$GetTickets = $con->query("SELECT * FROM tickets WHERE open='true'");
while($TicketInfo = $GetTickets->fetch_object()) {
$Subject = $TicketInfo->Subject;
echo "<div id='ticket'>".$Subject ."<a href='?delete=$TicketInfo->ID'><img style='float:right'src='../assets/images/delete.png' width='15px' height='15px'></a><a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='?close=$TicketInfo->ID'> Close </a><font style='float:right; margin-right:10px; color:green;' id='responseMsg'> </font></div>";
}
if(isset($_GET['delete'])) {
$ID = $_GET['delete'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
ajax.open('POST','delete.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg').innerHTML = ajax.responseText;
}
}
ajax.send('delete=$ID');
</script>
";
}
if(isset($_GET['logout'])) {
session_destroy();
header('Location: login.php');
}
if(isset($_GET['close'])) {
$ID = $_GET['close'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
ajax.open('POST','close.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg').innerHTML = ajax.responseText;
}
}
ajax.send('close=$ID');
</script>
";
}
?>
<br />
</div>
</body>
</html>
My problem is that whenever I click delete, the ajax response always appears next to the first ticket on the page (the top one)
If I for example click "Close" next to ticket 21, the AJAX response "Ticket Succesfully Closed" will always appear next to the first ticket on the page (for example ticket 1)
Here is close.php
<?php
require('../configuration/config.php');
if(isset($_POST['close'])) {
echo "Ticket Successfully Closed";
$TID = $_POST['close'];
$con->query("UPDATE tickets SET open='false' WHERE ID='$TID'");
}
And delete.php
<?php
require('../configuration/config.php');
if(isset($_POST['delete'])) {
echo "Ticket Deleted";
$TID = $_POST['delete'];
$con->query("DELETE FROM tickets WHERE ID='$TID'");
}
All answers are much appreciated as always! thanks in advance
You have multiple DOM elements with same ID. Check your while loop.
Code document.getElementById('responseMsg') will always get the first element that exists in DOM.
You are displaying multiple tickets with the same DOM id.
You need to append some unique identifier to element where you want to display server response.
Look at this line:
echo "<div id='ticket'>".$Subject ."<a href='?delete=$TicketInfo->ID'><img style='float:right'src='../assets/images/delete.png' width='15px' height='15px'></a><a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='?close=$TicketInfo->ID'> Close </a><font style='float:right; margin-right:10px; color:green;' id='responseMsg'> </font></div>";
You could change id='responseMsg' to id='responseMsg{$TicketInfo->ID}' and then send this ticket ID as a parameter in JavaScript function to target the right one "responseMsg" element.
E.g.
echo "<div id='ticket{$TicketInfo->ID}'>". $Subject ." <a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='#' onclick='closeTicket({$TicketInfo->ID});'> Close </a><span style='float:right; margin-right:10px; color:green;' id='responseMsg{$TicketInfo->ID}'> </span></div>";
<script type='text/javascript'>
function deleteTicket(ticketID) {
var ajax = new XMLHttpRequest();
ajax.open('POST','delete.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg'+ticketID).innerHTML = ajax.responseText;
}
}
ajax.send('delete='+ticketID);
}
</script>