skip to Main Content

I have built a site with codeigniter 3.

I want to prevent run all php files directly. imagine that I have a file named test.php in my root.

When the user goes to a site.com/test.php , it is not possible to access it. Not for a specific file but for all PHP files.

I want to access the site only by calling the controls and their methods like : site.com/user/login

2

Answers


  1. You have to add this code in your .htaccess

        <IfModule mod_rewrite.c>
          RewriteEngine On
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_FILENAME}.php -f
          RewriteRule ^(.*)$ $1.php [NC,L]
        </IfModule>
    
    Login or Signup to reply.
  2. The sure-fire way – which is also the approach most modern php frameworks use – is to actually have a document root that does not contain php files you don’t want exposed.

    This can also be done in codeigniter with a little trick:

    1. First make a public/ directory in your project. This will be the document root, everything in there will be public.
    2. Create a simple index.php file there with just "hello world" for testing
    3. Change your server’s config to have that directory as the document root. For example, if the typical/current document root is /var/www/html, in your case, it should now be /var/www/html/public.
    4. Ensure it works: when you visit the site, the "hello world" should show up. You also should not be able to access any other php files.
    5. (optional) At this point you can also implement url rewriting (similar to what Dev Kraken mentioned before). Then when you access non-existing urls, you should also/always get "hello world".
    6. Finally, replace the content of the index.php that we created to so:
    <?php
    
    // this makes codeigniter believe that it is running from the project root, not public directory
    chdir(dirname(__DIR__));
    
    // ..and this loads codeigniter
    require_once(__DIR__ . '/../index.php');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search