File Size Calculated but File Not Found - php

I am trying to install the "Waiting time file download script using php and jquery" script found at http://www.w3webtools.com/simple-page-download-file-using-php-and-jquery/
I have downloaded the demo scripts and installed them in my server at /var/www/test/.
When I try to call the demo files it recognizes the file size but says the file is not found. http://4x4submods.tk/test/download.php?f=advance-security-login-system-using-php-mysql.zip
Any ideas?
mod_rewrite is enabled.

This works:
<?php
header('Content-Type: text/html;charset=UTF-8');
include 'include/config.php';
include 'include/function.php';
?>
<!-- Edited to point to the latest copy of jquery! -->
<script src="http://code.jquery.com/jquery-2.0.0.js"></script><?php
$fname='hello.txt';
$download=1;
if(!file_exists(UPLOAD_DIR.'/'.$fname))
{
$download=0;
}
$downloadLink='download/'.makeHash($fname).'/'.$fname;
function file_size($url){
$size = filesize($url);
if($size >= 1073741824){
$fileSize = round($size/1024/1024/1024,1) . 'GB';
}elseif($size >= 1048576){
$fileSize = round($size/1024/1024,1) . 'MB';
}elseif($size >= 1024){
$fileSize = round($size/1024,1) . 'KB';
}else{
$fileSize = $size . ' bytes';
}
return $fileSize;
}
?>
<div class="container">
<span class="filename" id="fileinfo-filename" title="<?=$fname?>"><?=$fname?></span>
<span class="fileinfo" id="fileinfo">File Size: <span id="fileinfo-filesize"><?php
if($download!=0){
echo file_size(UPLOAD_DIR.'/'.$fname);
}else{
echo 'N/A';
}
?></span> - Your IP: <span id="fileinfo-views"><?=$_SERVER['REMOTE_ADDR'];?></span></span>
<div id="btnX" class="btn btn-blue">
<span class="text1" id="countdown-info">PREPARERING DOWNLOAD...</span>
<span class="timedown" id="countdown-time"></span>
</div>
<div id="<?=$download?>" class="loading" style="display: none;"></div>
<input id="download" type="text" style="display: none;" value="<?php echo $download ?>">
<a class="btn btn-green" id="btn-download" style="display: none;" href="<?=$downloadLink?>">
<span class="text2">DOWNLOAD</span>
</a>
</div>
<script type="text/javascript">
http://w3webtools.com/wp-admin/post-new.php#
var countDown;
jQuery(document).ready(function(){
countDown=function(start){
if(start==0)
{
jQuery('#countdown-time').html('');
jQuery('#countdown-info').html('PREPARERING DOWNLOAD...');
bla = $('#download').val();
if(bla==0){
jQuery('#countdown-info').html('ERROR: Press F5 to try again. <br></br>404: File not found!');
}else{
jQuery('#btnX').css('display','none');
jQuery('#btn-download').css('display','inline-block');
}
return true;
}
jQuery('#countdown-time').html(start+'s');
start--;
setTimeout('countDown('+start+')',1000);
}
countDown(5);
});
</script>
Function.php file:
<?php
function makeHash($fileName)
{
return md5( $fileName . SECURITY_CODE );
}
function verifyHash($fileName,$hashCode)
{
return $hashCode==makeHash($fileName);
}
Ensure that you use the same hash that you used in the key when decoding!
The rest was not really required and made it more complicated than necessary!
Including the file date in the hash, may make it not work if the file date changes for some reason, for example, if you need to do a system restore. You can probably put the server name back in the hash if you think you really want it!

Related

File upload with Jquery.fileupload.js in CodeIgniter - I can't find my error

