Tracking upload progress - php

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

Related

Google API returns Nothing when uploaded file greater than approx 30MB using PHP

Why my PHP code returns nothing while uploading file greater than 30MB approx, but it works on localhost the problem is in Server Side. Sometime it says 503 error or err: NET CONNECTION RESET.
but mostly returns nothing.
when i upload file that are less than 25MB they get uploaded pretty quietly.
And also if someone can help me with the progress bar while data is been uploading in drive , in my code the progress is showing but after the file is been uploaded, not while uploading(I read about the getURI and ... but didn't understood properly) can anyone guide me here too?
I am using V3 of Google-drive-api.
INDEX.php
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Google Drive Example App</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
$(function () {
$('#btn').click(function () {
$('.myprogress').css('width', '0');
$('.msg').text('');
var filename = $('#filename').val();
var myfile = $('#myfile').val();
var discription = $('#discription').val();
if (filename == '' || myfile == '') {
alert('Please enter file name and select file');
return;
}
var formData = new FormData();
formData.append('pdf', $('#myfile')[0].files[0]);
formData.append('name', filename);
formData.append('discription', discription);
$('#btn').attr('disabled', 'disabled');
$('.msg').text('Uploading in progress...');
$.ajax({
url: 'action.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
// this part is progress bar
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) {
$('.msg').text(data);
$('#btn').removeAttr('disabled');
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<h3>File Upload</h3>
<form id="myform" method="post">
<div class="form-group">
<label>File name: </label>
<input class="form-control" type="text" id="filename" />
</div>
<div class="form-group">
<label>File Discription: </label>
<input class="form-control" type="text" id="discription" />
</div>
<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>
<input type="button" id="btn" class="btn-success" value="Upload" />
</form>
</div>
</div>
</body>
</html>
ACTION.php
<?php
ini_set('upload_max_filesize', '1000M');
ini_set('post_max_size', '1000M');
set_time_limit(5000);
if(isset($_FILES['pdf']) && isset($_POST['name'])){
$name = $_POST['name'];
if($name == ''){
echo "file name is Empty";
}else{
$discription = $_POST['discription'];
$target_dir = "files/";
$file_name = basename($_FILES["pdf"]["name"]);
$filesize = $_FILES['pdf']['size'];
$FileType = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
$file = "test_file.".$FileType;
$file_path = $target_dir . $file;
$tmpname = $_FILES['pdf']['tmp_name'];
$upload = move_uploaded_file($tmpname, $file_path);
if($upload == true){
include_once __DIR__ . '/google-api-php-client-master/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('credentials.json');
$client->addScope('https://www.googleapis.com/auth/drive.file');
$service = new Google_Service_Drive($client);
$service = new Google_Service_Drive($client);
$client->getAccessToken();
$file = new Google_Service_Drive_DriveFile();
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$parentId = "PARENT_FOLDER_ID";
$file->setParents(array($parentId));
$mime_type = finfo_file($finfo, $file_path);
$file->setName($name);
$file->setDescription($discription);
$response = $service->files->create($file);
// Create a media file upload to represent our upload process.
$media = new Google_Http_MediaFileUpload(
$client,
$response,
$mime_type,
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($file_path));
function readVideoChunk ($handle, $chunkSize){
$byteCount = 0;
$giantChunk = "";
while (!feof($handle)) {
$chunk = fread($handle, $chunkSize);
$byteCount += strlen($chunk);
$giantChunk .= $chunk;
if ($byteCount >= $chunkSize)
{
return $giantChunk;
}
}
return $giantChunk;
}
// Upload the various chunks. $status will be false until the process is complete.
$status = false;
$handle = fopen($file_path, "rb");
while (!$status && !feof($handle)) {
// An example of a read buffered file is when reading from a URL
$chunk = readVideoChunk($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
//if want to show the progress bar too but not working while uploading , but it shows the uploaded chunks after the files is been uploaded.
if(!$status){ //nextChunk() returns 'false' whenever the upload is still in progress
echo 'sucessfully uploaded file up to byte ' . $media->getProgress() . ' which is ' . ( $media->getProgress() / $chunkSizeBytes ) . '% of the whole file';
}
}
$result = false;
if ($status != false) {
$result = $status;
}
$file_id = $status['id'];
fclose($handle);
// Reset to the client to execute requests immediately in the future.
$client->setDefer(false);
//i am manually creating the wbViewLink by the ID i am getting in response
$webViewLink = "https://drive.google.com/file/d/$file_id/view?usp=drivesdk";
$myobj = new StdClass();
$myobj->{'alt_link'} = $webViewLink;
$myobj->{'size'} = $filesize;
print_r($myobj);
}else{
echo "upload failed";
}
}
}
?>
Can anyone Help me here ?
I am using service account as you can see to Authenticate the user on my behalf...
when everything is fine then result is something like this{image}
but when i upload file then is greater then 30MB result (only on server, on localhost is works fine) {image}
also you can see in the 2nd image the status in OK but still no response.
You can't always override upload size setting with ini_set, depending on hosting provider. Try this in your .htaccess:
php_value upload_max_filesize 100M
php_value post_max_size 100M

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

How to post all file in the list? | Jquery - PHP

I have a script (index.php) to create a list of all added files from "browse file" button. And I have a script (process.php) to send all files on the list to email with phpmailer.
My problem is, only file(s) at the last click that sent. File(s) that have been added previously unsent.
index.php script
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<form id="data" action="process.php" method="POST" enctype="multipart/form-data">
<input id="file" type="file" name="files[]" multiple="multiple"/>
<div id="output"><ul></ul></div>
<input type="submit" name="submit" value="OK">
</form>
</body>
<script>
$("#file").change(function() {
var ele = document.getElementById($(this).attr('id'));
var result = ele.files;
for(var x = 0; x < result.length; x++){
var file = result[x];
$("#output ul").append("<li>" + file.name + "</li>");
}
});
</script>
</html>
process.php script
<?php
require 'mail/PHPMailerAutoload.php';
$to = 'destination#email.com';
$subject = 'Test';
if(isset($_POST['submit'])){
$attachment_name = $_FILES['files']['name'];
$attachment_type = $_FILES['files']['type'];
$attachment = $_FILES['files']['tmp_name'];
include 'smtp.php';
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->msgHTML('Tes');
foreach($attachment_name as $key => $att){
$nama_file = $attachment_name[$key];
$tmp_file = $attachment[$key];
$mail->addAttachment($tmp_file, $nama_file);
}
if (!$mail->send()) {
echo '<script>alert("Fail"); </script>';
} else {
echo '<script>alert("Success"); </script>';
}
}
?>
Assume you have success create multiple input tag for upload file. (using jquery)
And at the php side:
// first file
$_FILES['files']['name'][0];
$_FILES['files']['type'][0];
$_FILES['files']['tmp_name'][0];
// second file
$_FILES['files']['name'][1];
$_FILES['files']['type'][1];
$_FILES['files']['tmp_name'][1];
OR:
$total = count($_FILES['upload']['name']);
// Loop through all files
for($i = 0; $i < $total; $i++) {
$_FILES['files']['name'][$i];
//do what you want
}
Your current code is unsafe. Read the PHP docs on handling file uploads.
You can attach multiple files using a single file input tag if you set a multiple attribute on it, like this;
<input name="userfile[]" type="file" multiple="multiple">
The 'send_multiple_file_upload` example provided with PHPMailer handles this correctly. The inportant part is:
//Attach multiple files one by one
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}

Uploading files in to Files folder

I want to upload files in to webroot/files folder, but my controller doing nothing, is there any mistake ?
View file name: uploadfile.ctp
Controller name: UploadFileController.php
Model name: UploadFile.php
In my view file I have:
<div class="files">
<input type="file" name="files[]" /><br/>
</div>
<button type="button" class="plus">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php echo $this->Html->script('addFile');
addFile script :
$(document).ready(function() {
$(".plus").click(function() {
$(".files").append("<input type='file' name='files[]'/><br/>");
});
});
And my Controller, I think that a mistake is somewhere here :
public function uploadFile() {
$uploadedFile = $this->request->params['UploadFile']['files[]']['tmp_name'];
$dir = WWW_ROOT . 'files/';
if ( !is_dir( $dir ) ) {
mkdir($dir);
chmod( $dir , 777);
}
$fileName = 'file_' . date( 'Y_m_d_h_i_s', time() );
move_uploaded_file( $uploadedFile, $dir. $fileName);
}
I got one Notice to:
Notice (8): Undefined index: UploadFile [APP\Controller\UploadFileController.php, line 7]
Thank you for any clue !
Solution
View File (uploadfile.ctp) :
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
Controller (UploadFileController.php) :
class UploadFileController extends AppController {
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
//print_r($this->data); die;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
return false;
}
echo "Filename: $filename<br>";
}
}
}
}
Script (addFile.js) :
$(document).ready(function() {
var max_fields = 2;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x <= max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[]' id='uploadFilefiles'/><button href='#' class='remove_field'>Kustuta</button></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on kustuta text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});

Uploading Image one by one

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

Categories