tags:

views:

103

answers:

1

I'm passing the ABSPATH value from a wordpress theme options page to an external page which does not have access to ABSPATH. The problem is that once the value is received in the external file, the slashes are removed. How can I send the value and keep the slashes intact?

I'm passing the value for ABSPATH via a javascript window.open URL parameter like so...

<input type="button" id="templateUpload" value="Add New Template" onclick="window.open('../wp-content/themes/mytheme/myuploader.php?abspath=<?php echo ABSPATH ?>','popup','width=330,height=230,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no'); return false" />

The view source of the above executed wordpress theme options page reads...

?abspath=C:\xampplite\htdocs\wordpress/

Which is why I believe I'm having an issue

+2  A: 

It is the lack of JavaScript string literal escaping that has tripped you up: \x and \h are escapes in strings, so you'd need \\ to get a real backslash.

But that's not all.

<input ...  onclick="window.open('.../myuploader.php?abspath=<?php echo ABSPATH ?>',... />

Here you're outputting a value into:

  1. a URL parameter, inside
  2. a JavaScript string literal, inside
  3. an HTML attribute

That means you need three levels of escaping:

$uri= '../wp-content/themes/mytheme/myuploader.php?abspath='.urlencode(ABSPATH);
$jsuri= json_encode($uri);
$htmljsuri= htmlspecialchars($jsuri);

<input ... onclick="window.open(<?php echo $htmljsuri; ?>, 'popup', 'features...')" />

You can reduce that by using the HEX_ options in json_encode to ensure HTML special characters are already escaped out of the way, in PHP 5.3+:

$uri= '../wp-content/themes/mytheme/myuploader.php?abspath='.urlencode(ABSPATH);
$jsuri= json_encode($uri, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP);

<input ... onclick="window.open(<?php echo $jsuri; ?>, 'popup', 'features...')" />

However, anything involving multiple levels of escaping like this is confusing and generally to be avoided. Kick the JavaScript and the variable out of the markup instead, then you have only one level of escaping to worry about at once:

<input type="button" id="templateUpload" value="Add New Template" />
<script type="text/javascript">
    var ABSPATH= <?php echo json_encode(ABSPATH, JSON_HEX_TAG|JSON_HEX_AMP); ?>;

    document.getElementById('templateUpload').onclick= function() {
        var uri= '../wp-content/themes/mytheme/myuploader.php?abspath='+encodeURIComponent(ABSPATH);
        window.open(uri, 'popup', 'width=330, height=230');
    };
</script>

I omitted the return false as it isn't needed for a button, which has no default action to prevent. I also removed the stuff about removing browser chrome just due to finding it quite distasteful. ;-)

bobince
Wow Bobince, thanks for the work you put into the response. I really appreciate it!
Scott B