wetler
wetler

Reputation: 383

Alternative for eval() -PHP

i am trying to implement URL mapping in PHP. I have a json file which stores the url and functions which is to execute when that link is requested. I was using eval() but then i came across this

Kepp the following Quote in mind:

If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP

now i am thinking is their any other(better) way to do it.

My json file looks like this.

{
    "bw/":"main()",
    "bw/login":"login()"

}

and my loadPage function look like this.

function loadPage($url){ //$url = 'bw/'
    $str = file_get_contents('urls.json');
    $this->link = json_decode($str, true);
    $url = ltrim($url,"/");
    $key = $this->link[$url];
    eval("$key;");
}

EDIT: i defined $this->link in my code

Upvotes: 1

Views: 258

Answers (2)

user3739727
user3739727

Reputation: 1

A little better way is changing eval() to:

if (function_exists($key)) { 
   return $key(); 
} 
return default();

and you might create a function "default" to show an error 404 or default page when function doesn't exists.

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

A slight tweak to your JSON to allow you to call the function dynamically would make it easier, just remove the brackets so it would look like...

{
    "bw/":"main",
    "bw/login":"login"

}

and then call it using...

function loadPage($url){ //$url = 'bw/'
    $url = ltrim($url,"/");
    $key = $this->link[$url];
    $key();
}

Upvotes: 1

Related Questions