Home Backend Development PHP Tutorial PHP code to check whether a file or directory exists

PHP code to check whether a file or directory exists

Jul 25, 2016 am 09:08 AM

  1. $filename = '/path/to/foo.txt';
  2. if (file_exists($filename)) {
  3. echo "The file $filename exists";
  4. } else {
  5. echo "The file $filename does not exist";
  6. }
  7. ?>
Copy code

If the file exists, the displayed result of executing the PHP file is: The file C:blablaphphello.txt exists. If the file does not exist, the result of executing the PHP file is: The file C:blablaphphello.txt does not exist.

You can also use the file_exists function to test whether a directory exists, sample code:

  1. if (file_exists("C:blablaphp"))
  2. {echo "yes";}
  3. else
  4. {echo "no";}
  5. ?>
Copy code

Example

  1. /**
  2. * File or directory permission check function
  3. *
  4. * @access public
  5. * @param string $file_path file path
  6. * @param bool $rename_prv Whether to check the permission to execute the rename() function when checking modification permissions
  7. *
  8. * @ return int The value range of the return value is {0 <= x <= 15}. The meaning of each value can be derived from the combination of four binary numbers.
  9. * The return value is in binary notation, and the four digits from high to low respectively represent
  10. * permissions to execute the rename() function, permissions to append content to files, permissions to write files, and permissions to read files.
  11. */
  12. function file_mode_info($file_path)
  13. {
  14. /* If it does not exist, it is unreadable, unwritable, and unchangeable*/
  15. if (! file_exists($file_path))
  16. {
  17. return false;
  18. }
  19. $mark = 0;
  20. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
  21. {
  22. /* test file*/
  23. $test_file = $file_path . '/cf_test.txt';
  24. /* If it is a directory*/
  25. if (is_dir($file_path))
  26. {
  27. /* Check whether the directory is readable*/
  28. $dir = @opendir($ file_path);
  29. if ($dir === false)
  30. {
  31. return $mark; //If the directory fails to open, return directly to the directory that cannot be modified, written, or read
  32. }
  33. if (@readdir($dir) ! == false)
  34. {
  35. $mark ^= 1; //The directory is readable 001, the directory is unreadable 000
  36. }
  37. @closedir($dir);
  38. /* Check whether the directory is writable*/
  39. $fp = @fopen ($test_file, 'wb');
  40. if ($fp === false)
  41. {
  42. return $mark; //If the file in the directory fails to be created, it returns unwritable.
  43. }
  44. if (@fwrite($fp, 'directory access testing.') !== false)
  45. {
  46. $mark ^= 2; //The directory is writable and readable 011, the directory is writable and unreadable 010
  47. }
  48. @fclose($fp);
  49. @unlink($test_file);
  50. /* Check whether the directory can be modified*/
  51. $fp = @fopen($test_file, 'ab+');
  52. if ($fp === false)
  53. {
  54. return $mark;
  55. }
  56. if (@fwrite($fp, "modify test.rn") !== false)
  57. {
  58. $mark ^= 4;
  59. }
  60. @fclose($fp);
  61. /* Check whether the directory has permission to execute the rename() function*/
  62. if (@rename($test_file, $test_file) !== false)
  63. {
  64. $mark ^= 8;
  65. }
  66. @unlink($test_file );
  67. }
  68. /* If it is a file*/
  69. elseif (is_file($file_path))
  70. {
  71. /* Open in read mode*/
  72. $fp = @fopen($file_path, 'rb');
  73. if ( $fp)
  74. {
  75. $mark ^= 1; //Readable 001
  76. }
  77. @fclose($fp);
  78. /* Try to modify the file*/
  79. $fp = @fopen($file_path, 'ab+') ;
  80. if ($fp && @fwrite($fp, '') !== false)
  81. {
  82. $mark ^= 6; //Can be modified, written and read 111, cannot be modified, written and read 011...
  83. }
  84. @fclose($fp);
  85. /* Check whether the directory has permission to execute the rename() function*/
  86. if (@rename($test_file, $test_file) !== false)
  87. {
  88. $mark ^ = 8;
  89. }
  90. }
  91. }
  92. else
  93. {
  94. if (@is_readable($file_path))
  95. {
  96. $mark ^= 1;
  97. }
  98. if (@is_writable($file_path))
  99. {
  100. $mark ^ = 14;
  101. }
  102. }
  103. return $mark;
  104. }
  105. ?>
Copy code

Example of PHP judging whether the directory exists:

  1. /*---------------
  2. * Write xml data stream to xml file
  3. * @param $xmlData
  4. * @return bool|string
  5. */
  6. function writeXmlFile($xmlData)
  7. {
  8. $time = time(); //Get the timestamp, used to name the file
  9. $path = dirname(__FILE__); //Get the current absolute path
  10. $path = substr_replace($path, "", stripos($path, "actionsdata")); //Replace the inherent path of this file with an empty one
  11. $path .= "xmlFiles"; //Storage directory name
  12. / *Determine whether the target directory exists, if not, create a new one*/
  13. if(!is_dir($path))
  14. {
  15. mkdir($path); //Create a new directory
  16. }
  17. /*Record the complete path and file name*/
  18. $filePathAndName = $path.$time.".xml";
  19. /*Open the file, the file name is + <.xml>*/
  20. $fp = fopen($filePathAndName, "w") ;
  21. if(!$fp)
  22. {
  23. return false;
  24. }
  25. /*Write to file stream*/
  26. $flag = fwrite($fp, $xmlData);
  27. if(!$flag)
  28. {
  29. return false ;
  30. }
  31. fclose($fp);
  32. return $filePathAndName;
  33. }
  34. ?>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles