php if file exists – How to Check if a File Exists in PHP?

php if file exists – using PHP | file_exists( ), file_exists() function, Use the is_file(), Use the is_readable() function and Use the is_writable() function to check if a file exists and writable.

How to Check If a File Exists in PHP?

php if file exists – It’s an inbuilt function which is used to check whether a file or directory exists or not.

Check if a file exists using the file_exists() function

file_exists ( string $filename ) : bool

Example

<?php

$website_information_file = 'pakainfo.txt';

if (file_exists($website_information_file)) {
	echo 'The file ' . $website_information_file . ' exists';
} else {
	echo 'The file ' . $website_information_file . ' does not exist';
}

Check if a file exists using the is_file() function

index.php

<?php

$website_information_file = 'pakainfo.txt';

if (is_file($website_information_file)) {
	echo 'The file ' . $website_information_file . ' exists';
} else {
	echo 'The file ' . $website_information_file . ' does not exist';
}

Check if a file exists and readable

index.php

$website_information_file = 'pakainfo.txt';

if (is_readable($website_information_file)) {
	echo 'The file ' . $website_information_file . ' exists and is readable';
} else {
	echo 'The file ' . $website_information_file . ' may not exist or unreadable';
}

Check if a file exists and writable

index.php

<?php

$website_information_file = 'pakainfo.txt';

if (is_writable($website_information_file)) {
	echo sprintf('file %s exists and writable', $website_information_file);
} else {
	echo sprintf('file %s does not exist or is not writable', $website_information_file);
}

Also Read:

Read Also:  10 little Importance PHP functions list with Example

Checking if a File Exists in PHP

index.php

<?php
 
$website_information_file = "pakainfo.txt";
$directory = "pakainfo.zip";
 
if(file_exists($website_information_file)) {
    echo 'The file "'.$website_information_file.'" exists.';
}
 
if(is_file($website_information_file)) {
    echo '"'.$website_information_file.'" is indeed a file.';
}
 
if(is_dir($directory)) {
    echo '"'.$directory.'" turned out to be a directory.';
}
 
?>

Results

The file "pakainfo.txt" exists.
"pakainfo.txt" is indeed a file.
"pakainfo.zip" turned out to be a directory.

I hope you get an idea about php if file exists.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.