Uploading Image one by one - php

hi guys I have codes here that allow you to choose image and preview it right away. But i have problem when choosing an image in one by one because when I go to the next page I just get only the last image that I selected. How can I save all the images that selected one by one in an array and pass it to the next page. Its working when you are selecting multiple images in once but then in one by one it just get the last image.
<div id='upload' style="margin-left:5px;border-radius:5pt;background:#fff;width:710px;height:230px;color:white;font-size:11pt;font-weight:bolder">
<div id="list" style="float:left;width:700px;height:auto"></div>
</div>
<div style='margin-top:15px;margin-left:20px;float:left;width:700px;'>
<form method="post" action="index.php?pg=preview" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple />
<input id="but" type="submit" name="cancel" value="Cancel" onclick="history.go(-1)"style="margin-left:225px" ></input>
<input id="but" type="submit" name="next" value="Next"></input>
</form>
</div>
</div>
<script>
function check()
{
$("#show").show();
$("#show").load('check_image.php');
}
var x = 0;
var y = 0;
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
var name = files.item(0).name;
//alert(name);
if(x > 9)
{
alert('Total of 10 Images are acceptable');
}
else
{
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<div id="image"><img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/></div>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
y = i + x;
x = 0 + y;
i = 0;
}
document.getElementById('files').addEventListener('change', handleFileSelect, true);
</script>
<?php
$photo[] = '';
for($i=0; $i<count($_FILES['files']['name']); $i++)
{
if(isset($_FILES["files"]["name"]))
{
if ((($_FILES["files"]["type"][$i] == "image/gif")||
($_FILES["files"]["type"][$i] == "image/jpeg")||
($_FILES["files"]["type"][$i] == "image/jpg")||
($_FILES["files"]["type"][$i] == "image/png")||
($_FILES["files"]["type"][$i] == "image/pjpeg"))&&($_FILES["files"]["size"][$i] < 10000000))
{
if ($_FILES["files"]["error"][$i] > $i)
{
echo "Error: ".$_FILES["files"]["error"][$i]."<br />";
}
else
{
move_uploaded_file($_FILES["files"]["tmp_name"][$i],"pics/".$_FILES["files"]["name"][$i]);
$photo[$i] = "pics/".$_FILES["files"]["name"][$i];
}
}
else
{
$photo[$i]="";
}
}
}
?>

You can modify your code like this:
<form method="post" action="index.php?pg=preview" enctype="multipart/form-data">
$picture_count = 10;
for($i = 0; $i<10;++$i){?>
<input type="file" id="files" name="files[]" 0) echo 'style="display:none;"'?>/>
<input id="but" type="submit" name="cancel" value="Cancel" onclick="history.go(-1)"style="margin-left:225px" ></input>
<input id="but" type="submit" name="next" value="Next"></input>
</form>
<script>
function check() {
$("#show").show();
$("#show").load('check_image.php');
}
var x = 0;
var y = 0;
var j = 0;
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) { </p>
var name = files.item(0).name;
//alert(name);
if(x > <?php echo $picture_count-1;?>)
{
alert('Total of 10 Images are acceptable');
} </p>
else
{
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<div id="image"><img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/></div>'].join('');
document.getElementById('list').insertBefore(span, null);
document.getElementById('files'+j).style.display = 'none';
document.getElementById('files'+(++j)).style.display = 'block';
};
})(f); </p>
// Read in the image file as a data URL.
reader.readAsDataURL(f);</p>
}
}
y = i + x;
x = 0 + y;
i = 0;
}
document.getElementById('files').addEventListener('change', handleFileSelect, true);
</script>
This code will upload all allowed files to the server.
$picture_count - the maximum count of images for upload.
But, I would advise you to use scripts like jquery.uploadify, it is handier and works with many browsers

Related

how to insert video path, video name in mysql database in php.?

