What is the difference between getcwd() and __FILE__ methods in php

怪我咯
Release: 2023-03-13 12:32:01
Original
1436 people have browsed it

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
?>
Copy after login

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 &#39;../test.php&#39;;
echo $a;//变量a中的值是D:\php\zend6.1\ch6\admincp
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
echo $b;//变量b中的值是D:\php\zend6.1\ch6\test.php
?>
Copy after login

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(&#39;PATH_ROOT&#39;,($PATH_ROOT=dirname(FILE))?$PATH_ROOT:&#39;..&#39;);
$PATH_admincp=PATH_ROOT.&#39;\admincp&#39;;
$PATH_picture=PATH_ROOT.&#39;\pciture&#39;;
$PATH_admincp_include=$PATH_admincp.&#39;\include&#39;;
?>
Copy after login
<?php
include_once dirname(FILE).&#39;/../../path.php&#39;;
include_once PATH_ROOT."/con_ini.php";
?>
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template