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
Related
I am trying to convert my images into greyscale and then downloading it in Laravel but each and every time I am getting this error
The file "" does not exist
Dont' know why it giving this error here is my code.
$file = public_path() . "/large/s/" . $sheet[0]->sheet_f_id . '-s.jpg';
$image = Image::make($file);
$grayScale = $image->greyscale();
return Response::download($grayScale);
When I dump my $file variable I got the response something like this.
"D:\xampp\htdocs\wikistaging\public/large/s/03-02-05-025-s.jpg"
But still it is giving me the sam error why is that happening. Any help would be great.
If you want to download then first you have to save the created file and need to give the path to download. Here is working example
$img_name=$sheet[0]->sheet_f_id . '-s.jpg';
$destination_path=public_path() . "/large/s/";
$file = $destination_path.$img_name;
$image = Image::make($file);
$image->greyscale()->save($destination_path.'gray-'.$img_name);
return Response::download($destination_path.'gray_'.$img_name);
And if you don't want to keep the file you can delete, replace the last line with below line.
return Response::download($destination_path.'gray_'.$img_name)->deleteFileAfterSend(true);
Hope it will work for you.
You must save your image after call greyscale().
You can try it:
$filePath = public_path() . "/large/s/" . $sheet[0]->sheet_f_id . '-s-test.jpg';
$image->greyscale();
$image->save($filePath);
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().
I need to develop a little PHP script that I can run from a cron job which in pseudo code does the following:
//THIS IS PSEUDO CODE
If(file exists with name 'day.jpg')
rename it to 'fixtures.jpg'
else
copy 'master.jpg' to 'fixtures.jpg'
Where day.jpg should be the current day of the month.
I started to replace the pseudo code with the stuff I'm pretty sure how to do:
<?php
if(FILE EXISTS WITH NAME DAY.JPG) {
rename ("DAY.JPG", "fixtures.jpg");
} else {
copy ("master.jpg", "fixtures.jpg");
}
?>
Clearly there are still a few things missing. Like I need to get the filename with the current day of the month and I need to check if the file exists or not.
I guess I need to do something like this $filename='date('j');'.jpg to get the filename, but it isn't really working so I kinda need a bit help there. Also I don't really know how to check if a file exists or not?
$path = __DIR__; // define path here
$fileName = sprintf("%s%d.jpg", $path, date("j"));
$fixtures = $path . DIRECTORY_SEPARATOR . "fixtures.jpg";
$master = $path . DIRECTORY_SEPARATOR . "master.jpg";
file_exists($fileName) ? rename($fileName, $fixtures) : copy($master, $fixtures);
Basicly you need script like above but you need to work on your path. Your code above had syntax problem.
You have a basic syntax problem, it should be:
$filename = date('j') . '.jpg';
You don't put function calls inside quotes, you need quotes around the literal string '.jpg', and you need to use . to concatenate them.
I recommend you read the chapter on Strings in a PHP tutorial.
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
I am currently in the process of writing a mobile app with the help of phonegap. One of the few features that I would like this app to have is the ability to capture an image and upload it to a remote server...
I currently have the image capturing and uploading/emailing portion working fine with a compiled apk... but in my php, I am currently naming the images "image[insert random number from 10 to 20]... The problem here is that the numbers can be repeated and the images can be overwritten... I have read and thought about just using rand() and selecting a random number from 0 to getrandmax(), but i feel that I might have the same chance of a file overwriting... I need the image to be uploaded to the server with a unique name every-time, no matter what... so the php script would check to see what the server already has and write/upload the image with a unique name...
any ideas other than "rand()"?
I was also thinking about maybe naming each image... img + date + time + random 5 characters, which would include letters and numbers... so if an image were taken using the app at 4:37 am on March 20, 2013, the image would be named something like "img_03-20-13_4-37am_e4r29.jpg" when uploaded to the server... I think that might work... (unless theres a better way) but i am fairly new to php and wouldn't understand how to write something like that...
my php is as follows...
print_r($_FILES);
$new_image_name = "image".rand(10, 20).".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "/home/virtual/domain.com/public_html/upload/".$new_image_name);
Any help is appreciated...
Thanks in advance!
Also, Please let me know if there is any further info I may be leaving out...
You may want to consider the PHP's uniqid() function.
This way the code you suggested would look like the following:
$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
// do some checks to make sure the file you have is an image and if you can trust it
move_uploaded_file($_FILES["file"]["tmp_name"], "/home/virtual/domain.com/public_html/upload/".$new_image_name);
Also keep in mind that your server's random functions are not really random. Try random.org if you need something indeed random. Random random random.
UPD: In order to use random.org from within your code, you'll have to do some API requests to their servers. The documentation on that is available here: www.random.org/clients/http/.
The example of the call would be: random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new. Note that you can change the min, max and the other parameters, as described in the documentation.
In PHP you can do a GET request to a remote server using the file_get_contents() function, the cURL library, or even sockets. If you're using a shared hosting, the outgoing connections should be available and enabled for your account.
$random_int = file_get_contents('http://www.random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new');
var_dump($random_int);
You should use tempnam() to generate a unique file name:
// $baseDirectory Defines where the uploaded file will go to
// $prefix The first part of your file name, e.g. "image"
$destinationFileName = tempnam($baseDirectory, $prefix);
The extension of your new file should be done after moving the uploaded file, i.e.:
// Assuming $_FILES['file']['error'] == 0 (no errors)
if (move_uploaded_file($_FILES['file']['tmp_name'], $destinationFileName)) {
// use extension from uploaded file
$fileExtension = '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// or fix the extension yourself
// $fileExtension = ".jpg";
rename($destinationFileName, $destinationFileName . $fileExtension);
} else {
// tempnam() created a new file, but moving the uploaded file failed
unlink($destinationFileName); // remove temporary file
}
Have you considered using md5_file ?
That way all of your files will have unique name and you would not have to worry about duplicate names. But please note that this will return same string if the contents are the same.
Also here is another method:
do {
$filename = DIR_UPLOAD_PATH . '/' . make_string(10) . '-' . make_string(10) . '-' . make_string(10) . '-' . make_string(10);
} while(is_file($filename));
return $filename;
/**
* Make random string
*
* #param integer $length
* #param string $allowed_chars
* #return string
*/
function make_string($length = 10, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') {
$allowed_chars_len = strlen($allowed_chars);
if($allowed_chars_len == 1) {
return str_pad('', $length, $allowed_chars);
} else {
$result = '';
while(strlen($result) < $length) {
$result .= substr($allowed_chars, rand(0, $allowed_chars_len), 1);
} // while
return $result;
} // if
} // make_string
Function will create a unique name before uploading image.
// Upload file with unique name
if ( ! function_exists('getUniqueFilename'))
{
function getUniqueFilename($file)
{
if(is_array($file) and $file['name'] != '')
{
// getting file extension
$fnarr = explode(".", $file['name']);
$file_extension = strtolower($fnarr[count($fnarr)-1]);
// getting unique file name
$file_name = substr(md5($file['name'].time()), 5, 15).".".$file_extension;
return $file_name;
} // ends for is_array check
else
{
return '';
} // else ends
} // ends
}