I want to store video path and name in MySQL database but actually only stored the some fields information which i used in the form. and video stored the test upload folder
I have tried but video path(location) and name not store in database.
Here my code,
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br><br>
<input type="button" value="Upload File" onclick="uploadFile()">
</form>
Controller:
public function Insert_vedio()
{
$vedio_data=array(
'title'=>$this->input->post('Title'),
'v_name'=>$this->input->post('fileName'),
);
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
}
Actually I have not mention Title and name in view part. Here My actual code. name is video file name, but don't understand how to give the vedio name.
<form id="upload_form" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="e1"> Title</label>
<input type="text" placeholder="Movie Tile" name="Title" id="e1" class="form-control">
<input type="file" name="file1" id="file1"><br><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h6 id="status" style="color:red"></h6>
<p id="loaded_n_total"></p>
<div class="osahan-area text-center mt-3">
<button class="btn btn-outline-primary">Save Changes</button>
</div>
</div>
</form>
Here my Javascript
<script>
function _(el)
{
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
if(typeof file === "undefined") {
_("status").innerHTML = "ERROR: Please browse for a file before clicking the upload button";
_("progressBar").value = 0;
return;
}
$.get('Upload_vedio/Insert_vedio?getsize', function(sizelimit) {
if(file.type !== "video/mp4") {
var typewarn = "ERROR: You have to select a MP4-File";
_("status").innerHTML = typewarn;
_("progressBar").value = 0;
return;
}
if(sizelimit < file.size) {
var sizewarn = "ERROR: The File is too big! The maximum file size is ";
sizewarn += sizelimit/(1024*1024);
sizewarn += "MB";
_("status").innerHTML = sizewarn;
_("progressBar").value = 0;
return;
}
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("size", file.size);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "Upload_vedio/Insert_vedio");
ajax.send(formdata);
});
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
</script>

how to display real time record count of PHPexcel using Ajax?

I want to display real-time record count at front end using PHPexcel and Ajax. I am doing this by creating JSON file and storing data into this. Can I have a better option to show record count in the HTML? It is taking so much time AS the JSON file opening and closing so many times. At the same time, I am requesting this JSON and displaying data on the frontend. I am having this code and sharing you. Please let me know can I have a better option for the same.
File Name: Index.html
<div class="container">
<div class="row">
<h3>jQuery Ajax file upload with percentage progress bar</h3>
<form id="myform" method="post">
<div class="form-group">
<label>Select file: </label>
<input class="form-control" type="file" id="myfile" />
</div>
<div class="form-group">
<!--<div class="progress">
<div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
</div>-->
<div class="msg"></div>
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped active" id="progressbar" role="progressbar" style="width:0%">0%</div>
</div>
<h2 id="records"></h2>
<h2 id="consist"></h2>
<h2 id="hsn"></h2>
</div>
<input type="button" id="btn" class="btn-success" value="Upload" />
</form>
</div>
</div>
<script>
$(function () {
$('#btn').click(function () {
$('.myprogress').css('width', '0');
$('.msg').text('');
var filename = $('#filename').val();
var myfile = $('#myfile').val();
if (filename == '' || myfile == '') {
alert('Please enter file name and select file');
return;
}
var formData = new FormData();
formData.append('myfile', $('#myfile')[0].files[0]);
formData.append('filename', filename);
$('#btn').attr('disabled', 'disabled');
// $('.msg').text('Uploading in progress...');
$.ajax({
url: 'uploadscript.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
/*
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},*/
success: function (data) {
console.log(data);
var myData = JSON.parse(data);
console.log(myData.records.length);
$('#records').text("Records Found : " + myData.records.length).show();
$('#consist').text("Consistency : " + (myData.records.length - myData.notConsist.length)).show();
//$('.msg').text(data);
$('.msg').html(`<div class="alert alert-success"><strong>Success!</strong> Upload successfully!</div>`);
$('#btn').removeAttr('disabled');
$('.progress').hide();
}
});
t = setTimeout("updateStatus()", 3000);
});
});
function updateStatus(){
$.getJSON('upload/my.json', function(data){
var items = [];
pbvalue = 0;
var notExistHSN = 0;
var consistency = 0;
var notConsist = 0;
if(data){
var total = data['total'];
var current = data['current'];
console.log(current);
var pbvalue = Math.floor((current / total) * 100);
if(pbvalue>0){
$('#progressbar').text(pbvalue + '%');
$('#progressbar').css('width', pbvalue + '%');
//console.log(pbvalue);
}
$('#records').text("Records Found : " + current).show();
}
if(pbvalue < 100){
t = setTimeout("updateStatus()", 3000);
}
}).fail(function() {t = setTimeout("updateStatus()", 3000)});
}
</script>
File Name : uploadscript.php
<?php
error_reporting(E_ERROR | E_PARSE);
$target_dir = 'upload/';
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file);
require('Classes/PHPExcel.php');
require_once "Classes/PHPExcel/IOFactory.php";
$path = $target_file;
$fileObj = PHPExcel_IOFactory::load( $path );
$sheetObj = $fileObj->getActiveSheet();
$startFrom = 1; //default value is 1
$limit =null;
$header=array();
foreach( $sheetObj->getRowIterator($startFrom, $limit) as $row ){
foreach( $row->getCellIterator() as $cell ){
$value = $cell->getCalculatedValue();
array_push($header,$value);
}
break;
}
$highestRow = $sheetObj->getHighestRow();
$arr = array('total'=>($highestRow-1), 'current'=>'0', 'notConsist'=>'0',
'hsn'=>'0');
file_put_contents("upload/my.json",json_encode($arr));
$startFrom = 2;
$limit =count($header);
$i=1;
$outp = "";
foreach( $sheetObj->getRowIterator($startFrom, $limit) as $row ){
if ($outp != "") {$outp .= ",";}
foreach( $row->getCellIterator() as $key=>$cell){
// get all total count
$arr['current'] = "$i";
file_put_contents("upload/my.json",json_encode($arr));
$value = $cell->getCalculatedValue();
if($key==0){$outp .= '{"'.$header[$key].'":"'. $value. '",';}
else
if($key==($limit-1)){$outp .= '"'.$header[$key].'":"'. $value. '"}';
}
else {
$outp .= '"'.$header[$key].'":"'. $value. '",';
}
}
$i++;
}
$outp ='{"records":['.$outp.']}';
echo $outp;
?>