The issue is I can't upload file to the folder but the file name is storing in DB. I am getting an image if I copy and paste an image to the folder but I can't able to upload while update or add an image.
I not good in jQuery. Also, this project using Jquery.file upload plugin which I really don't know.
product-edit.php
<div class="col-sm-6">
<table id="files" class="files">
<tr>
<td>
<div class="col-sm-12 text-center">
<img style="width: 300px; height: 200px;" src="<?= base_url() ?>userfiles/product/<?php echo $product['image'] . '?c=' . rand(1, 9999) ?>"/>
</div>
<div class="col-sm-12 my-2" > <?php echo $product['image'] ?> </div>
<div class="col-sm-12 my-2" >
<a class="btn-danger btn-sm px-1 " data-url="<?= base_url() ?>products/file_handling?op=delete&name=<?php echo $product['image'] ?>" class="aj_delete">
<i class="fa fa-trash mx-1 "></i>Delete Image</a>
</div>
</td>
</tr>
</table>
</div>
<div class="col-sm-6">
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span class="my-2">Select files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]">
</span>
<div class="my-1">
<q>Allowed: gif, jpeg, png</q>
</div>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
</div>
</div>
jQuery
<script src="<?php echo assets_url('assets/myjs/jquery.ui.widget.js'); $invoice['tid'] = 0; ?>"></script>
<script src="<?php echo assets_url('assets/myjs/jquery.fileupload.js') ?>"></script>
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '<?php echo base_url() ?>products/file_handling?id=<?php echo $product['pid'] ?>';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
formData: {'<?=$this->security->get_csrf_token_name()?>': crsf_hash},
done: function (e, data) {
var img = 'default.png';
$.each(data.result.files, function (index, file) {
$('#files').html('<tr><td><a data-url="<?php echo base_url() ?>products/file_handling?op=delete&name=' + file.name + '" class="aj_delete"><i class="btn-danger btn-sm icon-trash-a"></i> ' + file.name + ' </a><img style="max-height:200px;" src="<?php echo base_url() ?>userfiles/product/' + file.name + '"></td></tr>');
img = file.name;
});
$('#image').val(img);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Here the controller method for upload file to the folder
Products.php
public function file_handling()
{
if ($this->input->get('op')) {
$name = $this->input->get('name');
if ($this->products->meta_delete($name)) {
echo json_encode(array('status' => 'Success'));
}
} else {
$id = $this->input->get('id');
$this->load->library("Uploadhandler_generic", array(
'accept_file_types' => '/\.(gif|jpe?g|png)$/i', 'max_file_size' => 2048, 'upload_dir' => FCPATH . 'userfiles/product/', 'upload_url' => base_url() . 'userfiles/product/'
));
}
}
The problem is you are loading the upload library config but are not actually processing the upload.
After this, which loads the upload library wih your configuration:
$this->load->library("Uploadhandler_generic", array(
'accept_file_types' => '/\.(gif|jpe?g|png)$/i', 'max_file_size' => 2048, 'upload_dir' => FCPATH . 'userfiles/product/', 'upload_url' => base_url() . 'userfiles/product/'
));
You need to actually process the upload:
if (!$this->upload->do_upload('userfile'))
{
// do something if the upload processing fails. You can output the errors using $this->upload->display_errors()
}
else
{
// do something if the upload is successful
// upload data will be stored in $this->upload->data()
}
By doing this, Codeigniter will take the file from your server's tmp directory and do with it what you want (such as moving it to its destination). Change userfile for the name of the file field.
Please note that if you need to process multiple files at once you'll need to loop through all files (which means a little tweaking on the above code)

Ajax file Upload giving the undefined index file from the php side

I've tried everything i came across and i am sure there is something i dont have in the code .Please i need some help thks.
This is the html which is a form with one input which should receive the file
<div id="Posts">
<h1 style="text-align: center;color: red;">SERVICES</h1>
<p style="text-align: center;"><span style="color:red;">***</span> please ensure to look at the definitions of every field... <span style="color:red;">***</span></p>
<form id="promo_imgs" enctype="multipart/formdata">
<h5 style="text-align: center;"> About the Services You offer</h5><hr style="width: 30%; border:0.5px dashed red;">
<div id="imgpr" class="imgpromo" style="max-width: 40%; min-height: 60px;border:dashed 0.5px;">
<label for="promotion" class="btn btn-primary">
Select an Image
</label>
<img src="" alt="" width="100%" style="max-height: 250px;" id="img">
<input type="file" name="promo0" accept=".png, .jpeg, .jpg" id="promotion" style="display:none;">
</div>
<button class="btn btn-primary" type="submit" id="serv_upload" name="serv_upload">Upload</button>
</form><span id="ajax">
<!--upload an image -->
</span>
then this is the jquery part of it which should preview the image (which works) and then upload the image(which goes successfully to return an undefined index file error)
/* to preview before upload service images*/
$(document).on('change',"#promotion",function(){
var link =URL.createObjectURL(event.target.files[0]);
console.log(link);
var $this=$(this);
$("#img").slideDown("fast").attr('src',link);
$("#serv_upload").slideDown("slow");
});
/* to upload service images*/
$(document).on('click',"#serv_upload",function(e){
e.preventDefault();
$("#ajax").html("Uploading...");
var files = $('#promotion').val(e.target.files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata= new FormData();
formdata.append('file',file);
$("#ajax").append(file.name);
$.ajax({
type:"POST",
url:"aboutinsert.php",
data:{formdata:formdata},
processData:false,
contentType:false,
cache:false,
success: function(data){
$("#ajax").html(data);
}
});
}
});
Finally the php part
$dir="img/portfolio" ;
$file = $_FILES['file']['name'];
$path = $dir.basename($file);
$ext= pathinfo($path,PATHINFO_EXTENSION);
$extensions = array("JPG","jpg","jpeg","png");
$exts=strtolower($ext);
if (!in_array($exts, $extensions)) {
# code...
echo "sorry you donot have the right file format";
}
elseif ($_FILES['file']['size']>2000000) {
# code...
echo "your file is larger than 2mb";
}
elseif (file_exists($path)) {
# code...
echo "sorry a file already exists with this name change the name and try again";
}
else{
if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
# code...
echo basename($_FILES['file']['name']). "upload success";
}
else{
echo "file Upload failed";
}
}
There seem to be some random names being used in the $_FILES array in your PHP code. You use:
$file = $_FILES['file']['name'];
and then
elseif ($_FILES['promo0']['size']>2000000) {
and finally
if (move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
Which is it? If you're not certain, you could var_dump($_FILES); and see what you have.

ask for the re-authentication in api when logout from dropbox

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());
}

