Monday, February 7, 2011

Call PHP Function based on URI

Hello all.

I am looking to create a simple php script that based on the URI, it will call a certain function.

Instead of having a bunch of if statements, I would like to be able to visit:

/dev/view/posts/

and it would call a 'posts' function I have created in the PHP script.

Any help would be greatly appreciated.

Thanks!

  • Are you using a framework? they do this sort of thing for you.

    you need to use mod_rewrite in apache to do this.

    Basically you take /dev/view/posts and rewrite it to /dev/view.php?page=posts

     RewriteEngine On
     RewriteRule ^/dev/view/posts/(.*)$ /dev/view?page=$1
    

    in view.php

    switch($_REQUEST['page'])
    {
     case 'posts':
      // call posts
      echo posts();
      break;
    }
    

    EDIT made this call whatever function is called "page"

    You probably want to use a framework to do this because there are security implications. but very simply you can do this:

    if (array_key_exists('page',$_REQUEST))
    {
     $f = $_REQUEST['page'];
     if (is_callable($f))
     {
      call_user_func($f);
     }
    }
    

    Note there are MUCH better ways of doing this! You should be using a framework!!!

    Byron Whitlock : You need whats called a front controller that will map this for you. WHat framework are you using?
    Gumbo : You don’t need to escape the `/` characters.
    stereointeractive.com : sort of relevant, http://twitto.org/ is a great example of taking this to the next level, perhaps a little too far! rather than using a switch statement it checks to see if your controller file has a method matching the parameter value. not secure, but it makes a point.
  • What you are looking for is a form of URL rewriting on your web server. For instance, if you are using Apache you should lookup mod_rewrite. An example of what your rule might look like:

    RewriteEngine On
    RewriteRule ^/dev/view/posts/(.*)$ /posts.php?id=$1
    

    But I'm assuming that you are wanting to have a trailing post ID or similar so that you can use this for multiple posts URLs.

  • Take a look at the call_user_func function documentation.

    $functions['/dev/view/posts']    = 'function_a';
    $functions['/dev/view/comments'] = 'function_b';
    $functions['/dev/view/notes']    = 'function_c';
    
    $uri = '/dev/view/comments';
    
    call_user_func($functions[$uri]);
    

0 comments:

Post a Comment