JQuery AJAX file upload responseText is not displaying

I have created a jQuery/AJAX script for file uploading and I handle the upload with PHP. It works perfectly with a progress bar and validations. There is one issue however, I cannot get any response text that I have set in PHP and encoded it using json_encode();, but don't get any response and get this instead:
<div class="upload-div">
<form method="post" enctype="multipart/form-data" class="upload_form" >
<label for="file" id="file_label" class="file-label"><i class="fa fa-plus"></i> إضافة صور<input type="file" name="files[]" id="file" multiple="" accept="image/*" /></label>
<input type="submit" id="upload_files" name="submitUpload" value="رفع الصور" />
</form>
<div class="progress">
<div class="bar"></div>
</div>
<div class="status-message"></div>
<div class="images-previews"></div>
<div id="next_step"></div>
<span class="submit-buttons">
<i class="fa fa-arrow-right"></i> الرجوع
<form method="post"><input type="submit" name="submitNoPics" value="التقدم بدون صورة" /></form>
</span>
</div>
<script src="js/upload.js"></script>
<script src="js/jquery.form.min.js"></script>
{"message":"Successfully uploaded 1 files!"}
As you can see the message I want to display is on the last line of code but it doesn't show alone. It shows with the whole HTML document. I will post my HTML and PHP code below, because I am new to Ajax and I am struggling. Please help me if you can and explain because I don't just want to get it done, I want to actually understand how and why this is not working. Thank you.
PHP:
<?php
//file upload
$extensions = array('jpeg', 'jpg', 'png', 'gif');
$dir = 'user-uploads/';
$count = 0;
$imgCounter = 1;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files'])){
for($x = 1; $x <= 8; $x++){
unlink('user-uploads/img'.$listingID.'-'.$x.'.jpg');
unlink('user-uploads/img'.$listingID.'-'.$x.'.png');
unlink('user-uploads/img'.$listingID.'-'.$x.'.gif');
}
mysqli_query($connectionDB, "DELETE FROM ad_image_tbl WHERE ad_id = $listingID");
// loop all files
foreach ( $_FILES['files']['name'] as $i => $name ){
// if file not uploaded then skip it
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
/* skip unprotected files
if( !in_array(pathinfo($name, PATHINFO_EXTENSION), $extensions) )
continue;
*/
switch($_FILES['files']['type'][$i]){
case 'image/jpeg' : $ext = '.jpg'; break;
case 'image/png' : $ext = '.png'; break;
case 'image/gif' : $ext = '.gif'; break;
default : $ext = '';
}
if($ext == ''){
echo errorMessage('<li>الملف المرفق لا يعتبر صورة</li>');
$error_message = 'الملف المرفق لا يعتبر صورة';
$message = array('message'=>'Attached file is not a valid image file.');
exit();
}
else{
// now we can move uploaded files
if($count <= 7 ){
$listingImage = $dir.'img'.$listingID.'-'.$imgCounter.$ext;
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $listingImage))
mysqli_query($connectionDB, "INSERT INTO ad_image_tbl VALUES('$imgCounter', '$listingID', '$listingImage')");
$imgCounter++;
$count++;
}
}
}
$message = array('message'=>'Successfully uploaded '.$count.' files!');
echo json_encode($message);
}
?>
jQuery/AJAX:
$(function() {
/* variables */
var fileInput = document.getElementById('file');
var fileCount = fileInput.files.length;
if(fileCount > 8){
fileCount = 8;
}
var bar = $('.bar');
var progress = $('.progress');
/* submit form with ajax request using jQuery.form plugin */
$('.upload_form').ajaxForm({
/* set data type json */
dataType:'JSON',
/* reset before submitting */
beforeSend: function() {
bar.width('0%');
progress.css('display', 'block');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
},
/* complete call back */
complete: function(message){
// var responseMessage = $.parseJSON(data.responseText);
progress.css('display', 'none');
document.getElementById('next_step').innerHTML = '<form method="post"><input type="submit" name="uploadSubmit" value="الانتهاء" /></form>';
console.log(message)
}
});
});
Why could you use a plugin to handle upload.
dropzone.js
You can get response as below
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
alert(response);
}
};
});

