Get path of temp uploaded file with image extension in PHP - php

I have a form which lets the user upload the image file.
<div id="imageDiv">
Image Path : <input class="imageOption" type="file" id= "uploadImageFile" name="uploadImageFile" >
</div>
The problem comes when I try to fetch the path from temp folder. I won't be needing the image files after processing the request. When I try to fetch the path with something like this
$imagePath = $_FILES['uploadImageFile']['tmp_name'];
The path looks like C:\wamp\tmp\phpA123.tmp.
The API I'm using would require a path with extension of an uploaded image like this
C:\wamp\tmp\image.png
Couldn't figure out a way to do so unless I want to copy this image to some other upload folder and use it. I don't want these images logged in a server
Thanks

It would be helpful to know the specific API in use, but no well written file storage API should ever have to rely on the uploaded file name being used to store a file. You should be able to use the temp file contents in the API, and specify the file name separately.
In L5:
// Get the UploadedFile object
$file = Request::file('uploadImageFile');
// You can store this but should validate it to avoid conflicts
$original_name = $file->getClientOriginalName();
// This would be used for the payload
$file_path = $file->getPathName();
// Example S3 API upload
$s3client->putObject([
'Key' => $original_name, // This will overwrite any other files with same name
'SourceFile' => $file_path,
'Bucket' => 'bucket_name'
]);

If you want to get same output as -
$imagePath = $_FILES['uploadImageFile']['tmp_name'];
in Laravel, you can do something like this as described by #cdbconcepts -
$file = Request::file('uploadImageFile');
$imagePath = $file->getPathName()

Related

Laravel File Upload different versions and formats of a file

Let me know a sample. how can I store the uploaded file to the database; laravel
ex.
In the system, if upload a doc file, it will automatically convert to PDF.(via cloud convert API ). how I can save both files in the database.
---------------------------------------------------
|id|proposal_id|version_id|Status|fileName|filetype|
---------------------------------------------------
Better to upload the files in a folder within the public folder and save the link folder in the database
you can use code like this:
if ($request->hasFile('image')) {
$file = array('image' => Input::file('image'));
$destinationPath = 'image/'; // upload path
$extension = Input::file('image')->getClientOriginalExtension();
$logofileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('image')->move($destinationPath, $logofileName);
}

Saving image path to database using Laravel

I have a function that takes submitted form data which is an image, then validates it and it deletes an old image if one already exists. It currently does that and stores the image on in the storage folder.
I am now trying to save the URL of the image to the database. I have seen examples where they do not save the path to the database but would it be best to do so?
Here is my function
public function postAvatarUpload(Request $request)
{
$this->validate($request, [
'image' => 'required|image|max:3000|mimes:jpeg,jpg,bmp,png',
]);
$user = Auth::user();
$usersname = $user->username;
$file = $request->file('image');
$filename = $usersname . '.jpg';
if (Storage::disk('local')->has($filename)) {
Storage::delete($filename);
}
Storage::disk('local')->put($filename, File::get($file));
$avatarPath = Storage::url($filename);
Auth::user()->update([
'image' => $avatarPath,
]);
return redirect()->route('profile.index',
['username' => Auth::user()->username]);
}
I mostly store images people upload to a subfolder in the public folder from Laravel. The image can then be requested with only your webserver doing the work and not having to serve it via PHP.
For images like an avatar I create a folder structure based on the model name and id of the model. Like: laravel_folder/public/images/user/13/avatar.jpg.
Because the path and url are based on the modelname and id, you can easily generate a direct url and path to it. Downside is that the url and path to avatars of other users is predictable, so don't use it for sensitive images.
I see you accept an image in multiple formats (jpg,png,bmp).
When you save the image, you save it as an jpg image. You should use an image manipulation library like Intervention, or get the extension of the file with pathinfo($file, PATHINFO_EXTENSION), otherwise the file won't be readable because the image extension and the image contents don't match.
Also think about the image size. Users can upload an image in poster size, while you only need a small image. Use an image manipulation library to create a smaller version image of the original image.
If you save the original image in the format you get from the user, then just check all extensions if they exist. One way to do it would be:
$extensions = [ 'jpg', 'jpeg', 'png', 'bmp' ];
$user = Auth::user();
$imagePath = "{public_path()}/images/{class_basename($user)}/{$user->id}/";
$imageName = "avatar";
// go through all extensions and remove image if it exists
foreach($extensions as $ext)
{
$imageFullPath = "{$imagePath}/{$imageName}.{$ext}";
if( file_exists($imageFullPath) )
{
#unlink($imageFullPath);
break;
}
}
The less you store in your filepath, the better because you aren't locked down to any folderstructure.
For now you might store all your uploads in /public/uploads but when your app gets bigger you might want to put everything in /public/uploads/form_xyz_images. When you put your whole image path in the database you'll have to adjust all values in the database.
A better way would be to only save the filename and append the path somewhere else. For example you could use accessors and mutators to get the path: https://laravel.com/docs/master/eloquent-mutators#accessors-and-mutators

