best way to display image in php - php

I am storing images in mysql Db directly. what is the best way to display the image in good quality (thumbnail and original size images) using php.

So, you are storing the binary content of a image files in your database (probably a BLOB field), right?
Displaying the original size image is not a big deal, I hope you have stored the file name / file extension (or at least mime type) of the original image along with the binary data.
If you table images e. g. contains two, content which holds the binary data and file_name which holds the file name and file extension of the stored image, you can think of code like this:
$res = mysql_query("select * from images");
while($row = mysql_fetch_assoc($res)) {
$pathname = 'some/path/' . $row['file_name'];
file_put_contents($pathname, $row['content']);
}
What this does is selecting all entries from the images table and writes the binary content from the database to an outfile named after the orignal image. Consider setting the [chmod][1] after writing the outfile, depending on your server setup.
If you dont have the file name property available, then you must generate some random name (maybe using md5($row['content'])? Could be very slow though.). But you need the original file extension or the mime type of the stored image, otherwise its not easy to find out if the image is abc.JPG or abc.PNG or abc.GIF etc.
Now you can access your created image (e. g. XYZ.jpg) using http://www.domain.com/some/path/XYZ.jpg if some/path/ is within your document root folder.
With the original image stored on disk it is easy to create a thumbnail. I heartly recommend Imagemagick (check if installed on your server), but you can also roll your own thumbnail script using PHPs GDLib which is bundled with PHP and most likely available. There already a ton of prebuilt thumbnail scripts for PHP which rely on Imagemagick and/or GDLib. I havenĀ“t tried yet but heard good things about phpThumb().
One last word: you probably noticed it yourself, storing images as binary in a database is not really a good idea. Of course, if the application is already built and you have to work with things the way they are, you dont have a choice on this. But performance-wise it is way better to store just the image pathname in the database along with some meta data (like filesize, width, height etc.), keeps your db size down and the select/php code for processing the resultset fast.

The best way to display the image in good quality (thumbnail and original size images) using php is storing both original image and thumbnail in the filesystem and then generate an <img> tag to display it.

Related

Hiding secrets inside photographs with php

