/    Sign up×
Community /Pin to ProfileBookmark

PHP Progress Bar, possible solution

Alright, well if anyone is following me talking to myself (in my other post about finding a php progress bar script), I have come to a new realization. Mind you, I have very limited knowledge of javascript, but from what I am gathering about the script above (from [url]http://progphp.com/progress.php)[/url], that though the script is just generating the progress bar and such. It is somehow passing the file information to the cache (ergo the need for APC) and is monitoring how much of the file has been moved to the cache so that it can be checked by the php script, right?. At least that is how it is making sense to me for it to work. To make it work for me and with bokeh’s script, I had to put all the code into one page (at least for now until I get a better understanding of how it all really works together), and have the page reference itself when the file is uploaded. There is a function in the javascript that does the call to the php, the function is postForm and it takes the php file and the name of the form as arguments. It also is calling some Yahoo functions, but I can’t seem to locate where they are defined. It seems like it should work, I could make a well educated guess that what I am missing is something simple.

Here is the php code:

[code=php]
<?php
session_start();

//recored pages current directory
$directory_self = str_replace(basename($_SERVER[‘PHP_SELF’]), ”, $_SERVER[‘PHP_SELF’]);

// set a max file size for the html upload form
$max_file_size = 209715200; // size in bytes

if(isset($_SESSION[‘logged’]) && $_SESSION[‘logged’] == 1) {

$directory_self = str_replace(basename($_SERVER[‘PHP_SELF’]), ”, $_SERVER[‘PHP_SELF’]);

$uploadsDirectory = ‘\directory\to\uploads\’;

$uploadForm = ‘http://’ . $_SERVER[‘HTTP_HOST’] . $directory_self . ‘upload.php’;

$uploadSuccess = ‘http://’ . $_SERVER[‘HTTP_HOST’] . $directory_self . ‘success.php’;

$fieldname = ‘file’;
$filename = $_FILES[‘file’][‘name’];
$filetype = $_FILES[‘file’][‘type’];

// possible PHP upload errors
$errors = array(1 => ‘Max file size exceeded’,
2 => ‘HTML form max file size exceeded’,
3 => ‘File was only partialy uploaded’,
4 => ‘No file was attached’);

if($_SERVER[‘REQUEST_METHOD’]==’POST’) {

$status = apc_fetch(‘upload_’.$_POST[‘APC_UPLOAD_PROGRESS’]);
$status[‘done’]=1;
$jsn = json_encode($status);

// check the upload form was actually submitted else print form
isset($_POST[‘upload’])
or error(‘The Upload form was not used.’, $uploadForm);

// check if any files were uploaded and if
// so store the active $_FILES array keys
$active_keys = array();
foreach($_FILES[$fieldname][‘name’] as $key => $filename)
{
if(!empty($filename))
{
$active_keys[] = $key;
}
}
// check at least one file was uploaded
count($active_keys)
or error(‘No files were uploaded’, $uploadForm);

// check for standard uploading errors
foreach($active_keys as $key)
{
($_FILES[$fieldname][‘error’][$key] == 0)
or error($_FILES[$fieldname][‘tmp_name’][$key].’: ‘.$errors[$_FILES[$fieldname][‘error’][$key]], $uploadForm);
}
// check that the file we are working on really was an HTTP upload
foreach($active_keys as $key)
{
@is_uploaded_file($_FILES[$fieldname][‘tmp_name’][$key])
or error($_FILES[$fieldname][‘tmp_name’][$key].’ not an HTTP upload’, $uploadForm);
}
// validation… since this is an image upload script we
// should run a check to make sure the upload is an image
foreach($active_keys as $key)
{
if($filetype == ‘application/octet-stream’ || $filetype == ‘text/html’ || $filetype == ‘text/x-php’ || $filetype == ‘application/x-javascript’) {
error($_FILES[$fieldname][‘tmp_name’][$key].’ not a valid file type’, $uploadForm);
} else {
filesize($filename);
}
}
// make a unique filename for the uploaded file and check it is
// not taken… if it is keep trying until we find a vacant one
foreach($active_keys as $key)
{
$now = time();
while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.’-‘.$_FILES[$fieldname][‘name’][$key]))
{
$now++;
}
}
// now let’s move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
@move_uploaded_file($_FILES[$fieldname][‘tmp_name’][$key], $uploadFilename[$key])
or error(‘receiving directory insuffiecient permission’, $uploadForm);
}
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.

header(‘Location: ‘ . $uploadSuccess);

// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
header(“Refresh: $seconds; URL= $uploadForm”);
$err = ‘<h3>Your File was not uploaded.</h3>’;
$err .= ‘<p>An error has occured: ‘.”<br/>”;
$err .= ‘<span style=”color:#CC0000″>’ . $error . ‘…</span>’.”<br/>”;
$err .= ‘You are being sent back to the upload form, please wait.</p>’;
}
} else if(isset($_GET[‘progress_key’])) {
$status = apc_fetch(‘upload_’.$_GET[‘progress_key’]);
echo json_encode($status);
exit;
}

} else {
header(“Location: http://” . $_SERVER[‘HTTP_HOST’] . $directory_self . “login.php”);
exit();
}
?>
[/code]

javascript code:

[code=html]
<script type=”text/javascript”>
function updateInput() {
var loop = document.getElementById(‘numfile’).value;
var inputStr = “”;
if (loop == 1) {
inputStr = “<p>Your file:”;
} else {
inputStr = “<p>Your files:”;
}
for (x=1;x<=loop;x++) {
inputStr = inputStr + “<br><input type=’file’ name=’file[]’ style=’margin:0.25em 0 0.25em 0;’ />”;
}
document.getElementById(‘divInput’).innerHTML = inputStr;
}
</script>
<!– Upload Progress Bar Scripting Code –>
<script type=”text/javascript” src=”Assets/YUI/build/yahoo/yahoo.js”>
</script>
<script type=”text/javascript” src=”Assets/YUI/build/event/event.js”>
</script>
<script type=”text/javascript” src=”Assets/YUI/build/dom/dom.js”>
</script>
<script type=”text/javascript” src=”Assets/YUI/build/animation/animation.js”>
</script>
<script type=”text/javascript” src=”Assets/YUI/build/dragdrop/dragdrop.js”>
</script>
<script type=”text/javascript” src=”Assets/YUI/build/conection/connection.js”>
</script>
<script type=”text/javascript” src=”Assets/YUI/build/container/container.js”>
</script>
<link rel=”stylesheet” type=”text/css” href=”Assets/YUI/build/container/assets/container.css” />
<script type=”text/javascript”>
var fN = function callBack(o) {
var resp = eval(‘(‘ + o.responseText + ‘)’);
var rate = parseInt(resp[‘rate’]/1024);
if(resp[‘cancel_upload’]) {
txt=”Cancelled after “+resp[‘current’]+” bytes!”;
} else {
txt=resp[‘total’]+” bytes uploaded!”;
}
txt += “<br>Upload rate was “+rate+” kbps.”;
document.getElementById(‘pbar’).style.width = ‘100%’;
document.getElementById(‘ppct’).innerHTML = “100%”;
document.getElementById(‘ptxt’).innerHTML = txt;
setTimeout(“progress_win.hide(); window.location.reload(true);”,2000);
}
var callback = { upload:fN }

var fP = function callBack(o) {
var resp = eval(‘(‘ + o.responseText + ‘)’);
if(!resp[‘done’]) {
if(resp[‘total’]) {
var pct = parseInt(100*(resp[‘current’]/resp[‘total’]));
document.getElementById(‘pbar’).style.width = ”+pct+’%’;
document.getElementById(‘ppct’).innerHTML = ” “+pct+”%”;
document.getElementById(‘ptxt’).innerHTML = resp[‘current’]+” of “+resp[‘total’]+” bytes”;
}
setTimeout(“update_progress()”,500);
} else if(resp[‘cancel_upload’]) {
txt=”Cancelled after “+resp[‘current’]+” bytes!”;
document.getElementById(‘ptxt’).innerHTML = txt;
setTimeout(“progress_win.hide(); window.location.reload(true);”,2000);
}
}
var progress_callback = { success:fP }

function update_progress() {
progress_key = document.getElementById(‘progress_key’).value;
YAHOO.util.Connect.asyncRequest(‘GET’,’progress.php?progress_key=’+progress_key, progress_callback);
}

var progress_win;

function postForm(target,formName) {
YAHOO.util.Connect.setForm(formName,true);
YAHOO.util.Connect.asyncRequest(‘POST’,target,callback);
/* Is there some event that triggers on an aborted file upload? */
/* YAHOO.util.Event.addListener(window, “abort”, function () { alert(‘abort’) } ); */
progress_win = new YAHOO.widget.Panel(“progress_win”, { width:”420px”, fixedcenter:false, underlay:”shadow”, close:false, draggable:true, modal:true, effect:{effect:YAHOO.widget.
ContainerEffect.FADE, duration:0.3} } );
progress_win.setHeader(“Uploading “+document.getElementById(‘test_file’).value+” …”);
progress_win.setBody(‘<div style=”height: 1em; width: 400px; border:1px solid #000;”> <div id=”pbar” style=”background: #99e; height: 98%; width:0%; float:left;”>&nbsp;</div> <div
id=”ppct” style=”height: 90%; position: absolute; margin: 1 0 0 185;”>0%</div></div><div id=”ptxt” style=”margin: 3 0 0 5″>0 of 0 bytes</div>’);
progress_win.render(document.body);
update_progress();
}
</script>
<!– Upload Progress Bar Scripting Code –>
[/code]

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@polorboyauthorFeb 06.2007 — Here is the rest (I actually maxed out the allow number of characters):

The Form code:
[code=html]
<form action="" onSubmit="postForm('upload.php','upload_form'); return false;"enctype="multipart/form-data" method="post" class="upload">
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo uniqid()?>"/>
<fieldset>
<legend>
Upload File
</legend>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>" />
<label for="numfiles">
Select the number of files you want to upload:&nbsp;
<select name="numfiles" id="numfile" onchange="updateInput()">
<option value="1" selected="selected">1</option>
<option value="2" >2</option>
<option value="3" >3</option>
<option value="4" >4</option>
<option value="5" >5</option>
<option value="6" >6</option>
</select>
</label>
<div id='divInput' style="margin:0.2em 0 0.2em 0;">
<label for="fileupload">
<input type="hidden" name="space_filler" />
</label>
</div>
<br />
<br />
<input type="submit" name="upload" value="Upload" id="upload" />
</fieldset>
</form>
[/code]


Based on the above snippets of code, my form does work but I am still not seeing a progress bar, and when I do get to my success page it is just loading a blank page. Whereas before it was loading my actual success.php page. The success.php page has not changed and has worked in the past when I didn't try to do this progress bar. I am really hoping someone can take a look at this and help me get to some kind of solution. I am not looking for someone to give me the answer, just help in finding one.
×

Success!

Help @polorboy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...