tags:

views:

173

answers:

6

Suppose there is a site where we are uploading images. Now, when we have to display the album of that particular logged-in user. What we can do is:

  1. We save the path of that image in the database and retrieve the image
  2. Save only the name(unique) of the image and use fopen() because we save all the uploaded images in a single folder

Now my question is:

What are the various options to retrieve that file instead of fopen()? Meaning, is there anything else that is faster than this?

A: 

I don't know if it's faster, but file_get_contents() is more succinct. With a binary file like an image you will probably want to use the FILE_BINARY flag.

Chris Kloberdanz
A: 

I think readfile() is would be best?

Irmantas
Do you have any evidence to support that?
Charlie Somerville
A: 

For ultimate speed, keep the file stored in a RAM disk.

Look up tmpfs for more details.

Charlie Somerville
+5  A: 

You shouldn't need to use fopen to display a gallery. Why can't you just show the images like that:

<img src="/folder/with/your/images/<?php echo $unique_name; ?>" />

?

Tomas Markauskas
I think this is the best solution, however, I'm wondering if the images are stored in a non-web-accessible directory to prevent people URL browsing?
MalphasWats
A: 

If your web server is lighttpd or Apache with mod_xsendfile, then you can send the file by specifying a special X-Sendfile header. This allows the web server to make a sendfile call, which can be very, very fast.

The reason is sendfile is usually an optimized kernel call which can take bits from the file system and directly put them on a TCP socket.

brianegge
A: 

How many images are in your uploaded folder?

  • If you have thousands of them, consider making your folders smaller.
  • For example, the terminfo system uses /usr/share/lib/terminfo/a/ subdirectory to hold entries that begin with 'a'.
  • The CPAN system for Perl uses authors/id/A/AB/ABRAHAM to divide things up.

The point is that the system probably does a linear search through the directory to find the files, and not all of them can be at the beginning. By splitting them up into smaller sub-directories, you greatly improve the lookup time - and hence the speed of any and all file open functions.

There was a paper or discussion about this - I think it was in Eric Raymond's 'The Art of Unix Programming', but it referenced some papers where the measurements were made - and it can give valuable speedups at minimal programming cost.

If done properly, you can write a simple function to generate the file name from the image storage base directory and the image file name.

Jonathan Leffler