here is my problem i need to rename the images when someone upload it, i want to use date and time and to created the $datatime value and i dont know how to make it works can some tell me how to do it? any help much be appreciated... Much Thanks
<?php if(isset($_POST['action'])=='uploadfiles') {
$time = time();
$date = date('Y-m-d');
$datetime = "$time" . "$date";
$upload_directory ='uploads/';
$count_data =count($_FILES['data']) ;
$upload = $_FILES['data']['name'][$x].',';
for($x=0;$x<$count_data;$x++) {
$upload .= $_FILES['data']['name']["$x" . ""].',';
move_uploaded_file($_FILES['data']['tmp_name'][$x], $upload_directory . $_FILES['data']['name'][$x]); ##### upload into your directory }
//echo "upload successfully..";
$con="INSERT INTO inmuebles (foto1) values ('$upload')";
$query=mysql_query($con); } ?>
Change here:
move_uploaded_file(
$_FILES['data']['tmp_name'][$x],
$upload_directory . $datetime . $_FILES['data']['name'][$x]
); ##### upload into your directory
Here the $datetime should be the string containing the timestamp.
Try the following:
$ext = pathinfo($_FILES['data']['name'][$x], PATHINFO_EXTENSION);
$newname = $datetime . '.' . $ext;
move_uploaded_file($_FILES['data']['tmp_name'][$x],
$upload_directory . $newname);
This will replace the current filename, and maintain the extension of the originally uploaded file.
If you want to maintain the original filename and simply append the datetime to it, use the following:
$info = pathinfo($_FILES['data']['name'][$x]);
$ext = $info['extension'];
$name = $info['filename'];
$newname = $name . $datetime . '.' . $ext;
move_uploaded_file($_FILES['data']['tmp_name'][$x],
$upload_directory . $newname);
Using date and time is a poor way to uniquely label anything because the limit of your fidelity is 1 item per second and computers are WAY faster than that, along with the fact more than 1 person could be using the upload at the same time. Instead use something build for this such as UUID (aka GUIDs). You can just use the uniqid() function in PHP which is very basic or if you read the comments somebody has written a UUID function (use version 5).
http://php.net/manual/en/function.uniqid.php
Related
I am trying to upload image files to a server and creating a random name when doing so. The issue I am having is that sometimes (far too often) it creates the same file name but for files with a different extension.
My code for the upload is below, what I want to do is add a check to make sure the name is not in use but with a different extension.
Example -
da4fb5c6e93e74d3df8527599fa62642.jpg & da4fb5c6e93e74d3df8527599fa62642.JPG
if ($_FILES['file']['name']) {if (!$_FILES['file']['error']){
$name = md5(mt_rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = $_SERVER['DOCUMENT_ROOT'] . '/images/infopages/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo '/images/infopages/' . $filename;
}else{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Any help is appreciated.
You can use PHP uniqid & rand functions combinedly. In this way you will never get duplicate values.
$filename = uniqid (rand(1000000,9999999), true) '.' . $ext[1];
I have deployed a Laravel project in a shared hosting. I have changed my .env file and copied all files from the public folder to the main directory and deleted the public folder. Now the problem is, whenever I am trying to upload an image, I am getting an internal server error. I suppose the problem is the Image Intervention is not getting the right folder to save the image. I have tried the both ways given below:
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('/images/admin/' . $filename);
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
and
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = '/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
But None of these is working. Any possible Solution?
Use laravel base_path function, so your code will look like this
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = base_path().'/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
Answer Update
Issue was fileinfo extension missing or disbaled.
Try This.
use Storage;
use File;
if(!empty($request->file('admin_pro_pic')))
{
$file = $request->file('admin_pro_pic') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$admin->image=$fileName;
}
Create imges inside public directory.
I am handling it like this:
// check for defined upload folder inside .env file, otherwise use 'public'
$publicUploadDir = env('UPLOAD_PUBLIC', 'public/');
// get file from request
$image = $request->file('admin_pro_pic');
// hasing is not necessary, but recommended
$new['path'] = hash('sha256', time());
$new['folder] = 'images/admin/';
$new['extension'] = $file->extension();
// store uploaded file and retrieve path
$image->storeAs($publicUploadDir, implode($new, '.'));
I am trying to upload a file using laravel Storage i.e
$request->file('input_field_name')->store('directory_name'); but it is saving the file in specified directory with random string name.
Now I want to save the uploaded file with custom name i.e current timestamp concatenate with actual file name. Is there any fastest and simplest way to achive this functionality.
Use storeAs() instead:
$request->file('input_field_name')->storeAs('directory_name', time().'.jpg');
You can use below code :
Use File Facade
use Illuminate\Http\File;
Make Following Changes in Your Code
$custom_file_name = time().'-'.$request->file('input_field_name')->getClientOriginalName();
$path = $request->file('input_field_name')->storeAs('directory_name',$custom_file_name);
For more detail : Laravel Filesystem And storeAs as mention by #Alexey Mezenin
Hope this code will help :)
You also can try like this
$ImgValue = $request->service_photo;
$getFileExt = $ImgValue->getClientOriginalExtension();
$uploadedFile = time()'.'.$getFileExt;
$uploadDir = public_path('UPLOAS_PATH');
$ImgValue->move($uploadDir, $uploadedFile);
Thanks,
Try with following work :
$image = time() .'_'. $request->file('image')->getClientOriginalName();
$path = base_path() . '/public/uploads/';
$request->file('image')->move($path, $image);
You can also try this one.
$originalName = time().'.'.$file->getClientOriginalName();
$filename = str_slug(pathinfo($originalName, PATHINFO_FILENAME), "-");
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$path = public_path('/uploads/');
//Call getNewFileName function
$finalFullName = $this->getNewFileName($filename, $extension, $path);
// Function getNewFileName
public function getNewFileName($filename, $extension, $path)
{
$i = 1;
$new_filename = $filename . '.' . $extension;
while (File::exists($path . $new_filename))
$new_filename = $filename . '_' . $i++ . '.' . $extension;
return $new_filename;
}
is there any pretty solution in PHP which allows me to expand filename with an auto-increment number if the filename already exists? I dont want to rename the uploaded files in some unreadable stuff. So i thought it would be nice like this: (all image files are allowed.)
Cover.png
Cover (1).png
Cover (2).png
…
First, let's separate extension and filename:
$file=pathinfo(<your file>);
For easier file check and appending, save filename into new variable:
$filename=$file['filename'];
Then, let's check if file already exists and save new filename until it doesn't:
$i=1;
while(file_exists($filename.".".$file['extension'])){
$filename=$file['filename']." ($i)";
$i++;
}
Here you go, you have a original file with your <append something> that doesn't exist yet.
EDIT:
Added auto increment number.
Got it:
if (preg_match('/(^.*?)+(?:\((\d+)\))?(\.(?:\w){0,3}$)/si', $FILE_NAME, $regs)) {
$filename = $regs[1];
$copies = (int)$regs[2];
$fileext = $regs[3];
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
while(file_exists($fullfile) && !is_dir($fullfile))
{
$copies = $copies+1;
$FILE_NAME = $filename."(".$copies.")".$fileext;
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
}
}
return $FILE_NAME;
You can use this function below to get unique name for uploading
function get_unique_file_name($path, $filename) {
$file_parts = explode(".", $filename);
$ext = array_pop($file_parts);
$name = implode(".", $file_parts);
$i = 1;
while (file_exists($path . $filename)) {
$filename = $name . '-' . ($i++) . '.' . $ext;
}
return $filename;
}
Use that function as
$path = __DIR__ . '/tmp/';
$fileInput = 'userfile';
$filename = $path .
get_unique_file_name($path, basename($_FILES[$fileInput]['name']));
if (move_uploaded_file($_FILES[$fileInput]['tmp_name'], $filename)) {
return $filename;
}
You can get working script here at github page
Use file_exists() function and rename() function to achieve what you're trying to do!
Who can help me to fix the following problem? Here is the issue: in a form POST i made people can upload files. The code below check if in the "uploads" folder there another file with the same name. If so, files are renamed as this example:
hallo.txt
1_hallo.txt
2_hallo.txt
... and so on.
This is the code used:
$OriginalFilename = $FinalFilename = $_FILES['uploaded']['name'];
// rename file if it already exists by prefixing an incrementing number
$FileCounter = 1;
while (file_exists( 'uploads/'.$FinalFilename ))
$FinalFilename = $FileCounter++.'_'.$OriginalFilename;
I would like to rename files in a different way. progressive numbers should be AFTER the file and, of course, before the extention. This is the same example of before but in the way i want:
hallo.txt
hallo_1.txt
hallo_2.txt
... and so on.
How can i modify the code to reach that result?
Thank you in advance and sorry for my newbie-style question. I'm really newbie! :)
Mat
Just change the $FinalFilename:
$FinalFilename = pathinfo($OriginalFilename, PATHINFO_FILENAME) . '_' . $FileCounter++ . '.' . pathinfo($OriginalFilename, PATHINFO_EXTENSION);
Or (better if you have a lot of files with the same name and often iterate more than once):
$filename = pathinfo($OriginalFilename, PATHINFO_FILENAME);
$extension = pathinfo($OriginalFilename, PATHINFO_EXTENSION);
while (file_exists( 'uploads/'.$FinalFilename ))
$FinalFilename = $filename . '_' . $FileCounter++ . '.' . $extension;