php and jquery cannot run through all conditions

I'm writing a code for my website. in this I use drag-drop to give point.
This is my jQuery code:
$('#click').click(function() {
$('#id0').ready(function() {
if ($(this).find('img#e1').length) {
a = 3;
} else if ($(this).find('img#e2').length) {
a = -3;
} else {
a = 0
};
$.post('php/noname1.php', {
point: a
})
});
});
and this is my php code
<?php
$con=mysqli_connect("localhost","name","pass","data") ;
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$point=$_POST['point'];
mysqli_query($con,"INSERT INTO test (point, part, comment) values ($point,'first','good')");
?>
When I click on #click, the php runs but in the database it only gets 3, even though I've changed the img from #e1 to #e2. I think the problem is in the jQuery code, but I don't see anything wrong in the code. Anybody know ?
Here's the html:
<body>
<header>
<div id='header'><img id='logo' src='photo/prlogo.jpg' width='420' height='120'></div>
</header>
<div id='body'>
<div id='product'><img id="product" src="photo/pr.jpg" ></div>
<div id='face'>
<img id="e1" class='e' src="photo/hap.png" width="50" height="50">
<img id="e2" class='e' src="photo/sad.png" width="50" height="50">
</div>
<button type="button" id='click' >Send</button>
<button type="button" id='undo'>Change your mind ?</button>
</div>
and this is how I create #id0, it's a div, droppable, I divided the picture into 5 div, #id0 is one of them:
for ( var i = 0; i < d; i++ ) {
divi.push('<div id="id' + i + '" class="tile" />');
}
I will assume that #id0 is your drop zone
HTML
<div id='product'><img id="product" src="photo/pr.jpg" ></div>
<div id='face'>
<img id="e1" class='e' src="photo/hap.png" width="50" height="50">
<img id="e2" class='e' src="photo/sad.png" width="50" height="50">
</div>
<div id="id0"></div>
<button type="button" id='click'>Send</button>
<button type="button" id='undo'>Change your mind ?</button>
jQuery
$('#click').click(function() {
if ($('#id0 img#e1').length) {
a = 3;
} else if ($('#id0 img#e2').length) {
a = -3;
} else {
a = 0
};
console.log(a)
});
Here's a fiddle http://jsfiddle.net/6JQxW/

how to refresh files/image gallery after delete with xmlhttp/ajax without reloading whole page?

