Mark W
Mark W

Reputation: 5964

How to write response to file using php

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.

Upvotes: 0

Views: 10306

Answers (3)

Travesty3
Travesty3

Reputation: 14469

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_contents to 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 include the getdoc script in the PHP script that is generating your HTML file, like this:

$_GET["name"] = "documentA";
echo "<a href=\"". include("getdoc.php") ."\"> Open Document A </a>";

Solution three

Or you could change the way the getdoc script works. You could use a script more like this:

header("Content-type:application/pdf");
header("Content-Disposition:attachment; filename=\"{$_GET["name"]}\"");
readfile($_GET["name"]);

And you keep your link like this: <a href="mylink.com/getdoc.php?name=documentA"> Open Document A </a>. When getdoc.php is 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.

Upvotes: 3

Your Common Sense
Your Common Sense

Reputation: 157839

How to write response to file using php

Noway.
PHP do not process HTTP requests.
You have to set up your web server to do the rewrite.
There are 100500 questions under mod_rewrite tag, you will find the solution easily.

Note that you may wish to rewrite your url to /getdoc.php?name=document2012-03-15.pdf, not one you mentioned in your question

Upvotes: 1

shanethehat
shanethehat

Reputation: 15570

<?php
    //get output from URL
    $myfile = file_get_contents('http://mylink.com/getdoc?name=documentA');
?>
<a href="<?php echo $myfile; ?>">Open Document A</a>

Upvotes: 1

Related Questions