Search code examples
phpjavascriptbackslashslash

Backslash Disappears from Filename


This is my code:

<script>
document.getElementById(div').innerHTML = '<a href="javascript:void(0);" onclick="openPhpFile (\'asdasD\\Asdeqw.txt\');">efff</a>';
</script>

When the openPhpFile function runs, I alert the filename, and the \ characters are gone, even though they are doubled. addslashes() doesn't help; what can it be?


Solution

  • You should do this instead:

    <script type='text/javascript'>
      (function () { // Closures are your friend
        // Declare variables
        var theDiv, theLink;
        // Create the link and assign attributes
        theLink = document.createElement('a');
        theLink.innerHTML = 'efff';
        theLink.href = '#';
        theLink.onclick = function () {
          openPhpFile('asdasD\\Asdeqw.txt');
        };
        // Get a reference to the container, empty the container and add the link
        theDiv = document.getElementById('div');
        theDiv.innerHTML = '';
        theDiv.appendChild(theLink);
      })();
    </script>
    

    Remember that if you are echoing the from PHP inside double quotes, you will actually need 4 backslashes. This is because PHP will also use the double backslash sequence, and would only output one. So if you want PHP to echo 2 backslashes, you need to put 4 in.