sorry for the lengthy question. i'll try to explain.
i have created a list of images that are visible when you hover over an element (using css)
each image is also a radio button to be chosen and used as part of a form.
All the images are basically all the images in a certain directory that you can also upload to.
I've managed to add a 'delete' button next to each image which will trigger a function that calls a php script to delete that particular image without reloading page. using xmlhttp.which works fine.
But the list of images doesn't refresh itself. As in the image i just deleted is still visible when i hover over the element until i refresh the page then it refreshes the list.
obviously i don't want to refresh the page, that was the whole point of using ajax. so any ideas what i can do? code is below:
<script>
function deleteImage(){
var answer = confirm('Are you SURE you wish to delete this?')
if (answer) {
var image = document.getElementById('filepath').value;
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("uploadmsg").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","delete.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("image="+image);
}
}
then the php/html to call it all.
<?php
$dir = "../images/";
$dh = opendir( $dir );
while( $filename = readdir( $dh ) ) {
$filepath = $dir.$filename;
$gallery[] = $filepath;
$list[] = $filename;
}
sort( $gallery );
sort( $list);
$num_pics = count($gallery);
?>
<div id='chooseimg' ><input type="text" value="Choose Image"><span><ul>
<?php
$a = 2;
while($num_pics > $a)
{
?>
<li>
<input type='radio' name='image' value='<?php echo $list[$a]; ?>'>
<?php echo $list[$a]; ?>
<div id='imglist'><img src='<?php echo$gallery[$a]; ?>' /></div>
<button type='button' onclick="deleteImage()">Delete</button>
<input type="hidden" id="filepath" value="<?php print $gallery[$a]; ?>"/> </li>
<?php
$a ++; }
?>
</ul></span></div>
<div id="uploadmsg"> </div>
the file delete.php contains:
<?php
$image = $_POST['image'];
if (!empty($image)){
unlink($image);
echo "<b>Image deleted<b>";
}
?>
and the css to make the hover over thing work is basically a span inside a div #chooseimage that is set to left:99999px; but when hover over chooseimg it moves to left:0px;
i don't think anyone needs any more info on that but let me know if you do.
as a side note i'm not sure if this actualy ajax? maybe someone can clarify for me.
if you could help i'd be very grateful. i've googled for hours but can't find anything.
ok so for anyone who has the same problem i figured it out.
the code to display all the images along with their radio and delete buttons are stored in a separate php file:
<?php
$dir = "../images/";
$dh = opendir( $dir );
while( $filename = readdir( $dh ) ) {
$filepath = $dir.$filename;
$gallery[] = $filepath;
$list[] = $filename;
}
sort( $gallery );
sort( $list);
$num_pics = count($gallery);
?>
<div id="choose"><div id="echo">
<div style="background-color: #F04D8E; color: #ffffff;">Choose Image</div></div>
<span><ul>
<?php
$a = 3;
while($num_pics > $a)
{
$image = $gallery[$a];
?>
<li>
//the radio button triggers an event which then showsthe image selected
<input id="radio" type='radio' name='image' onchange="thumb('<?php echo $image; ?>')"
value='<?php echo $list[$a]; ?>'><?php echo $list[$a]; ?>
<div id='gallery'>
// the delete button sends the images 'id' in its parameter
<button style="float:right;" type='button'
onclick="deleteImage('<?php echo $image; ?>', '<?php echo $list[$a]; ?>' )">
Delete</button>
<img src='<?php echo $image; ?>' /></div>
</li>
<?php
$a ++;
}
?>
</ul></span></div><br>
in the main page i call this script into a div straight away and also refresh it after the deleteImage function has been requested:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.onload = function(){
$('#result').load('show.php');
}
function deleteImage(id, name){
var answer = confirm('Are you SURE you wish to delete ' + name + ' ?')
if (answer) {
$.post("delete.php", { image: id })
.done(function(){
$('#uploadmsg').html("<b>" + name + " deleted </b>");
$('#result').ready(function(){
$('#result').load('show.php');
});
});
}}
function thumb(image){
$('#echo').html("<img src='"+image+"'>");
}
then all i need in the page is a div with id as result
oh and the delete.php page is still:
<?php
$image = $_POST['image'];
if (!empty($image)){
unlink($image);
}
?>
someone said this is dangerous? but i can't see why.
and questions feel free to ask
thanx

Categories