Check file exist on UploadiFive - php

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

Related

randomly rename files in php

I have a folder of 1000 images and I need to randomly rename them from 1.jpg to 1000.jpg , it must be completely random each time I run the script.
I just need that 1.jpg is different each time I run the script.
all I have to work with so far is the following code.
Please help. Thanks
<?php
if (file_exists('Image00001.jpg'))
{
$renamed= rename('Image00001.jpg', '1.jpg');
if ($renamed)
{
echo "The file has been renamed successfully";
}
else
{
echo "The file has not been successfully renamed";
}
}
else
{
echo "The original file that you want to rename does not exist";
}
?>
Check this out, if this helps. I tried it out and it works. Create a php file and copy the code, and in the same directory create a folder name files and fill it with images with extension .jpg and then run the php file. This is the refined code. Let me know if this works for you.
<?php
$dir = 'files/'; //directory
$files1 = scandir($dir);
shuffle($files1); //shuffle file names
$i = 1; //initialize counter
//store existing numbered files in array
$exist_array = array();
while (in_array($i . ".jpg", $files1)) {
array_push($exist_array, $i . ".jpg");
$i++;
}
foreach ($files1 as $ff) {
if ($ff != '.' && $ff != '..') // check for current or parent directory, else it will replace the directory name
{
// check whether the file is already numbered
if (in_array($ff, $exist_array)) {
continue;
}
//next 3 lines is proof of random rename
echo $ff . " ---> ";
rename($dir . $ff, $dir . $i . ".jpg");
echo $i . ".jpg<br/>";
$i++;
}
}
?>

Upload fails "move uploaded file"

First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.

Error in uploading files in yii2 move_upload function

Am doing multiple file upload in the controller but the file doesn't get uploaded
controller code: for the upload
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
I have tried var_dump($images['name'] and everything seems okay the move file does not upload the file
Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...
The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?
this is the related php man php.net/manual/en/function.move-uploaded-file.php
Have you added enctype attribute to form tag?
For example:
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>

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

Storing file input ID inside variable during for loop | PHP

I am using the following HTML & PHP code to move multiple images to my server.
Is there a way using my code that I can associate a specific input element with the uploaded file?
So in my for loop, I can discover when the image from 'image_22' is being processed. Is this possible using my current code?
Dream world would be storing the value "image_22" inside a variable $imageNum :-)
Here is a snippet of what I'm currently working with...
HTML:
<input id="image_22" name="images[]" type="file" />
<input id="image_8" name="images[]" type="file" />
...
PHP:
<?php
if (isset($_POST['Submit'])) {
$number_of_file_fields = 0;
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory
/**
* we get a $_FILES['images'] array ,
* we procee this array while iterating with simple for loop
* you can check this array by print_r($_FILES['images']);
*/
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
$number_of_file_fields++;
if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['images']['name'][$i];
if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory .
$_FILES['images']['name'][$i])) {
$number_of_moved_files++;
}
}
}
echo "Number of File fields created $number_of_file_fields.<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);
}
?>
Thank you!!
In your HTML, just include that value inside the [].
<input id="image_22" name="images[22]" type="file" />
<input id="image_8" name="images[8]" type="file" />
In your loop, instead of an incremental for loop, use a foreach with index, which is a more common pattern in PHP than the incremental type. The $index will be the number supplied in the []:
// Loop over the ['name'] key in $_FILES['images'] to get all the named indexes
foreach ($_FILES['images']['name'] as $index => $filename) {
if ($filename != '') {
// not empty...
$number_of_uploaded_files++;
// Check for validity (see below)...
// Use the name concatenated with _$index to supply store the index with the filename
$uploaded_files[] = $filename . "_$index";
if (move_uploaded_file($_FILES['images']['tmp_name'][$index], $upload_directory . $filename . "_$index")) {
// successful rename
$number_of_moved_files++;
}
}
}
Note that your script is currently vulnerable to path injection attacks. You must filter the name of each file against the inclusion of things like ../ which could force the file to be saved anywhere on your filesystem (writable by the web server)! It is recommended to check the name with a regular expression of acceptable values:
// Verify that the uploaded filename contains only letters, numbers, hyphen, underscore, space before the `.` and letters only after the `.`
// You could also insist that it end in `.(jpg|gif|png)` or whatever your acceptable formats are
// Most important is to prevent things like `../`
if (preg_match('/^[a-z0-9_- ]+\.[a-z]+$/i', $filename)) {
// It's an ok filename
}

Categories