tags:

views:

102

answers:

3

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!

+3  A: 

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
I know about using mod_rewrite, but the problem with that is I need to write code to match each 'posts' with a 'posts' function. Via the framework idea, you can write a function posts() and then just go to /dev/view/posts/ and it will call that function.
You need whats called a front controller that will map this for you. WHat framework are you using?
Byron Whitlock
You don’t need to escape the `/` characters.
Gumbo
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.
stereointeractive.com
A: 

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.

conceptDawg
+1  A: 

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]);
Sean Bright
This is what I was looking for. Thanks a lot!