Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to include another php file?

Tags:

php

I have a php file, and I want to include another php file that have css link tags and javascript source tags, but when I try to include them, it doesn't get added to the page.

my php page:

<?php 
    $root = $_SERVER['SERVER_NAME'] . '/mysite'; 
    $theme = $root . '/includes/php/common.php';
    echo $theme;
    include($theme);
?>

common.php:

<link rel='stylesheet' type='text/css' href='../css/main.css'/>";

Anyone know whats wrong? Thanks

like image 881
omega Avatar asked Feb 05 '13 03:02

omega


2 Answers

PHP's include is server-side, so you need to use the server side path. It is better to use dirname(__FILE__) instead of $_SERVER['SSCRIPT_NAME'], but $_SERVER['SERVER_NAME'] is absolutely wrong.

Try:

include dirname(__FILE__)."/common.php";

Or if the file you want to include is not on the same directory, change the path. For example for a parent directory, use dirname(__FILE__)."/../common.php".


Note that some might suggest using include "./common.php" or similar. This could work, but will most likely fail when the script invoking include is actually being included by another script in another directory. Using dirname(__FILE__)."/common.php" will eliminate this problem.

like image 54
Alvin Wong Avatar answered Sep 22 '22 12:09

Alvin Wong


Change your code to this:

<?php  
    $theme = 'includes/php/common.php';
    echo $theme;
    include($theme);
?>

If your includes folder is in the same folder as your php page then it should work, if not add you domain name instead. SERVER_NAME is not needed in this instance.

like image 25
C1D Avatar answered Sep 20 '22 12:09

C1D