Encoding uploaded files name

I want to ask, if I have a web form, and people use it to upload something to my db. If 2 persons uploaded the same file with the same name, in the uploads directory, one of them will replace the other. So I need to change the name of every file uploaded to db to : filename201405051200.pdf or jpg or...
Here we have the filename per example image1 and the numbers are the date and time of the uploads. So any help. I am using the code shown as an answer in the link below:
Uploading blob files/images into Mysql
I used this code:
$path = "../uploads/".$_FILES['file']['name'];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time())){
...
}
but now the format type of the file is replaced by the time. So if it is img.jpg it is now img85890338jpg and wont open properly
You can use pathinfo to extract the file extension:
$fileExt = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
After that you can create your new file name:
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time().date().'.'.$fileExt)) {
}

Symfony2: Amazon S3 retrieve image and mofidy using Imagine

I'm using amazon s3 to store my images. For now I've got 3 different folders - temporary one to not accepted pictures, one for accepted and one for watermarked one.
When photo is being accepted it is copied to accepted and watermarked folders and deleted form temporary one.
The problem is with watermarked folder because I need to add watermark. During work in progress I've mocked method that is adding watermark like this:
protected function addWatermark($product)
{
$filterName = 'watermark';
$this->imagineFilterManager->getFilter($filterName)
->apply($this->imagine->open($product->getFilePath()))
->save($path, array('format' => "png"));
}
and it was pretty fine. But the problem is - mock was working on uploaded file, and FilePath was temporary file path to image.
Now I need to retrieve image from amazon s3, pass it to imagineFilterManager and save back at amazon s3 location. The problem is with retrieving photo.
I tried like this:
read method:
public function read($path)
{
return $this->fileSystem->read($path);
}
protected function addWatermark($product)
{
var_dump('addWatermark');
$filterName = 'watermark';
$path = $this->getShopPicturePath($product);
$file = $this->staticContentAdapter->read($path);
$file = imagecreatefromstring($file);
$this->imagineFilterManager->getFilter($filterName)
->apply($this->imagine->open($file))
->save($path, array('format' => "png"));
var_dump('filtered');exit;
}
but after this $this-imagine-open() returns
File Resource id #141 doesn't exist
The strange thing form me is that it is was possible for me to save image file on s3 using only path:
->save($path, array('format' => "png"));
but it is not possible to open file using only path:
->apply($this->imagine->open($file->getFilePath()))
It throws exceptions
File watermarked/asd_asd.png doesn't exist.

How to recieve & store an image file from another server, being passed programatically with paramaters?

I am using the API of an image editing website (pixlr.com) for use by members of my site. I open Pixlr.com in an iframe where they can create an image and upon SAVE, pixlr sends the image file by use of parameters.
I want to save these image files (unique for each member) in a folder on my server (or on Amazon's S3 image server), using PHP. How do I receive their parameters ("image") of the image file and store them on my/Amazon's image server?
If the image is sent to your PHP script via POST, then you should be able to do something like this:
$handle = fopen($imageName, "wb");
fwrite($handle, $_POST["image"]);
fclose($handle);
Where $imageName is the absolute path and filename of the image where you want to save it (make sure you Apache user has write permissions to that directory). Depending on the picture's encoding you may need to figure out which extension to save it with (ie .jpg, .bmp, .png, etc).
EDIT:
Looks like they are sending the image via $_FILES. Try this:
move_uploaded_file($_FILES["image"]["tmp_name"], "/home/path/domain.com/upload/". time() .".png");

Categories