i'm building a directory browser and while i was looking for info i found this question, to my surprise the code is quite easier than i expected and i'm able to understand it, so i'm using it on my project(i'm quite new to php, and i never use code that i don't understand). It works fine and i've made a few aesthetic changes. Now here comes the problem, for some reason i cannot change the root directory, i have this:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location: ./test.php");
}
?>
<!doctype html>
<html>
<head>
<title>CoroCloud</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.pink-indigo.min.css" />
</head>
<html>
<body>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Cloud</span>
<!-- Add spacer, to align navigation to the right -->
<div class="mdl-layout-spacer"></div>
<!-- Navigation. We hide it in small screens. -->
<nav class="mdl-navigation mdl-layout--large-screen-only">
<?php
echo "<a class=\"mdl-navigation__link\" href=\"\">{$_SESSION['username']}</a>";
?>
</nav>
</div>
</header>
<div class="mdl-layout__drawer">
<span class="mdl-layout-title">CATEGORIES</span>
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="">File</a>
<a class="mdl-navigation__link" href="">Images</a>
<a class="mdl-navigation__link" href="">Music</a>
<a class="mdl-navigation__link" href="">Films</a>
</nav>
</div>
<main class="mdl-layout__content" style="background-color: white; background-image: url('https://i.warosu.org/data/tg/img/0357/97/1414469732022.gif'); background-size: auto 100%; background-repeat: no-repeat; background-position: center;">
<center>
<div class="page-content" style="padding: 24px; flex: none; align-items: center; justify-content: center;">
<?php
// Snippet from PHP Share: http://www.phpshare.org
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' kB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
$root = dirname("path");
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
$parent = realpath($file);
$i = 0;
while ($parent) {
if ($directory == $parent) return true;
if ($parent == dirname($parent) || !$recursive) break;
$parent = dirname($parent);
}
return false;
}
$path = null;
if (isset($_GET['file'])) {
$path = $_GET['file'];
if (!is_in_dir($_GET['file'], $root)) {
$path = null;
} else {
$path = '/'.$path;
}
}
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
echo "<div>\n";
echo "<table class=\"mdl-data-table mdl-js-data-table mdl-shadow--2dp\" style=\"min-width:300px\"\n";
echo " <thead>\n";
echo " <tr>\n";
echo " <th class=\"mdl-data-table__cell--non-numeric\">File</th>\n";
echo " <th>Size</th>\n";
echo " </tr>\n";
echo " </thead>\n";
echo " <tbody>";
if ($path) echo '<tr><td colspan="2" style="text-align:center">..</td></tr><br />';
foreach (glob($root.$path.'/*') as $file) {
$file = realpath($file);
$link = substr($file, strlen($root) + 1);
if (is_dir($file)){
echo '<tr><td style="text-align:center; vertical-align:middle"><i class="material-icons" style="vertical-align:middle">folder</i></td><td style="text-align:center; vertical-align:middle"><span style="vertical-align:middle">'.basename($file).'</span></td></tr><br />';
}
else {
$size = formatSizeUnits(filesize($file));
echo '<tr><td><a href="?file='.urlencode($link).'" download>'.basename($file).'</a></td><td>'.$size.'</td></tr><br />';
}
}
?>
</tbody>
</table>
</div>
</center>
</main>
</div>
</body>
</html>
What i'm doing is changing the value of $root, but the result is not what i expected, instead of allow me to browse the contents it stays in root directory even if i click another folder. In some of the tests i've done (with different paths and permissions) sometimes it didn't even show anything.
Can anybody tell me why is this happening AND how to solve this?
(Please don't answer with just a solution, i'd like to know what's is what I missunderstood and learn)
I think the issue lies within retrieving the $root path. Your whole script is based on working with absolute paths, therefore I've changed the $root path to also get its absolute path and voilà it worked.
Make sure that argument given to dirname does exist, as it looks like it's not intended to be just the string "path". More at php.net
$root = realpath(dirname("path"));
By the way:
While testing your script I found an issue regarding downloading files. When clicking a file it allows me to download it, but the downloaded file contains the HTML code of your script up to the point where the file is being sent. So make sure to move your code to the beginning of the file in order to fix it.
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
Edit:
I found another issue regarding the function is_in_dir, it's not capable of working with relative paths when the root directory is not the exact same as the scripts directory. To let it work the function needs to look for the specified $file within the root directory $directory like the following:
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
// new:
$parent = realpath($directory . DIRECTORY_SEPARATOR . $file);
$i = 0;
Related
So I need some help from a Ziggeo user. I have registered 8 videos in my ziggeo server and now I want to display them in pages divided by 2 videos per page.
Here is what I wrote, but unfortunately it doesn't show me any video, but the compiler doesn't say any error.
<?php include('./ziggeo/pagination.class.php');?>
<?php $myvideos = $ziggeo->videos();
$myarray = array($myvideos);?>
<div class="gallery">
<?php if(count($myarray)){
$pagination = new pagination($myarray, (isset($_GET['page'])?$_GET['page']:1), 3);
$videos = $pagination->getResults();
if(count($videos)!=0) {
echo $pageNumbers = '<h2>'.$pagination->getLinks().'</h2>';
foreach ($videos as $video) {?>
<div class="wall-of-videos-container">
<ziggeo ziggeo-video="<?= $video->token ?>"
ziggeo-width=320 ziggeo-height=240 ziggeo-popup> </ziggeo>
<?= date("Y-m-d h:i a", $video->created) ?>
·<?= $video->duration ?> seconds</div>
<? } echo $pageNumbers; } } ?>
</div><!-- End Gallery -->
I included all the files needed for the Ziggeo configuration.
Who can help me? Thank a lot!
Without seeing 'pagination.class.php' file contents and the output that you are creating it is difficult to know what went wrong, however to create pagination in PHP using Ziggeo PHP SDK, you would do something like this:
<?php
require_once('Ziggeo.php');
$ziggeo = new Ziggeo('YOUR TOKEN', 'YOUR PRIVATE KEY', 'YOUR ENCRYPTION KEY');
?>
You can get the token and keys from your dashboard on ziggeo.com
Ziggeo.php can be retrieved from Ziggeo PHP SDK here: github.com/Ziggeo/ZiggeoPhpSdk
Now looking at your code it seems that this is the call that you are not making correctly. To get the videos you should make the following call:
<?php $myvideos = $ziggeo->videos()->index(); ?>
It is good to remember that by default you will only get up to 50 videos, so if you are expecting to have more than that, you should set the limit parameter.
You can set limit, skip, reverse, states and tags
In case you want to get up to 100 videos (which is maximum per call) you would do something like this:
<?php
$myArguments = array('limit' => 100);
$myvideos = $ziggeo->videos()->index($myArguments);
?>
Now to list them, you would do something like this:
<?php
foreach ($myvideos as $video) {
?>
<ziggeo ziggeo-video="<?php echo $video->token; ?>" ziggeo-width=320 ziggeo-height=240 ziggeo-popup></ziggeo>
<?php
}
?>
You could add a check with count($myvideos) before foreach, however it should not be needed.
In general, to create a page with 2 videos per page you could use something like this:
<?php
$i = 0; //to have two videos per page
$j = 0; //to see how many we have
foreach ($myvideos as $video) {
$j++;
if($i === 0) { ?>
<div class="gallery_page">
<?php } ?>
<ziggeo ziggeo-video="<?php echo $video->token; ?>" ziggeo-width=320 ziggeo-height=240 ziggeo-popup></ziggeo>
<?php
$i++;
if($i === 2) { ?>
</div>
<div class="page_number"><?php echo $j/2; ?> </div>
<?php
$i = 0;
}
}
if($i !== 0) {
?>
<div class="page_number"><?php echo (($j-1)/2)+1; ?> </div>
<?php
}
?>
It is good to point out that the above code is not a complete paging system - it is just a simple sample that shows you how you could do it, however it would need to be customized and worked upon further to match gallery style, and similar.
Looking at your code, I think that it should work using something like this:
<?php
include('./ziggeo/pagination.class.php');
$myvideos = $ziggeo->videos()->index();
?>
<div class="gallery">
<?php
if(count($myvideos)) {
$pagination = new pagination($myarray, (isset($_GET['page']) ? $_GET['page']:1), 3);
$videos = $pagination->getResults();
if(count($videos)!=0) {
echo $pageNumbers = '<h2>'.$pagination->getLinks().'</h2>';
foreach ($videos as $video) { ?>
<div class="wall-of-videos-container">
<ziggeo ziggeo-video="<?php echo $video->token; ?>" ziggeo-width=320 ziggeo-height=240 ziggeo-popup></ziggeo>
<?php echo date("Y-m-d h:i a", $video->created); ?>
·<?php echo $video->duration; ?> seconds</div>
<?php } echo $pageNumbers;
}
} ?>
</div><!-- End Gallery -->
I did presume however that you have the headers set in the HTML HEAD of the page where the gallery will be shown:
<link rel="stylesheet" href="//assets-cdn.ziggeo.com/v1-latest/ziggeo.css" />
<script src="//assets-cdn.ziggeo.com/v1-latest/ziggeo.js"></script>
<script type="text/javascript">ZiggeoApi.token="YOUR TOKEN"</script>
If not present, the HTML code will be created from the above PHP code, however your videos would not be shown due to Ziggeo framework not being loaded on client side.
UPDATE (2016/05/31)
As the above is just general way to do this, it is not including CSS nor JavaScript.
As such I am adding the full code that can be used and as it shows another way to collect the page numbers and leaving the above so that someone can see both.
<script type="text/javascript">
//Basic code needed to switch pages
var currentPage = 1;
function showPage(number) {
//If we are on the same page as the selected one, we just break away from the function, so that we do not hide the same.
if(currentPage === number) { return false; }
var toShow = document.getElementById('page_' + number);
var toHide = document.getElementById('page_' + currentPage);
toShow.style.display = 'block';
toHide.style.display = 'none';
currentPage = number;
}
</script>
<style type="text/css">
/* Code to hide the pages (all) and show first one only, as well as a bit of styling so that it has some basic frame */
.gallery_page > ziggeo {
float: left;
}
.gallery_page {
background-image: linear-gradient(-45deg, lightGray, white);
border-radius: 10px;
box-shadow: 0 0 2px gray;
box-sizing: border-box;
display: none;
min-height: 400px;
margin: 20px 0;
padding: 40px;
width: 720px;
}
.gallery_page:first-child {
display: block;
}
.page_number {
box-shadow: 0 0 3px gray;
float: left;
margin: 0 4px;
text-align: center;
width: 2em;
}
</style>
<div class="gallery">
<?php
//How many videos per page do we want to have?
$numberOfVideos = 2;
//How many videos was there in total?
$totalNumberOfVideos = 0; //only if we need it for something later on
//How many videos are approved / are shown
$totalNumberOfApprovedVideos = 0; //only if we need it for something later on
//which page are we working on?
$currentPage = 1;
//Will serve as buffer for page number elements
$pageNumbers = '';
//temporary videos counter
$i = 0;
foreach ($myvideos as $video) {
//to only show approved videos
if($video->approved === true) {
if($i === 0) { ?>
<div class="gallery_page" id="page_<?php echo $currentPage; ?>">
<?php } ?>
<ziggeo ziggeo-video="<?php echo $video->token; ?>" ziggeo-width=320 ziggeo-height=240 ziggeo-popup></ziggeo>
<?php
$i++;
if($i === $numberOfVideos) { ?>
<br style="float:none; clear:left;">
</div>
<?php
$pageNumbers .= '<div onclick="showPage(' . $currentPage . ');" class="page_number">' . $currentPage . '</div>';
$currentPage++;
$i = 0;
}
$totalNumberOfApprovedVideos++;
$totalNumberOfVideos++;
}
else {
//$video->moderation_reason
//If you want to check if there was a reason why the video was not approved, you can check the above, or alternatively, you could do something else at this point.
$totalNumberOfVideos++;
}
}
if($i !== 0) {
$pageNumbers .= '<div onclick="showPage(' . $currentPage . ')" class="page_number">' . $currentPage . '</div>';
}
?>
</div><!-- End Gallery -->
<?php echo $pageNumbers; ?>
<?php
//This is not needed for pagination to work, however you might want to show it, etc
echo '<br><br>';
echo 'Approved videos: ' . $totalNumberOfApprovedVideos . '<br>';
echo 'Total videos: ' . $totalNumberOfVideos . '<br>';
echo 'Total number of pages: ' . $currentPage . '<br>';
echo $numberOfVideos . ' videos per page<br>';
?>
It is good to point out that this is just a framework - so the code mentioned before will work just as the followup code does, however both require additional styling and code to make it look nice and behave as we want it.
After adding the java script below:
<script type="text/javascript">
var currentPage = 1;
function showPage(number){
var toShow = document.getElementById('page_' + number);
var toHide = document.getElementById('page_' + currentPage);
toShow.style.display = 'block';
toHide.style.display = 'none';
currentPage = number;}
</script>
And the right references to the div gallery, now all is working. Thanks Bane.
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!
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());
}
How can i add a file size beside my file names using PHP???
Currently Using This:
<?php
# Configuration
$show_path = 0; # Show local path.
$show_dotdirs = 1; # Show '.' and '..'.
$path = substr($_SERVER['SCRIPT_FILENAME'], 0,
strrpos($_SERVER['SCRIPT_FILENAME'], '/') + 1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="menu">
<div id="menualign"><img src="images/home.png" onmouseover="src='images/homed.png'" onmouseout="src='images/home.png'"/><img src="images/moviesa.png"/><img src="images/tv.png" onmouseover="src='images/tvd.png'" onmouseout="src='images/tv.png'"/></div>
</div>
<div id="container">
<div id="fleft">
<table cellspacing="1">
<tr>
<th><?php if ($show_path == 1) { echo $path; } else { echo 'Current Movies'; } ?></th>
</tr>
<tr>
<td align="left"><?php
$dirs = array();
$files = array();
$dir = dir('../Movies/');
while ($entry = $dir->read()) {
if (($entry != '.') and (substr($entry, -4) != '.php')) {
if (is_dir($entry)) {
if (($entry != '..') or $show_dotdirs){
$dirs[] = $entry;
}
} else {
$files[] = $entry;
}
}
}
$dir->close();
sort($dirs);
foreach ($dirs as $dir) {
printf('<strong><</strong> %s <strong>></strong><br />' . "\n", $dir, $dir);
}
sort($files);
foreach ($files as $file) {
printf('<hr />%s<br />' . "\n", $file, $file);
}
?></td>
</tr>
</table>
</div>
<div id="fright">TEST
</div>
</div>
</body>
</html>
Which outputs as this: http://downunderpctech.com/output.png
I Would like to Add a section for Filesize
Probably using the same code but to collect filesize info as the Filename but in a new beside it
I am not too concerned about the Filesize output, but would prefer only to output KB
Thanks, Adam
You should use the function filesize on your $file variable.
And then you can output a human readable size with this little function:
function file_size($size)
{
$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
}
You define the function before the # Configuration and then you call it in your foreach:
echo file_size(filesize('../Movies/'.$file));
You can write the file, then use the filesize function to get the file size and rename the file with the size in the file name.
http://php.net/manual/en/function.filesize.php
You can add this to your foreach
echo '<span>'.round(filesize ('../Movies/'.$file)/1024, 1).' Kb</span>';
I believe I have most everything correctly configured for the recorder because I can
1 - Get the Flash permission prompt
2 - Start recording
3 - Listen to the playback
but when I go to save the file I can find it neither in the upload directory nor the temp dir.
I know php is working because I have tested a post - upload form successfully.
Here's the html and php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My Recorder</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript">
$(function() {
var appWidth = 24;
var appHeight = 24;
var flashvars = {'event_handler': 'microphone_recorder_events', 'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "10.1.0", "", flashvars, params, attributes);
});
</script>
<style>
#control_panel { white-space: nowrap; }
#control_panel a { outline: none; display: inline-block; width: 24px; height: 24px; }
#control_panel a img { border: 0; }
#save_button { position: absolute; padding: 0; margin: 0; }
#play_button { display: inline-block; }
</style>
</head>
<body>
<div id="status">
Recorder Status...
</div>
<div id="control_panel">
<a id="record_button" onclick="Recorder.record('audio', 'audio.wav');" href="javascript:void(0);" title="Record"><img src="images/record.png" width="24" height="24" alt="Record"/></a>
<span id="save_button">
<span id="flashcontent">
<p>JavaScript enabled and Adobe Flash Player installed, please</p>
</span>
</span>
<a id="play_button" style="display:none;" onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play"><img src="images/play.png" width="24" height="24" alt="Play"/></a>
</div>
<div id="upload_status">
</div>
<form id="uploadForm" name="uploadForm">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
</body>
</html>
<?php
$save_folder = dirname(__FILE__) . "/audio";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = $_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/x-wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\":$saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
?>
btw - this came straight from the cykod site, I've done barely anything to it...
also, how do i convert to mp3 upon pressing the save button?
Thanks!
Don't know if you ever got an answer to this, but check your folder permissions. After setting my "audio" folder such that everyone can read/write it worked. Of course this is not the best way to do this - you need to set your apache/php account to be writeable to the folder - but at least this should get you going.