Create a unique name for the uploaded image - php

I have a certain code for image upload .I found this on the internet and there was no explanation of the code either.What i can understand from the code is that php upload a certain file makes it a temporary file and then moves the temporary file to the original location
Code Looks something like this
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
What happens now is that when i try to provide an unique name to the image when it is being moved using the move_uploaded_file then a file does come up inside the folder but it says an invalid file and with the extension type of file.
My code for trying to achieve the same but with an unique name/id for the uploaded image.
$uniquesavename=time().uniqid(rand());
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $uniquesavename);
How to achieve the same as before and could you please explain me the previous code as well?

Sample code:
// Get file path from post data by using $_FILES
$filename = $_FILES["img"]["tmp_name"];
// Make sure that it's a valid image which can get width and height
list($width, $height) = getimagesize( $filename );
// Call php function move_uploaded_file to move uploaded file
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
Please try this one:
// Make sure this imagePath is end with slash
$imagePath = '/root/path/to/image/folder/';
$uniquesavename=time().uniqid(rand());
$destFile = $imagePath . $uniquesavename . '.jpg';
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $destFile);
Edit 1:
To get image type in two ways:
Get the file type from upload file name.
Use php function as below
CODE
// Get details of image
list($width, $height, $typeCode) = getimagesize($filename);
$imageType = ($typeCode == 1 ? "gif" : ($typeCode == 2 ? "jpeg" : ($typeCode == 3 ? "png" : FALSE)));

$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = "uploads/";
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
sleep(rand(1,5));
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
echo"failed, better luck next time";
}
}
here, location is folder inside directory, i mainly create folder "uploads"
time() adds timestamp , which is always unique, until two person upload at same time, which is rare.
moreover, adding 4 digit random number to it , making combination rarest
after that adding actual file name , to making combination unique.
why i use it :
u can extract timestamp later if u need to know when image was uploaded.
u can extract actual filename too.
Lets, say our so unique combination somehow fails,
then, php instance will wait for 1 to 5 second whatever random number is generated. and rename with latest timestamp and regenerated random number.
It's the best u can think of without being resource hog.

you can use
$strtotime = strtotime("now");
$filename = $strtotime.'_'.$_FILES['file']['name'];

Related

Upload images with random name and also delete older image from the directory

I am trying to upload an image with a random name, also when I update the image, I want the previous image to be deleted.
Code below:
$banner=$_FILES ['banner']['name'];
$upload="../image/banner/";
$target_file = $upload.basename($_FILES["banner"]["name"]);
$imagefiletype= pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["banner"]["tmp_name"], $target_file );
Any help will be appreciated.
When update your new images at that time first store old image name in variable. after update true then delete old image in your directory using "unlink" function.
$old_image = "xyz" // store old image name
after update query success
unlink('../image/banner/'.$old_image); // delete old image in your directory
You can do it like this.
$path = 'image/folder/'; $unique_name=time().uniqid(rand());
$File_with_location = $path . $unique_name . '.' . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));
$filename = $_FILES["img"]["tmp_name"];
move_uploaded_file($filename, $File_with_location);
for deleting old image you can use this
$path = './root/home/folder/file.jpg';
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}

Image upload and resize function not working as it must

I have simple resize image function in my laravel project. It should upload original image and make thumbnail of it.
After form submitting I got two images but the original image is placed in wrong directory. This is the function in my controller
if (Input::hasFile('image') && !Input::get('remove_image')) {
$file = Input::file('image');
$filename = str_random(20);
$image = new ImageResize($file);
$original = $filename . '.'. $file->getClientOriginalExtension();
$thumb = $filename . '-thumb.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/uploads', $original);
$imagePath = '/uploads/' . $original;
$thumbPath = '/uploads/' . $thumb;
$image->crop(200, 200);
$image->save('uploads/' . $thumb);
}
Basically when I upload image.jpg I get two images image.jpg and image-thumb.jpg. Both images should be save in uploads i.e. public/uploads/ BUT only thumbnail is saved there.
The original image is saved in **bootstrap**/uploads/. Why is going in bootstrap... directory? I didn't mentioned it anywhere?
You can try to replace the public_path() method to url('/'). Not sure this will help but I don't have good experiences with public_path()
Image::make($request->file('image'))->resize(462, 462)->save('upload_path/filename.jpg'));
Try This Code..
Use Image Intervention to resize and save the image
Image::make($avatar)->resize(250, 250)->save(public_folder('/uploads/'.$filename));
The resize function will resize the image and save function will save the image to uploads folder. Give a desired filename to $filename variable.
Leave only the directory to where you want to save the original. Try to change this line which is moving the image
$file->move(public_path() . '/uploads', $original);
with this one ( remove the public path )
$file->move('uploads', $original);

Detecting if user is uploading the same image

