skip to Main Content

I am developing an e-learning website and there is a course preview page for each course on the platform. the file structure of the platform is something like https://example.com/courses/[course_id...]/index.php and the PHP code gets the course id from the parent directory name to look it up in the database. The problem here is that I have to make the same copy of the index.php file in each course directory I make, so is there a way to modify the .htaccess file in a way that I can have only one copy of the index.php file?

2

Answers


  1. Let’s assume you have a file named course.php. This file pulls up a course based on ID at a URL like:
    http://localhost/course.php?id=1

    In your .htaccess

    RewriteEngine on
    RewriteRule ^courses/([0-9]+)$ course.php?id=$1
    

    Then you can go to http://localhost/courses/1 to get course ID 1.

    https://httpd.apache.org/docs/2.4/rewrite/intro.html

    Login or Signup to reply.
    1. Make index.php of root
    <?php
    #For security course must exist.
    # -1 will display 404
    $course  = isset($_GET['course']) ? $_GET['course'] : -1;
    $courses = [
        '1', '2', '3',
    ];
    if (!in_array($course, $courses)){
        header("HTTP/1.0 404 Not Found");
        echo '404';
        exit();
    }
    
    include_once("courses/".$course."/course.php");
    
    1. Make .htaccess of root
    RewriteEngine On
    # course/x to /index.php?course=x
    RewriteRule ^course/([0-9]+) /index.php?course=$1 [QSA,L]
    # protect folder courses
    RewriteRule ^courses/(.+)$ - [F,L]
    
    1. Your directory will look like this.
    root/
        index.php
        .htaccess
        /courses
                /1
                  /course.php
                /2
                  /course.php
    
    Goto http://app.local/course/1 to /courses/1/course.php
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search