I am creating profile form where I am allowing users to store their profile photos. To make sure the names are different and won't be overwritten, I am using microtome function to rename the uploaded file:
$temp = explode(".",$_FILES["fileToUpload"]["name"]);
$newfilename = round(microtime(true)) . '.'. end($temp);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"subsites/uploads/". $newfilename
...but later when I call $newfilename variable in the same form (to save file path in the database) it values is changed.
<input type="hidden" name="FormPicName" id="FormFileName"
value=<?php echo $_FILES["fileToUpload"]["tmp_name"],"subsites/uploads/". $newfilename?>>
I tried storing $newfilename as variable or session variable, but it still generates different values.
Is there a way to save microtome based variable as constant?
This is a great solution (I use this for my projects)
// get file extension
$ext = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION);
// make new filename
$newfilename = uniqid('profilepic_').'.'.$ext;
$newfilename will have something like profilepic_4b3403665fea6.jpg
Related
I have a <form> with a multiple file input that stores those files into the server. The names of the files must follow a numeric standard and that's why I rename them before storing. Each post has an ID an can have more than one file so the pattern is: post-id + dash and a number + file extension, this way, if the same post has two file with the same extensions, the dash + number will avoid them to be overwriten. So, before I store the files I run a loop to find the proper number to the name. The problem is, the function to verify the existence of the file seems not to be returning true when it should. The code:
$counter = 0;
do{
$nomeArquivo = $post->id . "-{$counter}" . "." . $arq->extension();
$counter++;
//these commented are other ways of verification I tried
//}while(Storage::exists($nomeArquivo));
//}while(file_exists("/storage/" . $nomeArquivo));
}while(is_file("/storage/" . $post->id . "-{$counter}"));
Storage::putFileAs('/public', $arq, $nomeArquivo);
This code above runs inside a foreach($files as $arq) where $files are the files from the form input.
Reference: https://laravel.com/docs/5.4/filesystem and https://laravel.com/api/5.4/Illuminate/Filesystem/Filesystem.html
Use the File Facade to check for the existence of a file:
File::exists($myfile)
http://laravel-recipes.com/recipes/123/determining-if-a-file-exists
If name of the file need to be unique only then,
You can give Unique Name like this:
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$destination ='/files/';
$filename = uniqid() . '.' . $extension;
$file->move($destination, $filename);
Now save above file name in your database. Hope it may help you
As user #fubar pointed in the comments, I was referencing the wrong path to verify the existence of the file. I change the while condition to while(\File::exists(public_path() . '/storage/' . $nomeArquivo)) and it worked well. Thanks
I need to upload two files with different ext example :
file_1.txt and file_image.png
when the user sent the two files using upload an form :
file_1.txt and file_image.png
before move_uploaded_file I need to rename the image name to be like the txt. name file :
file_1.txt
file_1.jpeg
I just want to rename the image filename, not the extension
Code is something like this :
switch($_REQUEST['action']) {
case "upload":
$Imagefile_temp = $_FILES['file']['tmp_name'];
$Textfile_temp = $_FILES['file']['tmp_name'];
$Imagefile_name = $_FILES['file']['name'];
$Textfile_name = $_FILES['file']['name'];
$ImageFileType = array('png' ,'jpg');
$TextFileType = array('txt');
$Image_extension = pathinfo($Imagefile_name, PATHINFO_EXTENSION); // holds the file extension of the file
$Text_extension = pathinfo($Textfile_name, PATHINFO_EXTENSION); //holds the file extension of the file
// //Declaring Path for uploaded images
$file_path = "uploads";
//checks for duplicate files
if((!file_exists($file_path."/".$Imagefile_name)) || (!file_exists($file_path."/".$Textfile_name))) {
$j = 0; //Variable for indexing uploaded image
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
if(in_array($Image_extension,$ImageFileType) ) {
$Image_extension = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($Image_extension); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $Image_extension[count($Image_extension) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
$Imagefilestatus = move_uploaded_file($Imagefile_temp,$file_path."/"."image_".$Imagefile_name) ;//if file moved to uploads folder
}
if(in_array($Text_extension,$TextFileType) ) {
$Text_extension = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($Text_extension); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $Text_extension[count($Text_extension) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
$Textfilestatus = move_uploaded_file($Textfile_temp,$file_path."/".$Textfile_name) ;//if file moved to uploads folder
}
}
}
}
$name = 'Whatevernameyouwant.'.pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
pathinfo with parameter PATHINFO_EXTENSION returns the file extension.
You can just explode the text file from the extension and use it as the image file name when moving it :
$text_file_name = $_FILES["text"]["name"]; // give you the text file name
$image_file_name = $_FILES["image"]["name"]; // give you the image file name
$file_expensions = strtolower(end(explode(".", $image_file_name))); // give you the image extension and so you can use it later for saving the file
$n = explode(".", $text_file_name, 1);
$name = $n[0]; // get text file name
$name = $name.".".$file_expensions; // this is new name of the image
move_uploaded_file($file_tmp, "path/$name")
I assume you are aware that the code you've presented here allows anyone with upload privileges to upload and execute PHP code.
(the reason I mention this is that there is scope for a lot of improvement elsewhere - and if the security vulnerability is exploitable then you should really think about start again from scratch with this).
Will your extension always be .jpg or .png ? (what about .jpeg ?)
I need to rename the image name to be like the txt. name file
I presume you mean that you want the filename on the retained image file to match that of the txt file - you can specify the destination name in move_uploaded_file(). Breaking down a process into steps is a good idea for managing complexity but file operations are expensive and here redundant.
So really you want to know how to get the a filename without an extension then add the file extension from a different file.
You already have the extension you want to apply in $Image_extension
While you could just do....
$destination_name=$destination_path
. str_replace('.txt', '.' . $image_extension, $Textfile_name);
However this will not work as expected if $imageFile_name contains more than one instance of '.txt'.
You could use PCREs to specify that you should only apply the change to the end of the string:
$destination_name=preg_replace("/txt$/i", $image_extension, $Textfile_name);
Or take the last 4 characters off $Textfile_name then append the image extension.
$destination_name=substr($Textfile_name, 0, -3) . $image_extension;
Or strrev the text file name, replace 'txt' with strrev($image_extension) with a limit of 1, then strrev the result to ensure only the end of the string is replaced.
If I spent more time thinking about this, there are probably other solutions too - but they will become increasingly esoteric.
In general, allowing users to pick their own names (or even part thereof) for content uploaded inside the document root is a bad idea.
I want to rename all files in a folder with random numbers or characters.
This my code:
$dir = opendir('2009111');
$i = 1;
// loop through all the files in the directory
while ( false !== ( $file = readdir($dir) ) ) {
// do the rename based on the current iteration
$newName = rand() . (pathinfo($file, PATHINFO_EXTENSION));
rename($file, $newName);
// increase for the next loop
$i++;
}
// close the directory handle
closedir($dir);
but I get this error:
Warning: rename(4 (2).jpg,8243.jpg): The system cannot find the file specified
You're looping through files in the directory 2009111/, but then you refer to them without the directory prefix in rename().
Something like this should work better (though see the warning about data loss below):
$oldName = '2009111/' . $file;
$newName = '2009111/' . rand() . (pathinfo($file, PATHINFO_EXTENSION));
rename($oldName, $newName);
Of course, you may want to put the directory name in a variable or make other similar tweaks. I'm still not clear on why you're trying to do this, and depending on your goals there may be better ways of reaching them.
Warning! The approach you are using could cause data loss! A $newName could be generated that is the same name as an existing file, and rename() overwrites target files.
You should probably make sure $newName doesn't exist before you rename().
In Propriete entity I have 5 field called image1 image2 image3 image4 image5
I wan't to add these fields in a for loop
I tried this but it doesn't work:
for($i=0;$i<count($this->request->data['files'])&&$i<5;$i++){
//... some code
$propriete->{'image'.$i+1} = $file['name'];
}
}
Can someone help me?
EDIT
This is the code of my loop:
for($i=0; $i<count($this->request->data['files']) && $i<5; $i++){
$file=$this->request->data['files'][$i];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . '/img/' . $file['name']);
debug($file['name']);
//prepare the filename for database entry
$propriete->{'image'.$i+1} = $file['name'];
}
}
Your code should work fine, you're just missing parenthesis which makes your concatenation go haywire
$propriete->{'image'.($i+1)}="test";
This can also be demonstrated by this simple test
$i=2;
echo 'image'.$i+1; // 1 :)
VS
echo 'image'.($i+1); //image3
Put the value of every method in a variable to store the value and then use it.For eg
$values = $this->request->data['files'];
You cannot for loop the data without putting them in a variable first.
If you cannot find the filename the problem should be that you are naming the object property in the wrong manner.You should enclose $i+1 with quotes.
I'm writing the code for a website right now that's uploads images and then displays them gallery style. What I would like to happen is for the file name of the image to be entered into the site's database as the name of the image. However, just using $_FILES['images']['name']; gives me the file name but with the file extension attached at the end. How would I remove the file extension so I can use the file name by itself?
You can use the pathinfo() function (docs).
$example = "my_file.jpeg";
$filename = pathinfo($example, PATHINFO_FILENAME);
echo $filename; // my_file
Just use preg_replace:
$name = preg_replace('/(.+)\.\w+$/U', $_FILES['images']['name'], '$1');
You can use rename to remove the extension:
-> http://www.php.net/manual/en/function.rename.php
As my comment above implies, it depends on what you consider in the filename to be the name and what is the extension.
everything up to the last dot:
$filename = 'some.file.name.zip';
$name = substr($filename, 0, strrpos($filename, '.'));
everything up to the first dot:
$filename = 'some.file.name.zip';
$name = substr($filename, 0, strpos($filename, '.'));
they look the same, but the first one looks for the first dot from the end of the string and the second one from the start of the string.