The easiest way is to use fopen() to see if the file can be opened. If it can be opened, the file will of course exist.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
fopen() function opens a file or URL. If the open fails, the function returns FALSE.
Syntax: fopen(filename,mode,include_path,context)
参数 | 描述 |
---|---|
filename | 必需。规定要打开的文件或 URL。 |
mode | 必需。规定要求到该文件/流的访问类型。可能的值见下表。 |
include_path | 可选。如果也需要在 include_path 中检索文件的话,可以将该参数设为 1 或 TRUE。 |
context | 可选。规定文件句柄的环境。Context 是可以修改流的行为的一套选项。 |
Possible values for the mode parameter:
mode | 说明 |
---|---|
"r" | 只读方式打开,将文件指针指向文件头。 |
"r+" | 读写方式打开,将文件指针指向文件头。 |
"w" | 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 |
"w+" | 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 |
"a" | 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 |
"a+" | 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 |
"x" | 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 |
"x+" | 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 |
fopen() binds the name resource specified by filename to a stream. If filename is of the form "scheme://...", it is treated as a URL and PHP will search for a protocol handler (also called a wrapper protocol) to handle the scheme. If the wrapper protocol has not been registered for the protocol, PHP will emit a message to help check for potential problems in the script and continue execution of filename as if it were a normal filename.
If PHP thinks filename specifies a local file, it will try to open a stream on that file. The file must be accessible to PHP, so you need to confirm that the file access permissions allow this access. If safe mode or open_basedir is activated further restrictions apply.
If PHP believes that filename specifies a registered protocol, and the protocol is registered as a network URL, PHP will check and confirm that allow_url_fopen has been activated. If it is closed, PHP will issue a warning and the call to fopen will fail.
Usage of fopen
1 2 3 4 5 6 7 |
|
But if the server where the image resource is located hangs up, this function will wait forever, so we need a backup plan.
CURL is a very useful class library. Let’s see how to use it to judge.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
If the file does not exist after curl_exec() is executed, the following information will be returned:
1 2 3 4 5 6 |
|
Use regular expressions to see if there is a 404. If so, the file does not exist.