PHP create_function, function without semicolon?
basically, what i want to know is, for the second parameter in the create_function function, is there anyway to pass a string without a semicolon? or will it not work.
example:
taken from php.net
create_function(开发者_运维知识库'$a,$b', 'return "CRCs: " . crc32($a) . " , ".crc32(b);'),
notice that there is a semicolon in the string. is there any possible way someone can enter a function without a semicolon that will still run/evaluate?
With create_function() you're creating an anonymous function. The second parameter is a string that is the code of the function (like any other function you'd write). It doesn't have to end in a semicolon, for example:
$coolfunction = create_function('$thing', 'if ($thing > 0) {return "Yes"; } else { return "no!"; }');
echo $coolfunction(1) . ' and ' . $coolfunction(-1);
Ends in a '}' and prints out: Yes and no!
No it is not possible. PHP is semicolon-sensitive, that you must use it to terminate every statements before right braces. I even tried regular function like this:
function f() {
return 1
}
and it spitted out a syntax error, unlike in JavaScript.
You should always sanitize any user input before using it. I suggest that you look for the semicolon in the user input, if it is missing, append it.
If the user can enter anything here you still have a problem if he enters an invalid function name or just rubbish.
You can validate with preg_match() (although I'm not an expert on preg so I will let someone else help you out there).
First, why do you need that ? That's a really dirty way to create a function. Hope because you want to make a interface where people can directly create a function (and this will be only for you or it'll be a big security issue). I don't really get how you want to use that.
Anyway, for you question, you don't have to care if it's working or not. I mean, just test if it's working, if not just put by yourself a semicolon. It's just a simply test on a string.
精彩评论