How to upload file temporarily and then submit form? - php

See EDITED QUESTION BELOW
I am currently uploading file with following code. But I want to upload file temporarily and then want to submit form. I mean after selecting audiofile >> Click on upload button next to file upload field..>> Message= file uploaded successfully >> Then click on "Submit" Button to upload all data and temporarily uploaded file in mysql and audio file in related folder....
Currently , with this code I am unable to upload larger files. And after long wait, I get error message like "webpage in not available"
I tried php.ini and .htaccess file update for max_execution_time, upload_max_filesize etc... also mod_security is disabled on server...
PHP code :
<?php
session_start();
// Database connection
include("../include/function.php");
include("commonfiles/validate.php");
// Create an object for an class
$bsq=new bsq();
//use class function to connect the database
$bsq->connect_db();
//
$fileName = $_FILES["audio"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["audio"]["tmp_name"];
// Path and file name
$pathAndName = "uploadsaudio_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
$fileName1 = $_FILES["doc"]["name"];
$fileNameNew1 = preg_replace('/\s+/', '_', $fileName1);
$fileTmpLoc1 = $_FILES["doc"]["tmp_name"];
// Path and file name
$pathAndName1 = "uploadsaudiodoc_admin/".$fileNameNew1;
// Run the move_uploaded_file() function here
$moveResult1 = move_uploaded_file($fileTmpLoc1, $pathAndName1);
// Evaluate the value returned from the function if needed
$fileName2 = $_FILES["pdf"]["name"];
$fileNameNew2 = preg_replace('/\s+/', '_', $fileName2);
$fileTmpLoc2 = $_FILES["pdf"]["tmp_name"];
// Path and file name
$pathAndName2 = "uploadsaudioppt_admin/".$fileNameNew2;
// Run the move_uploaded_file() function here
$moveResult2 = move_uploaded_file($fileTmpLoc2, $pathAndName2);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$all_columns[]="file_subject";
$all_columns[]="full_name";
$all_columns[]="upload_date";
$all_columns[]="display_date";
$all_columns[]="message";
$all_columns[]="audio";
$all_columns[]="doc";
$all_columns[]="pdf";
$display=date('Y-m-d', strtotime("+1 Day"));
//Get All values to insert in to table
$all_values[]=addslashes($_POST["file_subject"]);
$all_values[]=addslashes($_POST["full_name"]);
$all_values[]=addslashes($_POST["upload_date"]);
$all_values[]=$display;
$all_values[]=addslashes($_POST["message"]);
$all_values[]=addslashes($pathAndName );
$all_values[]=addslashes($pathAndName1 );
$all_values[]=addslashes($pathAndName2 );
//=====================
$qry=$bsq->webdreaminsert("eo_uploadsaudio_by_admin",$all_columns,$all_values,'');
echo mysql_error();
header("location:upload_audiofile_for_downloading_list.php");
}
?>
And HTML Form code:
<form action="" method="post" enctype="multipart/form-data" name="addtwebinar1" id="addtwebinar1" onsubmit="javascript:return validateimage1();" >
<input type="hidden" value="add" name="action" />
1) Audio File Subject* : <input name="file_subject" id="file_subject" type="text" value="" />
2) File Owner Name : <input name="full_name" id="full_name" type="text" value="" />
3) Session Conducted On : <input type="text" autocomplete="off" name="upload_date" id="upload_date" placeholder="Click To Open calendar" readonly="readonly" />
4) Your Audio File For Upload : <label for="audio">Audio File To Upload: </label><br>
<input type="file" name="audio" id="audio" />
// Here I want temporary upload button with message "Upload successfully / Not Uploaded..." etc.....
5) Your Doc File For Upload : <label for="doc">Doc File To Upload: </label><br>
<input type="file" name="doc" id="doc" />
6) Your Question Answer File For Upload : <label for="pdf">Question Answer For Practice File To Upload: </label><br>
<input type="file" name="pdf" id="pdf" />
7) Message If Any : <textarea name="message" id="message" cols="" rows="3" placeholder="Message"></textarea>
<button>SUBMIT</button>
</form>
I want to add Upload Button Next to field number 4 where audio file will be uploaded temporarily and then after filling up other fields, form will be get submitted....
Or Any other solution to upload larger files ( around 40 to 50 MB size each) without any error with low internet speed ?
EDITED QUESTION :
I used ajax for file uploading..... Now file gets uploaded to folder even 26 MB But mysql database is not getting updated.....
I have edited HTML code as follow with javascript :
1) Audio File Subject* : <input name="file_subject" id="file_subject" type="text" value="" />
2) File Owner Name : <input name="full_name" id="full_name" type="text" value="" />
3) Session Conducted On : <input type="text" autocomplete="off" name="upload_date" id="upload_date" placeholder="Click To Open calendar" readonly="readonly" />
4) Your Audio File For Upload : <label for="audio">Audio File To Upload: </label><br>
<input type="file" name="audio" id="audio" />
// Here I want temporary upload button with message "Upload successfully / Not Uploaded..." etc.....
5) Your Doc File For Upload : <label for="doc">Doc File To Upload: </label><br>
<input type="file" name="doc" id="doc" />
6) Your Question Answer File For Upload : <label for="pdf">Question Answer For Practice File To Upload: </label><br>
<input type="file" name="pdf" id="pdf" />
7) Message If Any : <textarea name="message" id="message" cols="" rows="3" placeholder="Message"></textarea>
<button>SUBMIT</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"> </script>
<script src="source/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%' + '' + 'Completed...';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
window.location.href='upload_audiofile_for_downloading_list.php';
}
});
})();
</script>
And Code in upload_audiofile_process.php :
<?php
session_start();
include("../include/function.php");
include("commonfiles/validate.php");
include("fckeditor.php");
//=================================================================================
// Create an object for an class
$bsq=new bsq();
//use class function to connect the database
$bsq->connect_db();
$fileName = $_FILES["image"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image"]["tmp_name"];
// Path and file name
$pathAndName = "uploadsaudio_admin/".$fileNameNew;
// Evaluate the value returned from the function if needed
$fileName1 = $_FILES["doc"]["name"];
$fileNameNew1 = preg_replace('/\s+/', '_', $fileName1);
$fileTmpLoc1 = $_FILES["doc"]["tmp_name"];
// Path and file name
$pathAndName1 = "uploadsaudiodoc_admin/".$fileNameNew1;
// Evaluate the value returned from the function if needed
$fileName2 = $_FILES["pdf"]["name"];
$fileNameNew2 = preg_replace('/\s+/', '_', $fileName2);
$fileTmpLoc2 = $_FILES["pdf"]["tmp_name"];
// Path and file name
$pathAndName2 = "uploadsaudioppt_admin/".$fileNameNew2;
// Evaluate the value returned from the function if needed
if (isset($_FILES["image"])) {
if ($_FILES["image"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
move_uploaded_file($fileTmpLoc, $pathAndName);
move_uploaded_file($fileTmpLoc1, $pathAndName1);
move_uploaded_file($fileTmpLoc2, $pathAndName2);
$all_columns[]="file_subject";
$all_columns[]="full_name";
$all_columns[]="upload_date";
$all_columns[]="display_date";
$all_columns[]="message";
$all_columns[]="image";
$all_columns[]="doc";
$all_columns[]="pdf";
$display=date('Y-m-d', strtotime("+1 Day"));
//Get All values to insert in to table
$all_values[]=addslashes($_POST["file_subject"]);
$all_values[]=addslashes($_POST["full_name"]);
$all_values[]=addslashes($_POST["upload_date"]);
$all_values[]=$display;
$all_values[]=addslashes($_POST["message"]);
$all_values[]=addslashes($pathAndName );
$all_values[]=addslashes($pathAndName1 );
$all_values[]=addslashes($pathAndName2 );
//=====================
$qry=$bsq->webdreaminsert("eo_uploadsaudio_by_admin",$all_columns,$all_values,'');
echo mysql_error();
}
}
?>
This code is working for 10-15 MB file upload.... BUT if file is larger than 20 MB...NOT WORKING....

You can solve your problem with this way.
First call ajax function on your upload button.
$.ajax({
url: 'example.php',
type: 'POST',
data: fileData,
success: function(data) {
// set file name or file id in some field using jquery.
$('#fileHiddenFieldId').val(data);
// and then set css property 'display:block' for submit button.
$('#submitButtonId').css('display','block');
}
});
Here url example.php is filepath where you put your php file upload code.
'fileData' is your uploaded file data which you post.
When you get success response then set file id or file name in some hidden field then display submit button.

Related

how to upload at new name and section

I have a problem that made me lose my temper really I have the following code
OK ?
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
$type = $_FILES["vedio"]['type'];
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<div id="inputs">
<label class="labels" for="name">Vedio Name: </label>
<input id="name" type="text" name="vedionamet" value="vedio"> </br>
<label class="labels" for="selectsection">Select Section :</label>
<select name="selectsection" id="section" >
<?php
foreach($sections as $pathat){
echo "<option value='$pathat'>" . "$pathat" . "</option>";
};
?>
</select></br>
<label class="labels" for="upup">Select Vedio : </label>
<input id="upload" type="file" name="vedio"></br>
<input id="subb" type="submit" name="uploadsub" value="Upload">
</
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.
For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder
<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
//Use this to get the path
$finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
//Use this to get the extension of file name
$type = pathinfo($vedname, PATHINFO_EXTENSION);
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname.".".$type);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
}
?>

