Steve
Steve

Reputation: 4908

Escaping <?php ?> in the JavaScript of a php file

I have a php file, index.php, that contains the jQuery/JavaScript code below. The code is defining a string that will be a new PHP file after it gets ajaxed up to the server. index.php loads fine until I put the PHP line in the first array member. Then when I load index.php I get:

SyntaxError: <html xmlns="http://www.w3.org/1999/xhtml"><head>

Since index.php is a PHP file that is running I know I have to escape the leading < in <?php or the PHP processor will jump in at the server. But apparently I need to do more than that. Does anyone see how I can structure this so that index.php loads and then this code passes <?php ?> up as a harmless string?

$(function() {

var seg1 = ["\<?php phpinfo(); ?>\n",
    "<!doctype html>\n ",
    "<!-- HTML5  -->\n",
    "<html>\n",
    "<head>\n",
    "<meta charset='utf-8' />\n",
    "<title>MyPlace</title>\n" ,
    "<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'><\/script>\n",
    "<script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js'><\/script>\n"
       ].join('');
}

Upvotes: 1

Views: 122

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173652

phpinfo() generates a HTML page by itself, so concatenating that with another document isn't exactly kosher.

That said, you could use output buffering first to capture the output of phpinfo() and then use json_encode() to properly escape it:

<?php

    ob_start();
    phpinfo();
    $info = ob_get_clean();

?>
$(function() {
    var seg1 = [<?php echo json_encode($info); ?>,
        "<!DOCTYPE html>\n" // etc etc
    ].join('');

Update

I misunderstood your question; it seems that you allow the upload and execution of arbitrary PHP code on your server. This is highly dangerous and my first advice would be to basically abandon that idea.

If you still feel like shooting your foot off, here's how:

var seg1 = ["<" + "?php phpinfo(); ?" + ">\n",
    "<!DOCTYPE html>\n" // etc etc
].join('');

Upvotes: 5

Related Questions