I have created a service that hides text inside photographs. For example:
$img_name = "myimage.jpeg";
$orig_contents = file_get_contents($img_name);
$msg = "My secret.";
$fp = fopen($img_name, "wb");
fwrite($fp, $orig_contents . $msg);
fclose($fp);
I'm curious: How much information can I hide inside photographs using this method? For example, could I embed chapters of a novel in an image file? I have added fairly large blocks of text without corrupting the image, but I'm wondering if PHP or image viewing applications impose limits on this.
(P.S. I am aware that this type of steganography is insecure; I'm just doing this for fun.)
You should take a look at Steganography. And be aware you are not hidding your data in the image. Anyone who could open the image with a text editor would see your text somewhere in the file (in this case, in the end, which is much worse). If I were you, I'd do the following:
Encrypt your data with some decent Algorithm and a strong key
Create a function that distributes your data through the file in a pseudo-random way, so that anyone would note that you're trying to put something secret in it (be aware you have to recover it afterwards). In a regular bitmap image, you can use the last bit of each pixel to save your information, since this change made by it would not be perceived by human eye, if you compared the original image with the one that has hidden data.
Pray NSA isn't reading this, otherwise you can get some serious trouble :)
No, there's essentially no limit imposed by either PHP or the JPEG format on how much data you'll be able to add to an image using this method. This works because the JPEG format stores all of the image data at the beginning of the file until some marker. After the marker, any data is assumed to be something else like a thumbnail, for example.
One cool trick (that also works with GIF images) is that you can append a ZIP file to the end of an image and the file works as both a JPEG and a ZIP file. It will be readable by both image processing programs or ZIP programs just by changing the file extension.
I think this is not the most secure way to do it, if you really want to hide string into an image, you will probably use a specific pattern to change a pixel every 10 pixels, the idea is simple convert your image to an array of integer, loop through the array and every 10 pixels change the value to the ascii character number.
Changing 1 each 10 pixel won't make a lot of noise.
To make it more secure use encoding, so use your own map to encode ascii, like #fvdalcin proposed.

What should I use to save an image in database

What should I use to save an image in the database. In what type I have to use to store and retrieve the image in PHP and MySQL.
Rule of thumb is you shouldn't be storing images in the database. Blob is available but is pretty crappy.
What you should be doing is storing the binary file on the filesystem which is many times faster than a database and in the database just store a path or link or file name and have the application load the image from the path instead.
This allows you to easily implement stuff like cdn's or san storage etc for static files. It even allows you to use something like lighttpd to display the static content images rather than apache.
https://blogs.oracle.com/manveen/entry/blob_vs_file_system_storage gives a little more information but there's plenty of stats and data on the web about the disadvantages of blobs
use BLOB Datatype which means Binary Large Object
BLOB
BLOB's may be slower than file storage, but it is much easier to copy, backup, and restore a single database file than it is to manage/maintain images in a file structure.
I also recommend storing the images in their own dedicated database (store the properties/tag information in a separate database).
Simple & optimized option is to upload the image on the server and store the string of "url of the image" in database.
Incase, you want to store actual image file only, then use Blob datatype.
Its a very bad idea to store images in database. Database is determined to save a little pieces of information - not images or files. You have HDD on that purpose.
Instead, you should save image on disk and save its filename in database. Like that:
$name = uniqid();
file_put_contents($name.".png",$image_data);
mysql_query("INSERT INTO `images` (image) VALUES ('$name.png')") or die(mysql_error());
If you really insist on saving images in DB use BLOB.

Conventions and checking file existance vs database storing

I'm building the database structure for a portal and I have some doubts related to elements that I decided aren't going to be stored in the database, typically media and specifically images.
Suppose that we have contents and every content could have a main image. Also, there is a slideshow with featured contents that need big images from the contents. An intuitive idea is leave the DB without this task and store the images with a name convention. Then, in the code (php), I could check if the file exists and then act as desired (asking to upload the image for the slideshow, showing a default image or a map instead of the needed main image...). The other extreme is storing the filename in the database, and other option is use the file name convention but store in the database a boolean instead of checking for the existence in the code.
I'm interested on the subjective perspective, but I would really like to know if there are best practices for this situation based on technical and objective reasons, or simply for practical reasons...
Store the image filename in the database with each content record. This is the most flexible option because you can easily change the selected image by updating the database record.
Suppose you add some sort of backend/admin area to manage the content. To change the content's main image you can show a dropdown of files in the images folder (and a file upload option) and easily update the record to the chosen image.
If you want a slideshow of content images, you can simply select the image filenames from the table and output <img /> tags pointing to the images.
If you do it without the database, by using a naming convention e.g. content-image-{contentId}.jpg then to change the image you would need to be renaming/deleting files and you would need to cater for different image file extensions.
I do not store images in the database. Instead I store them in a separate folder on disk and maintain a table with name, size, mimetype etc.
My practical reasons for not storing them in the database:
I use mysqldump and then a editor if I want to make changes in the db structure. That is easier without all the binary data inside the dump.
My database server runs on a fast 128GB SSD SATA 600 disk for performance. The space is limited. The images folder is mounted from a NAS storage, that is 12TB in size.
When a browser needs a images, it is not loaded with the html, but in a separate request. When delivering html there is no need that the image comes from a lighting fast storage device.

PHP & MYSQL - what should I do with my image data?

I'm creating a blog with a featured image on each post. I have a dilemma, I'm unsure what to do with my image data...
Should I insert image data into my MYSQL database using BLOB?
Or should I just create an uploader which makes a directory into the users images folder and upload the photo that way...then just reference it directly in the image field when adding a Blog Post?
Is there a standardised way?
Kind regards,
adam
Upload the files to your server and save the location of the file in your database. Less strain on your DB and your HTTP daemon is better at serving images than MySQL.
The general approach is not to store files in DB, unless you understand why do you need it to be stored there. So, since you are not sure, it's much simplier storing them in upload folder.
But, just in case you decide you need storing files (no matter images or some other) in DB, you have to declare BLOB field and then save it using some BLOB-supporting DB mechanism. 'PHP's MySQLi extension: Storing and retrieving blobs' is a good example of how it can be made
You should store images in folder. Click on below link from where you can get idea how to crop different-different size images and store images name in to database table:
How can I upload images in a normal insert form (MySql)? after upload the image should have three versions of different sizes and different names
convert the image data to base64. This can be done within PHP:
<?
$image=file_get_contents("image.png");
$image=base64_encode($image);
?>
Storing images in a DB is a good idea for secure images.
Always store images, music files etc in system files on disk, and then store the urls to them in the database. That will make it
1) faster
2) easier to configure security settings
3) better in any ways I can imagine
Disadvantage
If file system is corrupted you will have hard time recovering.
You can also use third party Image hosting sites too, you can use Amazon S3 or Mosso Cloud Files.
Problem with file system is it is difficult to scale.
Facebook uses cassandra to store images.
Since it is blog you can store images in filesystem.
Both are valid approaches.
They have different advantages/disadvantages.
Storing it in the database means you need to add extra code to change the image to a representation which will fit inside a INSERT/UPDATE statement (base64 is one approach, and requires equivalent decode, but you could just use mysql_real_escape_string()). Although you can't query the image directly (other than finding exact matches) it may reduce the number of seek and I/O operations required to retrieve the data compared with looking up the path in the database then retrieving the file.
It's also a lot simpler to set up replication of a database compared with setting up replication of the database AND the filesystem if you run on multiple nodes. And there's the issue og keeping filesystem and database backups synchronized.
OTOH, using a filesystem makes your data tables much smaller, and therefore faster to retrieve records from.
which makes a directory into the users images folder
You certainly don't want to allow users to upload content directly into your webserver's document tree - regardless of which route you take, the data should be stored in a location not directly accessible by the webserver but accessible by your code.

