9 กุมภาพันธ์ 2555

The First Solution: Use Relative File Paths

A web server will automatically assume that the code below belongs on the server, and thus, is not a remote file:
PHP Include File With Relative Paths

include (header.php); //This file is in the same directory as the PHP file

include (includes/header.php); //This file is in a directory under the PHP file

include (../header.php); //This file is in the directory above the current PHP file

?>
Relative file paths can be used in every legitimate situation an absolute path would be used, although it may take a little more work. As in the example above, you may have to work at determining where the file you wish to include exists in relation to the PHP file being run.
Not your idea of fun? We aren’t fond of it either, so on to the next solution!

The Second Solution: Use Another PHP Function

We may substitute the include statement with file_get_contents, which reads an entire file into a string.
PHP Include With File_Get_Contents

= file_get_contents("http://www.YourDomain.com/includes/header.php");

echo $includeFile;
?>


This is a good alternative to keep the absolute path an option in including a certain file. There are some instances where the above code wouldn’t come out as planned, depending on the situation. In addition, it adds another line of code that we can relinquish with the best solution: using a server variable.

The Best Solution: Using Server Variables

If you don’t want to spend hours rearranging code, you can do it the easy way with $_SERVER['DOCUMENT_ROOT'].
PHP Include Server Variables

include $_SERVER['DOCUMENT_ROOT'] . '/includes/header.php'; 

?>


This allows you to keep the absolute path that you’ve come to be familiar with in using the include statement. Technically, the $_SERVER['DOCUMENT_ROOT'] command gives your path to the public_html directory, as seen below:

  • /home/Your_Username/public_html

  • Essentially this is the root of your website, www.YourDomain.com, and therefore, you can use it just as you would with any other include statement. Just replace www.YourDomain.com with the server variable and you’re set!

    ไม่มีความคิดเห็น: