How to check if a php file exists. Checking the existence of a file in PHP. Using the function in practice

The required parameter for this function is pathname, which specifies the path to the directory to be created.

mkdir( "newfolder" );

If you specify the folder in this way, it will be created in the same directory from which the PHP script was launched. If you need to create a directory in a different location, you can specify a relative path to the folder being created or specify the full path from the site's root directory.

mkdir( "../newfolder" ); // one level down

mkdir("/folder1/folder2/newfolder" ); // full path

In the last example, the prerequisite is the existence of the subdirectories "folder1" and "folder2". If they are not there, the function in this form will not be able to create the folder and will return an error:

Warning: mkdir() : No such file or directory in …

If successful, the function returns True. If the pack was not created, False is returned.

if (mkdir("newfolder"))
echo "Folder created successfully";
else
echo "Folder not created";

But you should not use this function without checking for the presence of a folder, since the server will still display an error that the folder could not be created.

Assigning rights when creating a folder

The second optional parameter of the mkdir function is responsible for assigning rights to the created folder. By default, the maximum privileges are assigned – 0777.

Permissions are assigned using an octal value with a mandatory leading zero. Apart from the first zero, the numbers represent access levels for the owner, for the owner's group, for everyone else.

0 – access denied;

1 – read access;

2 – write access;

4 – execution access.

Most often, rights are specified as a composite amount, for example:

7 – full access (1+2+4);

5 – reading and execution (1+4).

mkdir( "newfolder" , 0777); // full access for everyone

Creating multiple nested subdirectories

You can create several subfolders at once by simply specifying another optional Boolean parameter – recursive.

mkdir("folder1/folder2/newfolder" , 0777, True ); // full access for everyone

In this case, if there are no folders "folder1" and "folder2", the function will create both them and the folder "newfolder". If no other problems arise, no error messages will be displayed and the function will return True.

Deleting a folder

An empty folder in PHP can be deleted using the rmdir function. The dirname parameter also specifies the full or relative path to the directory to be deleted:

rmdir( "myfolder" );

rmdir("folder1/folder2/myfolder" );

In each of these cases, only the "myfolder" folder is deleted. If there is no folder or the path is specified incorrectly, an error will be displayed:

Warning: rmdir(myfolder) : No such file or directory in …

Deleting a non-empty folder

Removing a non-empty directory is done by sequentially deleting the subfiles in the folder with the unlink function, and then deleting the empty folder with the rmdir function. You can use a function like this to do this:

function my_delete_dir($mypath)(
$dir = opendir($mypath);
while (($file = readdir($dir)))(
if (is_file($mypath."/" .$file))
unlink($mypath. "/" .$file);
elseif (is_dir($mypath."/" .$file) && ($file != "." ) && ($file != ".." ))
my_delete_dir($mypath."/" .$file);
}
closedir($dir);
rmdir($mypath);
}

my_delete_dir("myfolder" ); // function call

Checking the existence of a directory

Before most operations with directories, it is worth checking whether they exist. The file_exists function is used for this.

In addition, you need to make sure that the specified object is a folder and not a file - the is_dir function. The folder to be scanned is specified by a relative or full path.

if (file_exists("myfolder"))
echo "The specified folder exists";
else
echo "The specified folder does not exist";

if (is_dir("myfolder"))
echo "The specified folder object";
else
echo "The specified object is not a folder";

The widespread use of databases has not made the conventional file system irrelevant. Writing and reading files still occupy a significant place in programming.

Algorithms for checking the presence of a file allow you to avoid errors when executing code. The PHP file_exists function offers a simple solution for checking the existence of a file or directory.

Syntax and usage of the file_exists function

The result of the function is true or false. The only parameter is the file name and path to it. The function result is cached because if PHP file_exists does not work, but the file actually exists, then this is an algorithm error.

By using the clearstatcache() function, you can avoid many pitfalls in examining the state of an accessible file system. But be aware that on a non-existent file, PHP file_exists will return false until the file you are looking for is created, and then will return true even when it has already been deleted.

The correct combination of the clearstatcache() function and file system-related functions (for example, is_writable(), is_readable(), is_executable(), is_file(), is_dir() and others) allows you to avoid “hidden” script execution errors.

Caching significantly improves system performance, but in some cases it can create truly unreliable results on important files and cause a serious, hard-to-detect runtime error.

PHP function parameter file_exists

PHP can be installed on different computing platforms, and therefore the path and file naming may be different.

The documentation states that PHP checks based on UID/GID rather than effective identifiers. Developing an algorithm using PHP file_exists, you should pay attention not only to the correct slashes (forward or backward), the encoding of the path to the file and the name of the file itself, but also check for the presence of the required case, correct characters, access rights and other circumstances.

A negative result may be affected by the encoding of the script file and may require conversion of the character string retrieved from the database.

Using the function in practice

Areas of use PHP scripts differ significantly. This is not to say that PHP file_exists is used solely for storing system information, data files, objects or dynamically generated images.

There are frequent cases of using streaming generation of large volumes of temporary information that are not effectively placed in a database immediately. Information from different visitors can flow to the site, and only after preliminary processing for a certain period of time necessary information must be placed in database tables.

Reading system files may cause caching due to multiple page refreshes or incorrect visitor actions. There are quite a lot of situations in reality, but when used correctly, the function allows you to write safe and reliable code.

There are times when you need to check whether a specified file exists or not, for example, in order to subsequently perform some actions on the file.

I also encountered this issue when developing the module. And I found two options for solving the problem.

Checking the existence of a file using a URL link

In PHP there is a function " fopen", which can be used to open the specified URL.

What are we doing? We try to open the file, and if we succeed, then the file exists, otherwise, the file does not exist.

Implementation:

But what if we have not one file, but several, so to speak, an array of links? This is exactly the task that stood before me from the very beginning. And the solution to this problem is as follows:

In this case, we get a list of only those files that exist.

Checking the existence of a local file

The word “local” means that the script and files for verification are located on the same server. If you have a fairly large array of links, this option is the best for solving the problem, since we are not making a request for third party server, but scanning the specified directories.

This method uses the “file_exists” function, and, by analogy with the previous option, simply replaces part of the script:

And the same for the link array:

What's it worth note? The fact that this method is convenient for running files located within our file system. Therefore, it is advisable to indicate all links as relative ones.

By the way, when making one of the orders, it was with this method that I was able to scan about 135,000 files in just a couple of seconds.

There are times when you need to check whether a specified file exists or not, for example, in order to subsequently perform some actions on the file.

I also encountered this issue when developing the module. And I found two options for solving the problem.

Checking the existence of a file using a URL link

In PHP there is a function " fopen", which can be used to open the specified URL.

What are we doing? We try to open the file, and if we succeed, then the file exists, otherwise, the file does not exist.

Implementation:

But what if we have not one file, but several, so to speak, an array of links? This is exactly the task that stood before me from the very beginning. And the solution to this problem is as follows:

In this case, we get a list of only those files that exist.

Checking the existence of a local file

The word “local” means that the script and files for verification are located on the same server. If you have a fairly large array of links, this option is the best for solving the problem, since we are not making a request to a third-party server, but scanning the specified directories.

This method uses the “file_exists” function, and, by analogy with the previous option, simply replaces part of the script:

And the same for the link array:

What's it worth note? The fact that this method is convenient for running files located within our file system. Therefore, it is advisable to indicate all links as relative ones.

By the way, when making one of the orders, it was with this method that I was able to scan about 135,000 files in just a couple of seconds.

Description:

bool file_exists (string $filename)

Checks availability specified file or catalogue.

List of parameters:

Path to a file or directory.

On Windows platforms, to check for files on network resources, use names like //computername/share/filename or \\computername\share\filename.

Return values:

Returns TRUE if the file or directory specified by filename exists, otherwise returns FALSE.

Comment:

This function returns FALS E is for symbolic links pointing to non-existent files.

Attention!

If files are not available due to restrictions imposed by safe mode, That this function will return FALSE. However, these files can still be included if they are located in the safe_mode_include_dir directory.

Comment:

Comment:

Since the integer type in PHP is a signed integer and many platforms use 32-bit integers, some file system functions may return unexpected results for files larger than 2GB.

Examples:

Example #1 Checking file existence:

$filename = '/path/to/foo.txt'; if (file_exists($filename)) ( echo "File $filename exists"; ) else ( echo "File $filename does not exist"; )

file_exists

(PHP 3, PHP 4, PHP 5)

file_exists— Check the presence of the specified file or directory

Description

bool file_exists(string filename)

Returns if the file or directory with the name specified in the filename parameter exists; returns otherwise.

On Windows platforms, to check for files on network shares, use names like or.

Example 1: Checking if a file exists

Comment: The results of this function are cached. More detailed information see section clearstatcache().

Clue: As of PHP 5.0.0, this feature can also be used with some url packers. List of wrappers supported by the feature family stat(), see Appendix. M.

See also function descriptions is_readable(), is_writable(), is_file() And file().

See also:
All functions file
Description on ru2.php.net
Description on php.ru

You need the filename in quotes at a minimum (as a string):

Also, make sure it is properly verified. And then it will only work when activated in your PHP configuration

Try this:

At first you need understand: have you have no files .
File is an object file system, but you are making your request using the HTTP protocol, which does not support files other than URLs.

So you should request the unused file using your browser and look at the response code.

PHP, checking the existence/presence of a remote file

if it's not a 404 you can't use any wrappers to see if the file exists and you have to query your cdn using some other protocol like FTP

Here the simplest way check if the file exists:

There is a big difference between and.

php.net/manual/en/function.is-file.php returns true for (regular) files:

