PHP: Set name for image data URI - php

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;

Related

base64 encoding for image src

When I echo the following:
$im_dec = base64_decode($row['image']);
I obtain the desired URL:
https://www.ft.com/__origami/service/image/v2/images/raw/http%3A%2F%2Fprod-upp-image-read.ft.com%2F1263ad72-2d9a-11e7-9555-23ef563ecf9a?source=next&fit=scale-down&compression=best&width=210
Then I use this URL to be the src of my img:
$newImage = $dom->createElement('img');
$newImage->setAttribute("src", $im_dec);
$newImage->setAttribute("class", "articleImage");
$newTitle->appendChild($newImage);
And when I check the src attribute in my html document, I get a modified url where
& is replaced by & for example and many more weird stuff..
Some characters were modified and I don't know how to avoid it. I tried many things but I thought base64 encoding would work...
Help please!
You can convert an image to base64 encoding with the following example:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

Create a unique name for the uploaded image

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

How do I get a File Extension in PHP if I only have the File Name?

I have the path to an image file /files/uploads/1 but as you can see, I don't have an extension so I can't display the image. How can I get the extension of the file so I can display it? Thanks!
EDIT: Here is come code I have tried. BMP, PNG, JPG, JPEG and GIF are the only possible extensions, but $path ends up never getting assigned a value.
$exts = array('bmp','png','jpg','jpeg','gif');
foreach ($exts as $ext) {
if (file_exists("/files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
Personally, I had a problem where I had an unnecessary slash (/) before my path in the file_exists check, but the solution to the question is still the same.
$exts = array('bmp','png','jpg','jpeg','gif','swf','psd','tiff','jpc','jp2','jpx','jb2','swc','iff','wbmp','xbm','ico');
foreach ($exts as $ext) {
if (file_exists("files/uploads/" . $id . "." . $ext)) {
$path = "/files/uploads/" . $id . "." . $ext;
}
}
You don't need a file extension to show an image.
<img src="/files/uploads/1">
Will show the image. It's the same way the placehold.it images work
<img src="http://placehold.it/350x150">
First of all , I think when you get the file name for the image that means no need to add extension , so you have the file name and image folder
it should simply look like this :
$fullpath = ('uploadword/'.$filename);
// then call it
<img src='".$fullpath."'>
The normal scenario to upload all the images in specific folder then get the filename and save it in data base
move_uploaded_file($file_tmp,"upload/".$filename);
Some professional make it more sophisticated to make filename unique ,because they expected some duplicated values and many reasons , here is one simple technique :
$anynameorfunction = "";// random number etc...
$newname = $anynameorfunction.$filename;
move_uploaded_file($file_tmp,"upload/".$newname);
So, when they call it again it should be simple like this
$fullpath = ('uploadword/'.$newname);
// then call it
<img src='".$newname."'>
This is in very simple way and i wish you get what i mean

php return image from url

I want to return an image over an URL like http://placehold.it/500x500.
I have my URL http://example.inc/assets/image/35345, which calls an action on controller. The controller get some data (name, id, etc.) from database and also a binary string of the image content.
On the frontend site, i have my img tag, where i want to call the url in my src attribute.
<img src="http://example.inc/assets/image/35345">
Some more information, i use slim PHP Framework and my server is an ubuntu 13.x system (vagrant etc.). I am an typically frontend developer and dont have good skills # PHP.
Following snippets works:
$file = fopen($name, 'wb');
fwrite($file, $binaryData);
fclose($file);
but I dont want to generate files in a directory. Is this possible?
EDIT: Content-Type and Content-Length Headers are set, that is not the problem.
Grab the contents of the image, base_64 encode it, then return a a base64 image.
$file = file_get_contents($name);
list($width, $height, $type, $attr) = getimagesize($file);
echo '<img src="data:image/'.$type.';'.base64_encode($file).'"/>';
You should upload images in directory by using something like this. This code will upload your image in directory.
if ($_FILES['file']['name'] != "") {
$filename = $_FILES['file']['name']; //getting name of the file from form
$filesize = $_FILES['file']['size'];
$info = new SplFileInfo($filename);
$ext = $info->getExtension();
$filesize1 = ($filesize * .0009765625) * .0009765625;
if (!($ext == 'jpg' || $ext == 'png' || $ext == 'jpeg')) {
//set some error message and redirect
}
if ($filesize1 >= 5.0) {
//set message image size should be less than 5 mb
}
$target_path = $_SERVER['DOCUMENT_ROOT'] . "../images/profile_images/";
move_uploaded_file($_FILES['file']['tmp_name'], "$target_path" . $_FILES['file']['name']) or
die("Could not copy file!");
}
Insert image name(with extension) in database.($filename here)
Fetch image name from database and store in variable($profile_image here),use it in img src.
<a href='../images/profile_images/$profile_image'><img alt='Avatar' src='../images/profile_images/$profile_image'></a>
You can use only Anchor tag to redirect user on image in another tab in browser.
hope this answer will help you.
Because i had an mssql database with iso charset i have converted all of my results to utf-8, the problem was, that the bytestring also converted to utf-8.
after non converting the bytestring i also returned the bytestring and set the header content type to image/extension

how to display uploaded image on a website without saving it in a database using php

I'm working in a content based image retrieval php project.The user should upload an image to retrieve images similar to it . I need to display the query image without saving it in database. I tried two different ways to do that but it didn't work. The image appear as image icon.
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, $fileSize);
$content = addslashes($content);
I tried this:
echo '<img src="data:image/jpeg;base64,' . base64_encode( $content ) . '" height=200 width=200 />';
and this:
header("content-type: image/jpeg");
echo $content;
take a look at this jquery plugin. See Documentation section and it's a PHP implementation example. Basically, the plugin upload the image, save temporally on server file system and then send back so client to be rendered. Once it's on your file system you can do whatever you want with it (make the query, delete it for example). I think it's a good aproach, it was to me!!.
Hope This Helps!!

Categories