send 2 request with 1 ajax

I have little problem.
this is my html
<div class="row" style="margin-bottom: 10px;">
<div class="col-xs-1">
<span class="upload-excell btn btn-success" id="uploadExcellBtn"><i class="fa fa-upload"></i> Import Excel</span>
<div class="progress hidden" id="progress">
<div id="progressbat" class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em; width: 0;">
0%
</div>
</div>
</div>
<div class="col-xs-4">
<input class="form-control filter" type="search" title="filter" placeholder="Search...">
</div>
<div class="col-xs-7"></div>
</div>
<form class="Upload-form hiddenfile" method="post" enctype="multipart/form-data" action='upload url'>
<input type="hidden" name="csrf_token" value="<?php echo $this->session->csrf_token; ?>" />
<input type="file" name="file" class="excel-file"/>
</form>
this is my ajax
var $PROGRESS_BAR = document.getElementById('progressbat'),
progres = document.getElementById('progress');
$(document).on('submit', '.Upload-form', function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded / evt.total * 100);
$PROGRESS_BAR.style.width = percentComplete + '%';
$PROGRESS_BAR.innerHTML = percentComplete + '%';
}
}, false);
return xhr;
},
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
beforeSend: function(){
uploadExcellBtn.className = "upload-excell btn btn-success hidden";
progres.className = "progress";
$PROGRESS_BAR.style.width = '0%';
$PROGRESS_BAR.innerHTML = '0%';
},
success:function(){
$PROGRESS_BAR.style.width = '0%';
$PROGRESS_BAR.innerHTML = '0%';
$PROGRESS_BAR.className = "progress-bar progress-bar-success";
},
complete: function () {
var xhr2 = new XMLHttpRequest();
xhr2.open("GET", "new url", true);
xhr2.onerror = function() { console.log('[XHR] Fatal Error.'); };
xhr2.onreadystatechange = function() {
if (xhr2.readyState > 2){
var responseInfo = xhr2.responseText.replace(/}/g, '}/').split("/").clean(undefined);
for(var $i = 0; $i < responseInfo.length; $i++){
var parsedinfo = JSON.parse(responseInfo[$i]),
load = parseInt(parsedinfo.loaded);
if(load > loaded){
loaded = load;
percentage = Math.round(load / parseInt(parsedinfo.total) * 100);
$PROGRESS_BAR.style.width = percentage + '%';
$PROGRESS_BAR.innerHTML = percentage + '%';
}
}
}
if (xhr2.readyState == 4){
percentage = 0;
$PROGRESS_BAR.style.width = '0%';
$PROGRESS_BAR.innerHTML = '0%';
$PROGRESS_BAR.className = "progress-bar progress-bar-danger";
progres.className = "progress hidden";
uploadExcellBtn.className = "upload-excell btn btn-success";
refresh();
}
};
xhr2.send();
},
error: function(data){
console.log("error");
console.log(data);
}
});
return false;
});
I think it is possible to clean this code... as you understand in the first I have file upload and after complete I need to send request for reading this file it is reading on server side very well but I can not response my progress bar after upload complete.
this is my php function for uploading file
$excell = $_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($excell) {
$filename = stripslashes($_FILES['file']['name']);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
if ($extension == ("xlsx" || "xls")) {
$newname = $this->Conf->root_dir."/uploads/".Generate::string(5).".$extension";
$this->Session->new_file = $newname;
move_uploaded_file($uploadedfile, $newname);
echo true;
} else {
echo ' It is not Excell ';
}
} else {
echo ' error on upload ';
}
and this code is for reading
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
$xlsx = #(new SimpleXLSX($this->Session->new_file));
$data = $xlsx->rows();
$totalitems = count($data);
$lastkey = $totalitems - 1;
$current = 0;
foreach ($data as $key => $val) {
$current++;
if ($key == 0 || $key == $lastkey) continue;
// here I`m inserting in tho database
sleep(1);
$response = array(
'loaded' => $current,
'total' => $totalitems
);
echo json_encode($response);
}
sleep(1);
unlink($this->Session->new_file);
unset($this->Session->new_file);
$response = array(
'loaded' => $totalitems,
'total' => $totalitems
);
echo json_encode($response);
response for upload is working very well
but reading response not working...
I resolved this problem with jquery ajax..
with xhr parameter...