Returns TRUE, if the filename exists and is a regular file, otherwise FALSE .

returns true for both files and directories:

Returns TRUE, if there is a file or directory specified by file name; FALSE in otherwise.

Note.For more information on this issue also check this question using.

you can use cURL. You might get cURL just to give you the headers and not the body, which could make it faster. A bad domain can always take a while because you'll be waiting for the request to time out; you can probably change the timeout length using cURL.

Here's an example:

try it:

reads not only files, but also paths. so when empty, the command will work as if it were written like this:

if the /images/ directory exists, the function will still return.

I usually write it like this:

If you are using curl, you can try the following script:

Return values

Returns if the file or directory specified by the parameter exists, otherwise returns.

Comment:

This function returns for symbolic links pointing to non-existent files.

How to check if a directory exists in PHP and delete it?

Comment:

Validation occurs using real UIDs/GIDs rather than effective identifiers.

Comment: Since the integer type in PHP is a signed integer and many platforms use 32-bit integers, some file system functions may return unexpected results for files larger than 2GB.

Examples

Example #1 Checking if a file exists

Errors

If the operation fails, a level error is generated.

  • is_readable() — Determines whether the file exists and is readable
  • is_writable() — Determines whether the file is writable
  • is_file() — Determines whether the file is a regular file
  • file() — Reads the contents of a file and puts it into an array

Return to: File system

Existence check

PHP has two ways to check if directories exist. The first is to use the file_exists() function. The principle of its operation was discussed earlier in the article on access rights. Recall that the function takes only one string parameter - the path to file system. Despite the fact that the name contains the word “file,” it works great with directories.

The second method is related to the built-in is_dir() function. It, like file_exists(), accepts a relative or absolute directory path. However, in addition to checking for existence, it will also confirm the fact that it is a directory and not a file that is located on this path. If the string describes the location of a hard or symbolic link, is_dir() will navigate to it and parse the endpoint of the path. If successful, the boolean value true is returned, and if unsuccessful, false is returned.

//create a new directory in the root of the site for checks $dirName = “($_SERVER[‘DOCUMENT_ROOT’])/directory”; if (!file_exists($dirName)) ( mkdir($dirName); ) var_dump(file_exists($dirName)); //Result: bool(true) var_dump(is_dir($dirName)); //Result: bool(true)

The note
Functions responsible for checking directories for existence may return false if there are no access rights. Such things do not depend on the PHP script; this is the level of responsibility of the operating system.

Removing a directory

To delete a directory in PHP, use the rmdir() function. As the first parameter, it needs to pass the location of the directory. Similar to the above examples, the Boolean values ​​true or false will be returned.

Deleting a directory may seem like a simple task. However, in most cases this is not the case. The rmdir() function only works with an empty directory and returns false if it contains anything else. In this case, you need to use recursive deletion.

//create a temporary directory for demonstration $dirName = “($_SERVER[‘DOCUMENT_ROOT’])/directory”; if (!file_exists($dirName)) ( mkdir($dirName); ) if (rmdir($dirName)) ( echo ‘The directory was deleted successfully’; ) else ( echo ‘The directory could not be deleted’; )

Recursive deletion

There is no easy way to delete a full directory.

Below we provide two examples of the implementation of such a mechanism. It can be saved as a function and used in any part of the program code.

The first way to delete a directory in PHP is to use a recursive function. That is, a function that calls itself as long as certain conditions are met. Take a look at the example below. It's pretty simple to understand.

Checking file existence in php

We use standard function scandir() to iterate through the entire contents of a directory. If we come across a file, we call the unlink() function, and if we come across another directory, we use its name to make a recursive call.

//example of a function for recursively deleting a given directory function deleteDirectory($directoryName) ( $files = array_diff(scandir($directoryName), ['.', '..']); foreach ($files as $file) ( if (is_dir (“$directoryName/$file”)) ( deleteDirectory(“$directoryName/$file”); ) else ( unlink(“$directoryName/$file”); ) ) return rmdir($directoryName);

PHP also has two built-in classes RecursiveDirectoryIterator and RecursiveIteratorIterator. They can be used to iterate through all nesting levels of a specified directory. Please note that when creating an instance of the RecursiveIteratorIterator class, we use the second parameter RecursiveIteratorIterator::CHILD_FIRST. It forces all files and directories to be looped through, starting from the most nested ones. This way, you can do without explicitly calling the recursive function.

//an example of a function that does not use recursive calls function deleteDirectory($directoryName) ( $iterator = new RecursiveDirectoryIterator($directoryName); $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST); foreach ($files as $file) ( if (in_array($file->getFilename(), ['..', '.'])) ( continue; ) ($file->isDir()) ? rmdir($file) : unlink($file); rmdir($directoryName);



2024 wisemotors.ru. How it works. Iron. Mining. Cryptocurrency.