I wish to write the response of hitting a given url into the href attribute of an anchor tag using PHP. How can I do this?
Here’s an example of what I excpect to happen
mylink.com/getdoc?name=documentA
returns a string as a response:
mylink.com/document2012-03-15.pdf
I need to write this response (using PHP into the href attribute as shown below:
<a href="mylink.com/document2012-03-15.pdf"> Open Document A </a>
(so the above will be the final source of my page.
I think there are a few ways to do what you want. Not all of them will work exactly as you ask for, but the end result should be the same.
Solution one
My first possible solution was already posted by @shanethehat. You could use
file_get_contentsto call your PHP script via HTTP and get the response.Solution two
Another possible solution was suggested in the comments of the post by @YourCommonSense. You could simply
includethegetdocscript in the PHP script that is generating your HTML file, like this:Solution three
Or you could change the way the
getdocscript works. You could use a script more like this:And you keep your link like this:
<a href="mylink.com/getdoc.php?name=documentA"> Open Document A </a>. Whengetdoc.phpis called, it will get the specified file and start a file download.NOTE: you should probably do some input sanitization with this method (removing slashes, making sure the file ends in .pdf, etc) to make sure someone doesn’t try to get a file they’re not allowed to get.
That’s all I’m coming up with at the moment. There might be a more clever way to do it, but hopefully one of these solutions will do it for you. I would try solution 2 or 3 first, and if they don’t work out for you, then go with solution 1.