Tracking upload progress

I want to track the upload progress of a file to my server so I read this (German) article. I already checked my PHP.ini:
session.upload_progress.enabled = 1
session.upload_progress.cleanup = 1
session.upload_progress.prefix = upload_progress_
session.upload_progress.name = PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.freq = 1%
session.upload_progress.min_freq = 1
upload_max_filesize = 128M
I began to write a very simple script that only shows a form and uploads a file, when submitted:
<!-- upload.php -->
<?php
session_start();
$maxSize = 10485760;
$uploadName = "test";
if (#$_POST["upload"] ?: 0) { // Check, if upload is in progress
$t = getcwd() . "\\" . basename($_FILES["file"]["name"]);
if ($_FILES["file"]["size"] > $maxSize) {
echo "Upload " . (move_uploaded_file($_FILES["file"]["tmp_name"], $t) ? "succeeded" : "failed"); // Return, if upload is succeeded or failed
}
} else {
?>
<form action="<?= basename(__FILE__); ?>" enctype="multipart/form-data" id="frmUpload" method="POST" target="upload">
<input name="file" type="file" />
<input type="submit" value="Upload" />
<input name="MAX_FILE_SIZE" type="hidden" value="<?= $maxSize; ?>" />
<input name="upload" type="hidden" value="1" />
<input name="<?= ini_get("session.upload_progress.name"); ?>" type="hidden" value="<?= $uploadName; ?>" /> <!-- Set session name -->
</form>
<div style="display: none; ">
<iframe id="upload"></iframe>
</div>
<?php
}
?>
My second script should check the upload progress with the session name
// uploadProgress.php
<?php
session_start();
$pName = ini_get("session.upload_progress.prefix") . "test";
echo json_encode(#$_SESSION[$pName] ?: []);
?>
I created a 10mb file, to ensure a long upload time. Everytime I call uploadProgress.php while the upload is running $_SESSION[$pName] is not set and I cannot find my mistake. Is there something I overlooked or something I made wrong?
Forgive me as I'm not used to the syntax you're using... Not sure why you're using ternary operators in your IF statements, or why you're suppressing the $_SESSION and $_POST variables.
The only thing that stands out to me in your examples is I don't see any call to session_start()?
Here is another article that may help.
Solved the problem. Found a way to track the progress with JavaScript. Here is my solution:
/**********************\
| Script of upload.php |
\**********************/
var ui = { elems: ["dUploads", "fFile", "frmUpload", "pbPercent", "pbUpload", "pbWrpUpload"] }; for (var n = 0; n < ui.elems.length; n++) { ui[ui.elems[n]] = document.getElementById(ui.elems[n]); } delete ui.elems;
function refreshUploads (files) {
var tmp;
while (tmp = dUploads.firstChild) {
tmp.remove();
}
for (var file in files) {
var a = document.createElement("a");
a.setAttribute("href", "uploads/" + files[file]);
a.setAttribute("target", "_blank");
a.appendChild(document.createTextNode(files[file]));
var div = document.createElement("div");
div.appendChild(a);
ui.dUploads.appendChild(div);
}
}
ui.frmUpload.onsubmit = function (e) {
e.preventDefault();
var ajax = new XMLHttpRequest();
var data = new FormData();
data.append("ajax", 1);
data.append("file", ui.fFile.files[0]);
ajax.upload.onprogress = function (e) {
var percent = Math.floor(e.loaded / e.total * 100) + "%";
ui.pbUpload.style.left = percent;
ui.pbPercent.style.left = percent;
ui.pbPercent.innerHTML = percent;
};
ajax.onreadystatechange = function (e) {
if (ajax.readyState == 4 && ajax.status == 200) {
ui.pbWrpUpload.style.opacity = "0";
refreshUploads(eval(ajax.responseText));
}
};
ui.pbWrpUpload.style.opacity = "1";
ajax.open("POST", "upload.php", true);
ajax.send(data);
};
refreshUploads([]); // Normally all already existing files are loaded via PHP

Categories