0

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?

Nick_h
  • 21
  • 4
  • 1
    "but it doesn't seem to work" post what you tried, because it should work. – Sammitch Apr 02 '23 at 20:23
  • @Sammitch Ok I dit it! I hijacked the sql query return thing and hardcoded the result in variable $url as follows: $url="uploads/94/04/".urlencode("52909-05_You_Don't _Know_JS_Async_&_Performance.pdf"); and then echo "
    my pdf file"; the link almost works but fails. Now I see that the suspicious filename contains a blank after "You_Don't " (not evident is this comment) which ruins the whole thing. In the browser it shows a '+' representing this blank. But is if I use rawurlencode then it works
    – Nick_h Apr 02 '23 at 20:46

2 Answers2

0

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>';
imhvost
  • 4,750
  • 2
  • 8
  • 10
-1

What if you invert the quotes and apostrophes like this:

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