Home > Article > Backend Development > What is the difference between getcwd() and __FILE__ methods in php
PHP can use Magic constantFILE to get the absolute path of the current file, regardless of whether the current file is included in other files. This is very useful in many cases, but sometimes when we When performing operations such as reading and writing files, it is relative to the working directory of the current script, which is the directory of the entry php file. At this time, you can use another function getcwd() provided by php to obtain
See below Two examples
Create the file test.php in ch06 and the content is as follows
<?php $a= getcwd(); //变量a的值为D:\php\zend6.1\ch6 $b=FILE; //变量b的值为D:\php\zend6.1\ch6\test.php ?>
It can be seen that getcwd() returns the absolute path of the file but does not include the name of the file itself. FILE returns the absolute path where the file is located but includes the name of the file itself.
Create the folder admincp folder under the ch06 project. Create the file fff.php in the admincp folder. The code is as follows
<?php include_once '../test.php'; echo $a;//变量a中的值是D:\php\zend6.1\ch6\admincp echo '<pre class="brush:php;toolbar:false">'; echo $b;//变量b中的值是D:\php\zend6.1\ch6\test.php ?>
It can be seen that the test.php file is included in another file. The path variable a of test.php obtained using getcwd() in the test.php file changes after inclusion. Directory structureAdded the directory admincp where ffff.php is located, so ·FILE is better when using file positioning
Example
<?php define('PATH_ROOT',($PATH_ROOT=dirname(FILE))?$PATH_ROOT:'..'); $PATH_admincp=PATH_ROOT.'\admincp'; $PATH_picture=PATH_ROOT.'\pciture'; $PATH_admincp_include=$PATH_admincp.'\include'; ?>
<?php include_once dirname(FILE).'/../../path.php'; include_once PATH_ROOT."/con_ini.php"; ?>
The above is the detailed content of What is the difference between getcwd() and __FILE__ methods in php. For more information, please follow other related articles on the PHP Chinese website!