Articles
Ce document est aussi disponible en français
However, it is not always easy to know where your application lives on the server : it may even change quite often. Moreover, if the path and filename was handed by the user, or did transit via Internet, il is important to validation this value.
The simplest solution is to use the realpath() function, to turn a path into an absolute path. realpath() is also able to handle symbolic links.
Example n°1
<?php require_once realpath('../../config/application.conf.php'); ?>realpath() is best used before dirname(), which gives the file path, and basename(), which gives the file name.
Example n°2
My file index.php must include another file, init.inc.php, stored in the includes folder. The latter is stored with the index.php file. Hierarchy is the following :
- application/
- includes/
- init.inc.php
- index.php
<?php require_once realpath('./includes/init.inc.php'); ?>Though, the problem here is that whenever inclusion happens after chdir(), it will fail. To harden the inclusion, it is better to use the __FILE__constant, which holds the full path of the current executing file. Then, dirname() will give you the path name.
<?php /** * Changer le répertoire courant */ chdir('../../'); /** * <a href="http://www.php.net/chdir">chdir()</a> above will have no impact on the next inclusion */ require_once realpath(dirname(__FILE__) . './includes/init.inc.php'); ?>Example n°3
Last but not least, function pathinfo() give access to file path, filename and even extension :
<?php print_r(__FILE__); /** * Array * ( * [dirname] => /home/mon_compte/public_html * [basename] => index.php * [extension] => php * [filename] => index */ ?>Don't use pathinfo() to guess the type of the file. Instead, rely on extension Fileinfo.
Keep in mind
-
realpath() is available since PHP 4.
- realpath() return FALSE upon error.
| < Précédent | Suivant > |
|---|
Commentaires
Vous pouvez ajouter votre commentaire! |
Vous devez vous connecter pour commenter


