I'll be brief and hope I can explain my scenario correctly. Here's my scenario. The jQuery slider plugin has an anonymous callback method. I would like to give the Admin the ability to create a function for that callback method. So from the plugin's add/edit pages the admin has a textarea to input the jQuery code. Now the textarea input gets save to the database and when it's passed using the wp_localize_script() it gets pass as a string that does not get recognize as a Javascript/jQuery code. So far, I have only being able to make it work using eval() in order for it to be recognize and to run as a Javascript/jQuery function.

On the Admin page:

<textarea id="callback" name="callback" rows="10" ><?php echo $callback; ?></textarea>

On the wp_localize_script() array:

wp_localize_script( 'init_file', 'slider_option', $config_array );

$config_array = array(
    ...
    'onSliderEnd' => $callback,
    ...
);

On the initialize jQuery file:

$('body').slider({
    ...
    'onSliderEnd': function(){ eval( slider_option.onSliderEnd; ); },
    ...
});

Is this a safe way to use eval()? Any other suggestions? Or should I just not allow such an option?

Thanks in advance for all your replies.

up vote 1 down vote accepted

Not allow.

Your user is not a software developer, pretending that he is can only end bad. This is even before speaking about security etc.

If you think that there are callbacks that make sense, just provide them yourself.

Never let anyone add any jQuery scripts via any text editor. How are you going to know if the script is malicious or not, how are you going to handle jQuery errors, how are you going to know if the jQuery is even proper and allowed jQuery.

eval() brings an added extra security risk and should be avoided where user submitted strings are to be evaluated. Always sanitize, validate and escape user submitted values properly and appropriately.

  • I've avoided eval() for those reasons, but I've recently read a few articles that gave another side of using eval, which is why I wasn't sure if to go ahead and try it given what I was trying to accomplish in this scenario. Is there any save way/environment to use it? – john Apr 20 '16 at 22:13

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.