PHP 中的 file_exist() 是一个非常昂贵的操作吗? [英] Is file_exist() in PHP a very expensive operation?

查看:39
本文介绍了PHP 中的 file_exist() 是一个非常昂贵的操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将头像添加到我正在设计的论坛引擎中,我正在讨论是否做一些简单的事情(论坛图片名为 .png)并在显示文件之前使用 PHP 检查文件是否存在,或者做一些更复杂的事情(但不多)并使用数据库字段来包含要显示的图像的名称.

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.

我个人更愿意使用 file_exists() 方法,因为如果当前的头像不存在(还),这给了我一种简单的方法来回退到默认"头像,并且它易于实现代码明智.但是,我担心性能,因为这将在论坛阅读页面上按页面加载显示的每个用户运行一次.所以我想知道,PHP 中的 file_exists() 函数是否会导致任何严重的减速,从而在高流量条件下导致显着的性能下降?

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:我能看到的代码差异是文件检查版本让文件说话,而数据库表单相信数据库是准确的,不会费心检查.(当然,它只是一个传递给浏览器的网址.)

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.)

推荐答案

和其他发帖人说的一样,file_exists() 的结果会被 PHP 自动缓存以提高性能.

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

但是,如果您已经从数据库中读取用户信息,您也可以将信息存储在那里.如果只允许用户使用一个头像,您可以只在有头像"(1/0) 的列中存储一个位,然后将文件名与用户 ID 相同,并使用类似 SELECT 的内容CONCAT(IF(has_avatar, id, 'default'), '.png') 作为用户的头像

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

您还可以考虑将实际图像作为 BLOB 存储在数据库中.将其放在自己的表中,而不是将其作为列附加到用户表中.这样做的好处是让您的论坛非常容易备份 - 您只需导出数据库即可.

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.

这篇关于PHP 中的 file_exist() 是一个非常昂贵的操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