DevWL
DevWL

Reputation: 18840

Silex - Redirecting to home page if url not found

I am new to Silex. I want to redirect user to home page if the given route is not found in Silex app. I have done it dirty way placeing at the bootom of my front controler (index.php) those lines of code:

...
/*
* if no route found in controlers above - get curen route
*/
// input "XL-FOLDER-LEARNINGOWY/SILEX/test1/web/index.php" output ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web','index.php']
$file_with_path = explode('/', $_SERVER['PHP_SELF']);
//input ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web,'index.php'] output ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web']
array_pop($file_with_path); 
// input ['XL-FOLDER-LEARNINGOWY','SILEX','test1','web'] output "XL-FOLDER-LEARNINGOWY/SILEX/test1/web"
$path = implode('/', $file_with_path); 
//input "XL-FOLDER-LEARNINGOWY/SILEX/test1/web/asdasd/asdasdasd/asdasd" output "asdasd/asdasdasd/asdasd"
$route = str_replace($path, '', $_SERVER['REQUEST_URI']); 

/*
* redirect to default view - if non route found
*/
$app->get($route, function () use($app) {

    return $app['twig']->render('index.twig');

})
->bind('home');

// RUN SILEX APP
$app->run();

Is there is a better way to get curent route that is in the url after base path without all this conversions?.

Upvotes: 1

Views: 3113

Answers (2)

DevWL
DevWL

Reputation: 18840

I have tweaked your answer a bit so it does what I need. Now the script can redirect to different paths based on the root/main path that the user tries to access.

   $app->error(function(\Exception $e, $code) use ($app) {
        if (404 === $code) {
            $path = $app['request']->getPathInfo();
            $path = explode('/',$path);
            echo $path[1];
            if($path[1] == 'php'){
                return $app->redirect($app['url_generator']->generate('php'));
            }

            if($path[1] == 'css'){
                return $app->redirect($app['url_generator']->generate('css'));
            }

            //...

            return $app->redirect($app['url_generator']->generate('home'));
        }
        // Do something else (handle error 500 etc.)
    });


    // RUN
    $app->run();

For example if they try to access:

www.website.pl/php/hjasdaskldjalsd [404]

this will get redirected to

www.website.pl/php [200]

and

www.website.pl/css/ghjghdfgdfg [404]

this will get redirected to

www.website.pl/css [200]

and if he enter something like

www.website.pl/hjkhsd [404]

he will get redirected to home page

www.website.pl [200]

Upvotes: 0

BlueM
BlueM

Reputation: 3851

The easiest way to accomplish this is to simply return a redirect from the error route:

$app->error(function (\Exception $e, $code) use ($app) {
    if (404 === $code) {
        return $app->redirect($app['url_generator']->generate('home'));
    }
    // Do something else (handle error 500 etc.)
});

Upvotes: 6

Related Questions