I have a form that contains an image upload and an input text box. The user will be able to upload an image and enter text without refreshing the page using Ajax. The image will be relayed to PHP and PHP will handle what to do with the image. My problem is that for the first time the user uploads an image, it'll be checked if the same image name is on the server or not. If it is, the image name will get a uniqid() and then will be uploaded. But what if the user changes the data in the text box field, but keeps the image? Then that image will be uploaded again with a uniqid() since it's already on the server. I've tried solving this using my current code for the image handling:
PHP
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
if (isset($_SESSION["size"]))
{
$prevSize = $_SESSION["size"];
if (filesize($prevSize) != filesize($size))
{
if (#getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
}
}
else
{
$_SESSION["size"] = $size;
if (#getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
}
move_uploaded_file($tempName, $target_file);
Unfortunately, this code isn't working like I want it to. If I upload the same image twice in a row, in the same session, it doesn't override my previous image. Instead, it puts it on the server with a uniqid name. What am I doing wrong? And if there's a better way in solving this, I'd love to know!
What you can do is whenever someone uploads an image, store a hash of the image, encrypt it and store it in the database on the image row.
From now on, whenever someone uploads an image run a query like this:
SELECT COUNT(*) FROM images WHERE hash = $hash then in an if statement check if the returned value is bigger than 0, if it is, do what you need to do without re-uploading the image, and if it is 0, then upload your image and proceed
I chose a user avatar upload for this example. I'm not sure what your image is, but the workflow should be similar. No duplicate avatars will be copied to the image path.
function get_avatar_filename($filename) {
// only generate an avatar filename if the mimetype matches
switch (mime_content_type($filename)) {
case 'image/jpeg':
return sprintf('%s.jpg', hash_file('md5', $filename));
case 'image/gif':
return sprintf('%s.gif', hash_file('md5', $filename));
case 'image/png':
return sprintf('%s.png', hash_file('md5', $filename));
// otherwise the user uploaded a non-supported image
// return the default image
default:
return 'default-avatar.jpg';
}
}
function upload_avatar($avatarPath, $filename) {
// get the avatar filename
$f = get_avatar_filename($filename);
// copy the file to $avarPath only if the file doesn't already exist
if (!file_exists("{$avatarPath}/{$f}")) {
move_uploaded_file($filename, "{$avatarPath}/{$f}");
}
// return the avatar filename
return $f;
}
Now you can use these functions when you process the user form submission
// process user form submission ...
// ...
$filename = upload_avatar(
$_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/",
$_FILES['user_avatar']['tmp_name']
);
// save the avatar location for the user ...
// or whatever
$user->setAvatar($filename);
$user->save();
If the user uploads a non-supported image type, they will just be assigned default-avatar.jpg which is a file that should exist in your images directory.

PHP: Set name for image data URI

I'm stuck with a little problem and can't find a solution. I'm outputting my images to the website as base64 data URI. If someone opens the image directly in the browser the url to the image would be the data URI which works find but the name that shows in the browser tab is something random and i want to change that. I know that i could add /new+name++that+i+want at the end of the data URI to change the title that shows in the browser but sometimes there is already a name/title at the end of the data URI and in this case it would just create an error if I add something to the end. Is there any save way to set a title/name rather than adding something at the end and hoping it doesn't create an error?
Thanks for reading and have a nice day.
My Code:
$img = "uploads/images/smile.png";
$filetype = mime_content_type($img);
$imgdata = base64_encode(file_get_contents($img));
$src = "data:" . $filetype . ";base64," . $imgdata;
Use pathinfo for file type $filetype = pathinfo($path, PATHINFO_EXTENSION);
$img = "uploads/images/smile.png";
$filetype = pathinfo($img, PATHINFO_EXTENSION);
$imgdata = base64_encode(file_get_contents($img));
$src = "data:" . $filetype . ";base64," . $imgdata;

Retrieving external image and saving locally results in distorted image

Stuck on this one. I have this function below that simply takes $ImageSrc which is an external image from anywhere, eg imgur, and then saves it locally (this is not a scraper, I'm allowing people to attach images to their profiles)
public function UploadScreenshot($ImageSrc, $Title, $Description = false) {
$RandomName = substr(md5($Title . time()), 0, 20);
$UploadDir = "/home/vanrust/public_html/Screenshots/";
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
$image = file_get_contents($ImageSrc);
file_put_contents($UploadDir . $RandomName, $image);
}
The result of the file no matter what is unrecognizable.
The image:
After UploadScreenshot() has retrieved it:
Try to use rename() to move the original file to the new location and rename it.
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
rename($UploadDir . $RandomName, $ImageSrc);
}
Alternatively, you can use move_uploaded_file() if your $ImageSrc does contain a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism).
file_put_contents() needs to be used with caution. A single offset (in binary codes) at the beginning or at the end of the file will significantly alter the picture. It requires a validation at the end to compare both files bytes.

Categories