0

i need a solution to check a string with PHP and determine if it is a javascript command.

i want to generate javascript scripts dynamically in runtime. but a string could be an invalid javascript command.

for example in :

 $str = 'hello';

hello is a simple string and not a javascript command but in:

 $str = 'str.split()';

str.split() is javascript commnad.

i want to know if a string is really a javascript command

Omid
  • 4,575
  • 9
  • 43
  • 74
  • 6
    Can you define "javascript command"? Are you looking for script tags, or javascript keywords, or checking to see if something is valid javascript, or something else? – Joe Enos Aug 15 '11 at 06:03
  • Just a tip: When asking a question on here, it is often useful to state *why* you are trying to do something. – porges Aug 15 '11 at 07:03
  • 1
    If you're generating it dynamically, why can't you just test it using a browser error console, or is it being generated from user input? – Bojangles Aug 15 '11 at 09:42
  • @JamWaffles: Yes it's being generated by user – Omid Aug 15 '11 at 10:16
  • @Omid Ah right. A curious case; can you give an example of why/where this user generated JS is used? – Bojangles Aug 15 '11 at 11:11

2 Answers2

3

I think you should try using a JavaScript linter written in PHP.

Sure the JavaScript will need to be valid but it could work.

Just check if the linter says it's okay and then you can consider it as JavaScript code.

Edit: Example taken and edited from the page I linked to.

$lint = new JSLEngine();

if ($lint->Lint($js))
{
    // This is valid JavaScript, now we can do stuff with it.
}
Olical
  • 39,703
  • 12
  • 54
  • 77
  • 1
    Thanks, I don't think the general concept is a good idea though. If he is generating scripts from users input then this could be one massive XSS target. Just sounds a tad dangerous to me. – Olical Aug 15 '11 at 09:46
  • Good, but i don't want to use external application due to performance – Omid Aug 15 '11 at 10:14
0

You could always create an array of every javascript function then use in_array($variable, $array) to check whether the specified variable is in that array, however this would mean writing every single javascript function manually.

The problem you will have is highlighted in the thread below:

How to display all methods of an object in Javascript?

I hope you get your problem resolved.

Just to extend on this - How to display all methods of an object in Javascript?

This post explains how ES5 will allow you to do this. However you will need to find a way of getting the javascript content into a php variable, eg <?php $blah = get_file_contents("thejavascriptpage.php");?> - thejavascriptpage.php containing the javascript, then explode the arrayed response.

Community
  • 1
  • 1
rickyduck
  • 4,030
  • 14
  • 58
  • 93