How to save the full path of file upload in php? - php

I am using Laravel and I have a form that uploading a file. And I want to save the full path of that file in my database. Do you know how?
if($request->hasFile('alternate_add_file_path')) {
$file = $request->file('alternate_add_file_path');
$destination = 'files/';
$extension = $file->getClientOriginalExtension();
$file_name = $getCreateDate . '_' . str_replace('/','_',$M_USER_NAME) . '.' . $extension;
$file->move($destination, $file_name );
}
This below is for the save into database
$M_FILE_PATH = $file_name;
I do not have an error though, just only the filename which saved into my database, not the full path.

To convert a relative path to an absolute one (server side) you can use realpath. Eg.
$fullpath = realpath($file_name);

Related

Create random filename but check it's not already used

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

Image Upload is not working in a Laravel Project hosted in a shared server

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, '.'));

PHP move_uploaded_file Rename file

I know that move_uploaded_file() sets the name of the uploaded file and sets the destination also. I have this:
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file`
I have tried explode $_FILES['file']['tmp_name'] but I don't get to change the name of my uploaded file to my POST variable $newfile=$_POST["something"];
Thank you in advance
I am using
//File name
$file_name = $_FILES["file"]["name"];
$file_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name);
// get extension
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// change name
$imagename = $file_name . time() . "." . $ext;
Set the entire upload path with the file name in $targetpath variable.
In you code
$sourcePath = $_FILES['file']['tmp_name'];
$newfile=$_POST["something"]; //any name sample.jpg
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$newfile;
move_uploaded_file($sourcePath,$targetPath) ;
Now the uploaded file name is sample.jpg
I think this will helpful for you.

Laravel - Create custom name while uploading image using storage

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

PHP - move_uploaded_file not working to copy file in same folder

Having some trouble with rewriting a photo file. I need the file name to get rewritten as a random string. The file uploads fine - I can't seem to get it copy the file and rewrite the file name to the random string. The file is going to stay in the directory.
The function is working fine and I can rewrite file name in the database, but it will not rewrite the actual file in the folder. The folder permissions are rwxr-xr-x (755).
Any thoughts?
function AfterUpdate(){
$file = $this->file_attachment;
$path_parts = pathinfo($file);
$newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];
$file_src = $_SERVER['DOCUMENT_ROOT'] . $file;
$newfile_src = $_SERVER['DOCUMENT_ROOT'] . $newFilename;
if (move_uploaded_file($file_src, $newfile_src)){
$this->file_attachment = $newFilename;
}
}
$newFilename contains a path location I guess by looking at the $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];.
$newFilename should just be the new file name with extension.
move_uploaded_file will only move files from one folder to another or the same, that already exists. But will not create a folder for you.
Simple fix. Replace move_uploaded_file with rename. The file will not be moved, just renamed.
$file = $this->file_attachment;
$path_parts = pathinfo($file);
$newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];
$file_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $file;
$newfile_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $newFilename;
if (rename($file_src, $newfile_src)){
$this->file_attachment = $newFilename;
}

Categories