Paranoid
Paranoid

Reputation: 1923

PHP include contents of another directory

For example,

My website is mywebsite.com. Public_html is the main directory and inside public_html there is a folder sub_dir and a file index.php. sub_dir has the following files:

index.php , profile.php , contact.php

Now I want public_html directory to act like sub_dir directory. Like if I visit public_html/index.php it will show the contents of public_html/sub_dir/index.php without being redirected there. If I visit public_html/profile.php it will show the contents of public_html/sub_dir/profile.php.

How do I do this?

Upvotes: 0

Views: 48

Answers (2)

Tom Green
Tom Green

Reputation: 373

Edit:

I have just seen your comment about doing it only via PHP, because you can't change document_root While I still think using .htaccess would be a better solution, you could certainly do this only using PHP, here's a quick mock-up:

// Grab the URL parts
$url = parse_url("http://stackoverflow.com/posts/20420420");

// Redirect the user to the same path in `sub_dir`
header('Location: '. $url['scheme'] .'://'. $url['host'] .'/'. 'sub_dir'. $url['path']);

This would redirect the user to http://stackoverflow.com/sub_dir/posts/20420420.

Other people have suggested using include(), you could combine this with my parse_url() example above to dynamically call include() to load the file from sub_dir.


I see a few ways of doing this...

You could use PHP's header() function, but this wouldn't really be ideal.

You could also use .htaccess, something like:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^sub_dir
    RewriteRule ^(.*)$ sub_dir/$1 [L]
</IfModule>

If you placed this in public_html requests would be passed to sub_dir. So if you requested example.com/test.php you would actually be loading example.com/sub_dir/test.php.

What's your hosting setup like? Depending on your environment you can also change your webservers document_root...

Upvotes: 1

Richat CHHAYVANDY
Richat CHHAYVANDY

Reputation: 597

There are some ways to do this.

  1. Use include()

In file public_html/index.php

<?php include_once 'sub_dir/index.php';?>
  1. Use file_get_content()

In file public_html/index.php

<?php echo file_get_content('sub_dir/index.php');// Show as text?>

Upvotes: 0

Related Questions