note 115287 added to function.require-once

From: Date: Sat, 28 Jun 2014 22:41:05 +0000
Subject: note 115287 added to function.require-once
Groups: php.notes 
Request: Send a blank email to php-notes+get-199778@lists.php.net to get a copy of this message
If you happen to encounter some "Warning: require_once(): failed to open stream" and you are certain the provided path is right, consider the following example & solution. Considering the following tree: + C:\server\absolute\path\ + somefolder\ - index.php + supbath + anotherfolder1\ - file1.php - file2.php + anotherfolder2\ - file3.php With the respective sources: original index.php: <?php // absolute path // inclusion status: SUCCESS require_once 'C:\server\absolute\path\subpath\anotherfolder1\file1.php'; ?> original file1.php: <?php // relative path // inclusion status: SUCCESS require_once 'file2.php'; // relative path // inclusion status: FAILURE require_once '../anotherfolder2/file3.php'; ?> You will notice the use of "\" as DIRECTORY_SEPARATOR, but the same result is obtained using "/". Assumption ? PHP does not behave as it should if it encounters a relative path starting by a '../'. Well, this is not true. Below is a modified file1.php: <?php // absolute path // inclusion status: SUCCESS require_once '/file2.php'; // absolute path // inclusion status: SUCCESS require_once '/../anotherfolder2/file3.php'; ?> It seems that PHP recognizes a non-prefixed file name as an absolute path in a require_once, and that it computes this absolute path from a relative context. I am not sure this is the expected behaviour, but it was quite hard to figure out. Also, if you want to recognize those special cases where you had to specify a relative path starting with a "/", you can use the following trick. <?php // it goes down one level, and then goes up one level : the result is neutral, but after prefixing your paths with this, PHP handles them define ('REQUIRE_TRICK', '/TRICK/../'); require_once REQUIRE_TRICK . 'file2.php'; require_once REQUIRE_TRICK . '../anotherfolder2/file3.php'; ?> If this ever gets reworked/fixed, it will be easy to remove the define. ---- Server IP: 72.52.91.14 Probable Submitter: 88.185.253.207 ---- Manual Page -- http://php.net/manual/en/function.require-once.php Edit -- https://master.php.net/note/edit/115287 Del: integrated -- https://master.php.net/note/delete/115287/integrated Del: useless -- https://master.php.net/note/delete/115287/useless Del: bad code -- https://master.php.net/note/delete/115287/bad+code Del: spam -- https://master.php.net/note/delete/115287/spam Del: non-english -- https://master.php.net/note/delete/115287/non-english Del: in docs -- https://master.php.net/note/delete/115287/in+docs Del: other reasons-- https://master.php.net/note/delete/115287 Reject -- https://master.php.net/note/reject/115287 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199778) next »