skip to Main Content

I have a MySQL table containing filenames and a query dependent on some user choice returning these filenames in a PHP script, say in a variable $filename. I want to create anchor tags with the href attribute pointing to these filenames so that the user can download the relevant PDF files stored in directory.
I tried to code like this:

echo "<a href='".$filename."' target='_blank'> my pdf file</a>";

but if the filename contains an apostrophe (‘) the link appears broken in the browser.
I have also tried escaping the apostrophe in the filename with backslash with no luck.
Additionally I tried delimiting the string containing the anchor tag inside single quotes, but this doesn’t allow inline code like $filename.
Then I saw this SO question Cannot pass variable with apostrophe in "a href" link, but it doesn’t seem to work.
Would constructing the href attribute in client-side javascript be of any help?

2

Answers


  1. What if you invert the quotes and apostrophes like this:

    echo '<a href="'.$filename.'" target="_blank"> my pdf file</a>';
    
    Login or Signup to reply.
  2. Maybe like this:

    echo '<a href="' . $filename . '" target="_blank">my pdf file</a>';
    

    Or:

    echo "<a href='$filename' target='_blank'>my pdf file</a>";
    

    Or with urlencode (the most reliable):

    echo '<a href="' . urlencode( $filename ) . '" target="_blank">my pdf file</a>';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search