php wont give download link feedback after upload done

i'm trying to get DropzoneJS to work, i got far but it seems i've got a problem i can't solve.
so basicly what i want is to upload a file and get a download link back within the same page.
so i added this code to my index.php:
<form action="index.php" class="dropzone" id="my-awesome-dropzone"></form>
and the php code into the index.php:
<?php
include('config.php');
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$dirname = uniqid();
mkdir( $filedir.'/'.$dirname);
mkdir( $filedir.'/'.$dirname.'/file');
copy("template/d.php", "d/$dirname/index.php");
copy("template/dl.php", "d/$dirname/dl.php");
preg_match('/\.([a-zA-Z0-9]+?)$/', $_FILES['file']['name'], $matches);
if(in_array(strtolower($matches[1]), $accepted)) {
if($_FILES['file']['size'] <= $maxsize) {
$newname = ($_FILES['file']['name']);
// file name encryption
//$newname = md5_file($_FILES['file']['tmp_name']).'.'.$matches[1];
move_uploaded_file($_FILES['file']['tmp_name'], $filedir.'/'.$dirname.'/file/'.$newname);
$linkurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/([^\/]+?)$/', '/', $_SERVER['PHP_SELF']).'#'.$newname;
$imgurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/([^\/]+?)$/', '/', $_SERVER['PHP_SELF']).$filedir.'/'.$dirname.'/file/'.$newname;
$alt = $_POST["alt"];
$dlurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/([^\/]+?)$/', '/', $_SERVER['PHP_SELF']).$filedir.'/'.$dirname;
print '<h2>Picture Uploaded Successfuly!!!!</h2> <p id="codes">
<img src="'.$imgurl.'" height="300" alt="Uploaded Picture" >
<label for="codebb">BBCode:</label>
<input type="text" id="codebb" value="[URL='.$siteurl.'][IMG]'.$dlurl.'[/IMG][/URL]" onclick="javascript:this.focus();this.select();" readonly="true" /><br />
<label for="codehtml">HTML Code: </label>
<input type="text" id="codehtml" value=\'<a href="'.$siteurl.'"><img src="'.$dlurl.'" alt="'.$alt.'" />&lt/a>\' onclick="javascript:this.focus();this.select();" readonly="true" /><br />
<label for="codedirect">Direct Link:</label>
<input type="text" id="codedirect" value="'.$dlurl.'" onclick="javascript:this.focus();this.select();" readonly="true" /></p>';
echo ".$newname";
} else
print '<p>Sorry, Max Picture size is 10Mb</p>';
}
}
?>
when i upload the file the php works and the file is uploaded successfully into its folder so the php is working.
my problem now is why dont i get the print from the php script.
fully working script:
http://37.34.62.131/test/uploader%201.0/
not working NEW script:
http://37.34.62.131/test/
i think it has something to do with the uploader because my old script uses a submit button and my newer version is using a automatic submit.
i very appreciate your time!

PHP-Jquery image upload not working

I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**
you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image
That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot

Uploading multiple files to FTP server using jquery.MultiFile

I have a problem conserning uploading multiple files to my ftp server and I am using jQuery's multifile extension.
This is the multifile javascript code on page with the upload form (file_upload.php):
<script type="text/javascript">
$(function(){ // wait for document to load
$('.remove').MultiFile({
STRING: {
remove: '<img src="images/upload-remove.png" height="16" width="16" alt="x"/>',
denied:'You can't choose file $ext .\nTry again...',
file:'$file',
selected:'Chosen file: $file',
duplicate:'This file is already chosen:\n$file'
}
});
});
</script>
And this is the HTML form (file_upload.php):
<form name="uploader" action="file_upload2.php" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Upload file:</label>
<br />
<input type="file" class="multi, remove" name="file[]" value="Upload file" />
<input type="submit" value="submit"/>
</fieldset>
</form>
The PHP part is where I don't get it. I tried to do it with this code (file_upload2.php):
<?php
if(isset($_POST['submit']))
{
$ftp_config['server'] = 'ftpserver.org'; //ftp host
$ftp_config['username'] = 'ftp_username'; // ftp username
$ftp_config['password'] = 'ftp_password'; // ftp user password
$ftp_config['web_root'] = 'public_html'; //foldername from user home dir.
$fileElementName = 'file[]'; //file field name
$conn_id = ftp_connect($ftp_config['server']);
$ftp_login = ftp_login($conn_id,$ftp_config['username'],$ftp_config['password']);
if(!ftp_put($conn_id,$ftp_config['web_root'].'/'.$_FILES[$fileElementName]['name'],$_FILES[$fileElementName]['tmp_name'],FTP_BINARY)){
$result = " Error occurred. ";
}else{
$result = " File has been uploaded. ";
}
echo $result;
}
?>
You have to loop through $_FILES for each file that was uploaded.
Do a print_r($_FILES); to see what you have to work with.

PHP Remote Image Process to save image on my server using the Picup App for mobile safari

I can't get the image to save in the /image_upload/uploads/ folder (then I can hopefully figure out the rest).
This is the code I got from parorrey.com
<?php
//remote image to copy
$remoteImageURL = 'http://www.mywebsite.com/image.jpg'; //I'm not sure what URL should be here
//local directory to store image
$dir_path = 'http://www.mywebsite.com/image_upload/uploads/';
if($remoteImageURL)
{
require_once('class.get.image.php');
// initialize the class
$image = new GetImage;
// just an image URL
$image->source = $remoteImageURL;
$image->save_to = $dir_path; // with trailing slash at the end
$get = $image->download('curl'); // using cURL
$pic = $dir_path.basename($remoteImageURL);
//you can use the picture path e.g. Insert into DB from this variable $pic
?>
This is some of the code for the PICUP application
<script>
var currentParams = {}
document.observe('dom:loaded', function()
{
$(document.body).addClassName('iphone');
// We'll check the hash when the page loads in-case it was opened in a new page
// due to memory constraints
Picup.checkHash();
// Set some starter params
currentParams = {
'callbackURL' : 'http://mywebsite.com/upload_pic5.php',
'postURL' : 'http://www.mywebsite.com/image_upload/picup_remote_image.php',
'referrername' : escape('mywebsite'),
'referrerfavicon' : escape('http://mywebsite.com/kwboat.ico'),
'purpose' : escape('Select your photo for our App.'),
'debug' : 'false',
'returnThumbnailDataURL': 'true',
'thumbnailSize' : '150'
};
Picup.convertFileInput($('photo'), currentParams);
});
</script>
<script type="text/javascript">
window.name = "fileupload";
</script>
This is my form code
<form action="save.php" method="post" id="add_boat">
<div class="step_bar_info">Upload a Picture of your boat</div>
<div id="image_box">
<div id="upload_area">
<?php if (isset($image_url))
{
echo '<img src="' . $image_url .'" />';
}
else
{
echo '<img src="images/boat.png" width="150px"/>';
} ?>
</div>
<input type="file" name="photo" id="photo"/><br />
Please select your photo to upload, you will need to install Picup App (Free) from iTunes. <br /><br /> Picup is a free iPhone app that facilitates photo uploads to our web app. Since Mobile Safari doesnt support file-upload form fields
<?php $image_url=($pic); ?><!-- gets from image processor though maybe should just change $pic -->
</div><!--image box-->
<input type="hidden" id="image_url" name="image_url" value="images/boat.png"/>
<div id="titlebox">Boats name<br/><input name="title" type="text" size="24" maxlength="60" value="" tabindex="1"></div><!--endtitlebox-->
<div id="info_box">Info<br/><textarea name="info" cols="20" maxlength="100" rows="2" tabindex="6"></textarea></div>
<input id="add_boat" type="submit" name="add_boat" value="save " alt="submit" title="Save item in our secure database system " />
</form>
Just from looking at your code I would like to say. If your choose file button is not showing up on your form.
In the picup currentParams. Picup.convertFileInput($('photo'), currentParams);
"photo" is intended to be your id="" name="" not "image_url"
Try
// initialize the class
$image = new GetImage();
Or its a typo?

Categories