Reputation: 5463
I've used the Codeigniter framework heavily to depend on my php web development. I love the fact that classes and models have the line
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
to prevent direct access to the file.
I want to do the same in my non codeigniter site (mainly classes), and was wondering if I could do the same thing? Is there a best practice to do this?
Thank you!
Upvotes: 1
Views: 1755
Reputation: 5084
Best practice is to move the files outside your public folder, so your files cannot be accessed at all. Only have the files that should be public in your public folder, like css, js files, and move your application one folder up.
So if your public folder is:
/home/pcken/pubic_html
move your folder with your application to
/home/pcken/
And use the index.php as a router to include files from that folder.
Otherwise the !defined("BASEPATH")
works fine.
Upvotes: 2
Reputation: 6016
Codeigniter sets the BASEPATH constant in the index.php file. So surely you just want to do the same in the index file of your non Codeigniter project and then add the follow line to any files you don't want direct script access too.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Upvotes: 2
Reputation: 22862
You could that with .htacces
I grabbed this code from the codeingiter forum, it will remove the index.php from urls and prevent direct access to your files, unless it's an image or css as you can see on the comments.
Credits goes to ElliotHaughin
Options -Indexes
Options +FollowSymLinks
RewriteEngine On
RewriteBase /(base domain goes here)/
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ index.php?/$1 [L]
#When your application folder isn't in the system folder
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
Upvotes: 2