ALT text for images in HTML

We are working on a website that has tons of images and one of the requirement is to have ALT text for each image (JPG, JPEG, PNG, GIF etc). So whenever the HTML shows and image the ALT text for that image is also written to HTML along with IMG SRC.
After our discussion with developers the solutions that turned up are
1) Create a new table to hold all these image names. Then each time the image is used a db lookup is done and appropriate ALT text is added.
2) Another solution is to write some EXIF info into each file and each time they are used the EXIF info of the file is read and added to HTML as required.
Any suggestions on how to proceed. There are a lot of images so we are looking for the best solution with least load on server and loading time.
Additional info - We run PHP on our server to select images etc.
Thanks
I'ld rule out EXIF as it does not support PNG and GIF.
The db lookup sounds okay (to me) and would scale okay (as long as you did it cleverly). For example you should try to reduce lookups as much as possible.
You might even already have some of this data, and it would be useful to have data about the images anyways
I would recommend storing it in the database because I am sure you have to maintain records of these images, adding another column to a table is little work. Also, if its inside the database you can perform searches on the alt text in case you want to have such a feature.
If you wan't to give the images an alt text, it should be something that works correctly if the image is not there.
I shouldn't be "image's alt text", or "image.jpg". Rather it should be something like "Stackoverflow.com has a lot of questions and answers." when showing a SO screenshot. But if your image can't have a meaningful alt text, then just make alt="", and move on, sometimes it's simply better to give no alt text than giving a bad alt text.
Because of this, you should store the alt text for every image that means something, and not put meaningless alt text (ruling out EXIF information).
If you can live with the alt tags matching the name of the file, you can use some javascript to get all the images and add an alt tag based on the name of the file.
Something like this:
//get all the img tags
var images = document.getElementsByTagName('img');
for (i=0;i<images.length;i++)
{
//get the filename from the src
filename = images[i].src.substring(images[i].src.lastIndexOf('/')+1,images[i].src.lastIndexOf('.'));
//do any formatting here
filename = filename.replace('_',' ');
//set alt/title tags
images[i].setAttribute('alt', filename);
images[i].setAttribute('title', filename);
}
I would avoid option 2 because if you wanted to update the alt text you would need to write to the image file each time, also, if you wanted to process the images eg. generate thumbnails, the meta-data might be lost.
Option 1 seems the most logical, and if you're querying for filenames from a DB, then just get the alt text at the same time.
Maybe third option:
store ALT text in filename :)
While both solutions seem fine to me the question about required load is a bit tricky: if you get the images from a database anyway I'd store the alt tag values in the database as well. If the files are served from a directory it depends on if you are using a database at all. If you don't use a database going the EXIF route sounds like a reasonable alternative, but might create more load than using an additional database as you need to open each file to retrieve the EXIF data.
In short, go the database route if you already use a database.
I would suggest the database option, because the EXIF option will become a problem if somehow an image has to be switched with another image (transferring EXIF data is not trivial), plus parsing a lot of image files on each request would be very resource consuming.
But be it with the database or the EXIF option, I would strongly suggest that you generate a php file acting as a cache, with an associative array of image_name => alt_text, because you don't want 30 sql queries on each page load. The php file would be included as a bootstrap, so every script would have acces to the associative array, via a global variable for example.
And you would have a script that generates this file, so whenever an alt text is changed, you can easily regenerate the cache file containing the associative array.
Honest question: do you really even need to create a new table? If you're using a PHP upload mechanism anyway, couldn't you simply add a new field to the database and add the alt text, then link it as a variable as needed? The PHP would be very simple from there. Just a thought!
If you already have a database (which I presume you do), then don't add a whole new table, just add a column to the existing table where your images are. Then you can just get all the information with the same query you populate your page with. I believe this is the best option.
When you say "a lot of images", how many are we talking about? Hundreds, or thousands?
If you're in the hundreds, I would just create a PHP file with an array of the imagePath/altText pair. Then include this PHP file wherever you are referencing the image. To abstract the implementation, have a method in the PHP file to return the altText given the complete image path.
$texthash = array(
"/some/path/imageName.png" => "some alt text"
, "/some/path/imageName2.png" => "some other alt text"
);
function get_alt_text($imgpath) {
return $texthash($imgpath);
}
This strategy is fast and will not slow down your pages as long as the number of images is still relatively small. The only tricky part is making sure you keep the array sorted by image path as new images are added.
Once the number of images gets large enough that this method is slowing down performance, move the information to the database, and change the method in the PHP file to query the database. Since you've abstracted the implementation, you won't need to change any of the referencing PHP files.
Also make sure you are HTML-escaping the alt text before using it in the HTML.

Categories