Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is file_exist() in PHP a very expensive operation?

I'm adding avatars to a forum engine I'm designing, and I'm debating whether to do something simple (forum image is named .png) and use PHP to check if the file exists before displaying it, or to do something a bit more complicated (but not much) and use a database field to contain the name of the image to show.

I'd much rather go with the file_exists() method personally, as that gives me an easy way to fall back to a "default" avatar if the current one doesn't exist (yet), and its simple to implement code wise. However, I'm worried about performance, since this will be run once per user shown per pageload on the forum read pages. So I'd like to know, does the file_exists() function in PHP cause any major slowdowns that would cause significant performance hits in high traffic conditions?

If not, great. If it does, what is your opinion on alternatives for keeping track of a user-uploaded image? Thanks!

PS: The code differences I can see are that the file checking versions lets the files do the talking, while the database form trusts that the database is accurate and doesn't bother to check. (its just a url that gets passed to the browser of course.)

like image 858
Nicholas Flynt Avatar asked Nov 25 '08 07:11

Nicholas Flynt


2 Answers

As well as what the other posters have said, the result of file_exists() is automatically cached by PHP to improve performance.

However, if you're already reading user info from the database, you may as well store the information in there. If the user is only allowed one avatar, you could just store a single bit in a column for "has avatar" (1/0), and then have the filename the same as the user id, and use something like SELECT CONCAT(IF(has_avatar, id, 'default'), '.png') AS avatar FROM users

You could also consider storing the actual image in the database as a BLOB. Put it in its own table rather than attaching it as a column to the user table. This has the benefit that it makes your forum very easy to back up - you just export the database.

like image 163
MrZebra Avatar answered Sep 19 '22 17:09

MrZebra


Since your web server will already be doing a lot of (the equivalent of) file_exists() operations in the process of showing your web page, one more run by your script probably won't have a measurable impact. The web server will probably do at least:

  • one for each subdirectory of the web root (to check existence and for symlinks)
  • one to check for a .htaccess file for each subdirectory of the web root
  • one for the existence of your script

This is not considering more of them that PHP might do itself.

like image 20
Greg Hewgill Avatar answered Sep 21 '22 17:09

Greg Hewgill