PHP Multiple File Uploader is uploading only a single file - php

I have been browsing through S.O for hours and still can't figure out why my code is not working. I am trying to upload multiple music files but for some reason only 1 file out of all selected is being uploaded.
Here's my code:
HTML
<input id="songs" name="songs[]" type="file" multiple="multiple" accept=".ogg,.flac,.mp3" />
PHP
$path = "../songs/"; //file to place within the server
$valid_formats1 = array("mp3", "ogg", "flac"); //list of file extention to be accepted
$tot = count($_FILES['songs']['name']);
for($i = 0; $i < $tot ; $i++){
$temporaryPathOfImage = $_FILES['songs']['tmp_name'][$i];
if ($temporaryPathOfImage != ""){
$dirPath = "../songs/" . $_FILES['songs']['name'][$i];
if(move_uploaded_file($temporaryPathOfImage, $dirPath)) {
echo "Stored in: " . "../songs/" . $_FILES['songs']['name'][$i];
}
}
}

Related

Check file exist on UploadiFive

I downloaded this upload example: https://github.com/xmissra/UploadiFive
When sending an apernas file, it works perfectly but when sending more than one file the function that checks if the file already exists presents a problem. Apparently the loop does not ignore that the file has just been sent and presents the message asking to replace the file. Is there any way to solve this?
This is the function that checks if the file already exists.
$targetFolder = 'uploads'; // Relative to the root and should match the upload folder in the uploader
script
if (file_exists($targetFolder . '/' . $_POST['filename'])) {
echo 1;
} else {
echo 0;
}
You can test the upload working at: http://inside.epizy.com/index.php
*Submit a file and then send more than one to test.
I tried it this way but it didn't work:
$targetFolder = 'uploads';
$files = array($_POST['filename']);
foreach($files as $file){
if (file_exists($targetFolder . '/' . $file)) {
echo 1;
} else {
echo 0;
}
When you have multiple files to be uploaded keep these things in mind;
HTML
Input name must be array name="file[]"
Include multiple keyword inside input tag.
eg; <input name="files[]" type="file" multiple="multiple" />
PHP
Use syntax $_FILES['inputName']['parameter'][index]
Look for empty files using array_filter()
$filesCount = count($_FILES['upload']['name']);
// Loop through each file
for ($i = 0; $i < $filesCount; $i++) {
// $files = array_filter($_FILES['upload']['name']); use if required
if (file_exists($targetFolder . '/' . $_FILES['upload']['name'][$i])) {
echo 1;
} else {
echo 0;
}
}

Large CSV download script timing out

I have a a script that can upload the contents of a CSV file and download the links to a local directory, the CSV file i need to upload to it is about 4056 lines long and 4056 FTP downloads, the script works fine but the web server times out when i use it.
even tried set_time_limit(0);
is there a way i could session the script and loop the process so it could do it's job for a few hours without interruptions.
<?php
/**
* Please change your upload directory according to your needs. Make sure you include the trailing slash!
*
* Windows C:\tmp\
* Linux /tmp/
*/
$uploaddir = '/tmp/';
if(isset($_FILES['userfile']['name'])){
// Read uploaded file
$lines = file($_FILES['userfile']['tmp_name']);
echo "Reading file ... <br/>";
$linecount = 0;
foreach($lines as $line ){
echo ++$linecount . ". FTP Url is : " .$line . "<br/>";
echo " Downloading " . $line . "<br/>";
$parsed_url_values = parse_url($line);
//TODO perhaps do a validation of the ftp url??
if($parsed_url_values['scheme'] == 'ftp'){
// set up basic connection
$conn_id = ftp_connect($parsed_url_values['host']);
// login with username and password
$login_result = ftp_login($conn_id, $parsed_url_values['user'], $parsed_url_values['pass']);
ftp_pasv($conn_id, true);
$path = rtrim($parsed_url_values['path'], '_');
$filename = basename($path);
if (ftp_get($conn_id, $uploaddir . $filename, $path , FTP_BINARY)) {
echo " Successfully downloaded the file " .$line . "<br/>";
} else {
echo " Could not save the file to " . $line . ". Please verify the url is correct and the file exists.<br/>";
}
} else {
echo " Sorry. This script was made for FTP downloads only.";
}
}
}
?>
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Select the file to upload : <input name="userfile" type="file" />
<input type="submit" value="Upload" />
</form>
You need to increase the execution time of your script by using max_execution_time. You can use this example, place it on top of your script:
<?php
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
.. The rest of your script
Hope this will help you!
In my practice I often use step by step loading if i can't load data via cron or php cli.
Something like that (not tested):
<?php
$newFileName = '/path/to/file.csv';
$line = isset($_REQUEST['csvline']) ? (int) $_REQUEST['csvline'] : 0;
$handle = fopen($newFileName, "r");
//10 seconds for each step
$stepTime = 10;
$startTime = time();
$lineCounter = 0;
while (($fileop = fgetcsv($handle)) !== false)
{
//already loaded lines
$lineCounter++;
if ($lineCounter <= $line) continue;
//here goes your script logic
//stops when time goes out
if (time() - $startTime >= $stepTime) break;
}
//next you need to query this script again
//using js maybe (window.location or ajax call)
//so you can see loading progress or any other useful information
//like
if (!feof($handle)) {
echo "<script>window.location = '/your.php?csvline={$lineCounter}'<script>";
}
//you even can start loading from last line before script fails
But i'm sure that using cron is the best solution for your problem.

image upload and save with multiple copies / names

How do I upload an images and then save with a different name and multiple copies in the same directory ?
One copy of the uploaded image(abcd.jpg) needs to be named '212_1_today_00.jpg' and another copy needs be named '424_1_today_00.jpg' and may be another '848_1_today_01.jpg'
better use time() instead of today as random no might be repeated at some point.......
<?php
if($_FILES){
$image = $_FILES['image'];
if($image['error'] == 0){
$a = explode('.',$image['name']);
$e = end($a);
$t = time();
$name = rand(100, 999)."_1_{$t}";
move_uploaded_file($image['tmp_name'], $name.'_00.'.$e);
# if u want 1 copy
copy($name.'_00.'.$e, rand(100, 999)."_1_{$t}_01.{$e}");
# if u want n more copies
/*
$n = 5; #no of copies u want
for ($i = 1; $i <= $n; $i++) {
copy($name.'_00.'.$e, rand(100, 999)."_1_{$t}_0{$i}.{$e}");
}
*/
echo 'Done';
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" accept='image/*'/>
<input type="submit">
</form>
First I uploaded one with the name '212_1_today_00.jpg' and I copied using PHP function - copy
Found at http://www.php.net/manual/en/function.copy.php
<?php
$file = './myfolder/212_1_today_00.jpg';
$newfile = './myfolder/424_1_today_00.jpg';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}

$_FILES Uploads Only First File When Parsed

Ok guys this might seem like such a newbie issue but I've got looping issues that I just can't seem to work around. I'm simply trying to upload multiple images on my first project site.
When I posted this test php page up, it uploads all the files that I requested of it fine
; with all images that I wish to upload being uploaded at the directory intended.
<?php
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
?>
However when I tried including my parser, though it goes into the correct directory, only the first file gets uploaded
<?php
if(isset($_POST['property_name'])){
$property_name = mysql_real_escape_string($_POST['property_name']);
$district = mysql_real_escape_string($_POST['district']);
$address = mysql_real_escape_string($_POST['address']);
$property_type = mysql_real_escape_string($_POST['property_type']);
$sql = mysql_query("SELECT id FROM mydb WHERE property_name='$property_name' LIMIT 1");
$propertyMatch = mysql_num_rows($sql);
if($propertyMatch > 0)
{
echo 'Sorry, you tried to place a duplicate "Property Name" into the system, click here';
exit();
}
$sql = mysql_query("INSERT INTO mydb (property_name, district, address, property_type) VALUES ('$property_name','$ district','$address','$property_type')")or die (mysql_error());
if (!file_exists("property_images/$property_name"))
{
mkdir("property_images/$property_name");
}
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
}
?>
The count code works fine so I think its either these {} buggers or I need to get my eyes fixed. Any help would be uber appreciated.
you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at http://www.php.net/manual/en/features.file-upload.multiple.php
hope this will sure help you.

Renaming multiple files when uploaded

I have a form that uploads multiple file. The php code that I am using works fine but I would like to rename the files also and don't know how to go about this. I think adding a time stamp to the name would be the best answer. Here is the working code so far:
/* FILE UPLOAD CODE */
{
$number_of_file_fields = 0;
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploads/'; //set upload directory
/**
* we get a $_FILES['file'] array ,
* we procee this array while iterating with simple for loop
* you can check this array by print_r($_FILES['file']);
*/
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$number_of_file_fields++;
if ($_FILES['file']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['file']['name'][$i];
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_directory . $_FILES['file']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
/* END FILE UPLOAD CODE */
Any help on what to add and where to accomplish this would be greatly appreciated.
If you want to give the same name to all the uploaded files, then you can get the name by using $_GET.
For example:
<form action="upload.php" method="post"> \\ this would send it to your page
<input type='text' size='30' name='filename'/>
<input type='submit' />
</form>
simply get the name using $_GET like this
$name = $_GET['filename'];
and now run your code but move the file with this name like this
move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_directory . $name[$i])
You can specify the new file name as the second parameter in move_uploaded_file()
For example:
move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_directory . "new_file_name");

Categories