user623990
user623990

Reputation:

Easy and efficient way of breaking up html code into several files and using php's include()

Currently, for things like a header, footer or common sidebar object, I create a custom .php file and do something along these lines:

echo '
    <some><html><here>
';

and then include it on the pages that I want it to appear:

include('path/to/file');

The only problem with this is that someone can point their browser to my .php file and view part of html on its own. It isn't a huge deal, but it seems unprofessional and a little careless. Is there a better way of doing this?

Upvotes: 5

Views: 1354

Answers (4)

deviousdodo
deviousdodo

Reputation: 9172

The simplest way is to move all those files outside the DocumentRoot / public directory and include them from there. Something like:

include '../pages/header.php';
// rest of the script
include '../pages/bottom.php';

Anyway that's the purpose of that directory - to only hold things that are meant to be accessed directly.

Of course, the first step after this would be to look into having only one index.php file which filters all the requests (permissions, filtering, rewrites, etc) and includes whatever is necessary based on the request (this is called a Front Controller and there are also a few lightweight frameworks which already implement it). Here's a starting point: https://github.com/adrian-gheorghe/basic-website/blob/master/public/index.php

Upvotes: 1

Kevin Ji
Kevin Ji

Reputation: 10499

WordPress pretty much does what you are currently doing: it stores all of the theme files in /wp-content/themes/THEMENAMEHERE/, and you can access the files to there directly. It's not that big of a concern, as users can't exactly do anything harmful, but if you care, you can store your files in a separate directory (as other answers have mentioned), or configure httpd.conf or .htaccess to block access to the particular scripts.

Upvotes: 0

FarK
FarK

Reputation: 636

You must restrain the access to other files in the server configuration.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692291

Put the included php files in a separate directory, and make this directory inaccessible from the outside (using .htaccess with Apache, for example).

Upvotes: 1

Related Questions