U
U
Uniq2016-10-27 23:14:08
PHP
Uniq, 2016-10-27 23:14:08

Router in php how to split a request?

Hello everyone, the point is
there is a site.com/news link - the router takes a controller named news.php and launches the content,
but how to make site.com/news/xxx so that the router processes xxx not for .php controllers, but as a request to the database?
the router itself:

class Route
{
    static function start()
    {
 
        $controller_name = 'Main';
        $action_name = 'index';
        $URIParts = explode('?',$_SERVER['REQUEST_URI']);
        $routes = explode('/',$URIParts[0]);
        //$routes = explode('/', $_SERVER['REQUEST_URI']);
 
        if ( !empty($routes[1]) )
        {	
            $controller_name = $routes[1];
        }

 
        if ( !empty($routes[2]) )
        {
            $action_name = $routes[2];
        }
 
        $model_name = 'Model_'.$controller_name;
        $controller_name = 'Controller_'.$controller_name;
        $action_name = 'action_'.$action_name;
        /*
    echo "Model: $model_name <br>";
    echo "Controller: $controller_name <br>";
    echo "Action: $action_name <br>";
    */
 
        $model_file = strtolower($model_name).'.php';
        $model_path = "application/models/".$model_file;
        if(file_exists($model_path))
        {
            include "application/models/".$model_file;
        }
 
        $controller_file = strtolower($controller_name).'.php';
        $controller_path = "application/controllers/".$controller_file;
        if(file_exists($controller_path))
        {
            include "application/controllers/".$controller_file;
        }
        else
        {
  
            Route::ErrorPage404();
        }

 
        $controller = new $controller_name;
        $action = $action_name;

        if(method_exists($controller, $action))
        {
 
            $controller->$action();
        }
        else
        {
           
            Route::ErrorPage404();
        }

    }
    function ErrorPage404()
  {$host = 'http://'.$_SERVER['HTTP_HOST'].'/';
        header('HTTP/1.1 404 Not Found');
    header('Location:'.$host.'404');
       
    }

}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
OnYourLips, 2016-10-27
@padonnak

See examples with the code of one of the popular routers: https://github.com/nikic/FastRoute

T
trevoga_su, 2016-10-28
@trevoga_su

www.phpinfo.su/articles/practice/chpu_na_php.html

R
Rsa97, 2016-12-25
@Rsa97

Do not use direct variable substitution in the query. Instead, use placeholders.

$stmt = mysqli_prepare($connect, "INSERT INTO *** (fio,email,age,anw1,anw2,frequency) VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssssss", $fio, $email, $age, $anw1, $anw2, $frequency);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question