multiple upload's title not saved to database - php

I am sorry but these solutions din't solved my purpose. So m giving more detail of my code,
var a=0;
function _add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\"><br><input type=\"text\" name=\"text[]\">";
document.getElementById("dvFile").innerHTML += txt;
alert(a);
a=a+1;
}
here i have used a to increement title.
function upload(){
if(count($_FILES["item_file"]['name'])>0) { //check if any file uploaded
$GLOBALS['msg'] = ""; //initiate the global message
for($j=0; $j < count($_FILES["item_file"]['name']); $j++) { //loop the uploaded file array
$filen = $_FILES["item_file"]['name']["$j"]; //file name
$path = 'uploads/'.$filen; //generate the destination path
$text=$_POST['text']['name']["$j"] + "<br>";
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path)) {
$insert=mysql_query("insert into image_upload set title='".$text."', image='".$filen."'") or die(mysql_error());
//upload the file
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>"; //Success message
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload"; //Failed message
}
uploadForm(); //display the main form
}
this is what i have done. Please help me to get title for each uploaded file. as i am able to save different images in database but title appears to be same for all in database.

Try this:
$text=$_POST['text'][$j];

Related

How to copy the set of files from one folder to another folder using php

I want to copy set of uploaded files from one folder to another folder.From the below code, all the files in one folder is copied.It takes much time. I want to copy only the currently uploaded file to another folder.I have some idea to specify the uploaded files and copy using for loop.But I don't know to implement.I am very new to developing.Please help me.Below is the code.
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
To copy only the uploaded files, there is only a slight change in the coding which I have made. That is instead of using "." from one folder, I passed the array value. So that only the files which are uploaded will be copied to the new folder instead of copying everything which takes long time.Below is the only change made to do:
$files = glob("test_uploads/$name_arrray[$i]");

How to retrieve file name from php and putting it in JS

I have a JavaScript function below where it displays a message after file uploading is complete:
function stopVideoUpload(success) {
var namevideofile = $('.fileVideo').val();
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listVideo').append(namevideofile + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}​
Below is the php script which is on another page which successfully uploads the files:
if( file_exists("VideoFiles/".$_FILES['fileVideo']['name'])) {
$parts = explode(".",$_FILES['fileVideo']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileVideo']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileVideo"]["tmp_name"],
"VideoFiles/" . $_FILES["fileVideo"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileVideo"]["tmp_name"],
"VideoFiles/" . $_FILES["fileVideo"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result;?>);</script>
Now except having var namevideofile to retrieve the value from the file input value (.fileVideo is the class for the file input), what I want it to do is that when the uploading is complete, the name given to file in the server would be var namevideofile. So if I have 2 files known as video.png, as I stated in my php code that if file exists then add a number to end of file name so that would create video.png and video1.png in server.
So when I append namevideofile, it should display video.png and video1.png after uploading is completed for both files. The problem with var namevideofile = $('.fileVideo').val();, is that it displays both file names as video.png which is incorrect.
So does anyone know how to change var namevideofile so that it retrieves the file name from the server after uploading? The issue is that the php script is on a separate page (videoupload.php) to the JS function (QandATable.php) so does ajax need to be involved here or not.
Anyone who could provide an example of how this can be coded would be very helpful to me :)
you can echo and store the value in a javaScript variable:
var namevideofile = <php echo $filename; ?>;

Insert the form values from an array into a database

I have created a form that allows a user to upload multiple files to a directory. Now I am trying to grab the names of the files from the form input fields and store them into a database.
I am trying to get the array values of the input fields ie; the ['file']['name'] and the ['file']['tmp_name'] and insert them into a database. With the below code I have only managed to get the word "array" to be inserted into the database and not the actual names of the files themselves.
I think I need to loop through the array using a foreach loop but I am uncertain as to how to go about writing it and where to insert it into my code. Below is the code so far:
#connect to the database
mysql_connect("localhost", "root", "");
mysql_select_db("masscic");
//Upload Handler to check image types
function is_image($file) {
$file_types = array('jpeg', 'gif', 'bmp'); //acceptable file types
if ($img = getimagesize($file)){
//echo '<pre>';
//print_r($_FILES); //will return an array of information for testing
//print_r($img); //will return an array of information for testing
if(in_array(str_replace('image/', '', $img['mime']), $file_types))
return $img;
}
return false;
}
//form submission handling
if(isset($_POST['submit'])) {
//file variables
$fname = $_FILES['files']['name'];
$ftype = $_FILES['files']['type'];
$fsize = $_FILES['files']['size'];
$tname = $_FILES['files']['tmp_name'];
$ferror = $_FILES['files']['error'];
$newDir = '../uploads/'; //relative to where this script file resides
for ($i = count($fname) -1; $i >=0; $i--) {
if ($ferror[$i] =='UPLOAD ERR OK' || $ferror[$i] ==0)
{
if(is_image($tname[$i]))
{
move_uploaded_file($tname[$i], ($newDir.time().$fname[$i]));
echo '<li><span class="success">'.$fname[$i].' -- image has been accepted<br></span></li>';
}else
echo '<li><span class="error">'.$fname[$i].' -- is not an accepted file type<br></span></li>';
}
}
}
$sqlInsert = mysql_query("INSERT INTO files (file_names) VALUES('$fname')") or die (mysql_error());
Thanks for any help.
When uploading multiple files (with the same field name) another dimension is added to the array. Say I upload a.html and b.html, I'll get:
$_FILES['files']['name'][0]; // a.html
$_FILES['files']['name'][1]; // b.html
$_FILES['files']['size'][0]; // size of a.html
$_FILES['files']['size'][1]; // size of b.html
To iterate through:
for(var $i = 0; $i < count($_FILES['files']['name']); $i++) {
echo 'File name ' . $_FILES['files']['name'][$i] . ' has size ' . $_FILES['files']['size'][$i];
}
This is explained at http://www.php.net/manual/en/features.file-upload.multiple.php

Passing uploaded files to another part of the script for onward processing

I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
echo "Files successfully uploaded . <br/>" ;
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories