How to write response to file using php - 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:
Open Document 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_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 " Open Document 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: Open Document 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.

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

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

Related

file_get_contents not working when parameters included in a relative url

I am trying to create a simple web service that will give a result depending on parameters passed.
I would like to use file_get_contents but am having difficulties getting it to work. I have researched many of the other questions relating to the file_get_contents issues but none have been exactly the situation I seem to having.
I have a webpage:
example.com/xdirectory/index.php
I am attempting to get the value of the output of that page using:
file_get_contents(urlencode('https://www.example.com/xdirectory/index.php'));*
That does not work due to some issue with the https. Since the requesting page and the target are both on the same server I try again with a relative path:
file_get_contents(urlencode('../xdirectory/index.php'));
That does work and retrieves the html output of the page as expected.
Now if I try:
file_get_contents(urlencode('../xdirectory/index.php?id=100'));
The html output is (should be): Hello World.
The result retrieved by the command is blank. I check the error log and have an error:
[Fri Dec 04 12:22:54 2015] [error] [client 10.50.0.12] PHP Warning: file_get_contents(../xdirectory/index.php?id=100): failed to open stream: No such file or directory in /var/www/html/inventory/index.php on line 40, referer: https://www.example.com/inventory/index.php
The php.ini has these set:
allow_url_fopen, On local and On master
allow_url_include, On local and On master
Since I can get the content properly using only the url and NOT when using it with parameters I'm guessing that there is an issue with parameters and file_get_contents. I cannot find any notice against using parameters in the documentation so am at a loss and asking for your help.
Additional Notes:
I have tried this using urlencode and not using urlencode. Also, I am not trying to retrieve a file but dynamically created html output depending on parameters passed (just as much of the html output at index.php is dynamically created).
** There are several folks giving me all kind of good suggestions and it has been suggested that I must use the full blown absolute path. I just completed an experiment using file_get_contents to get http://www.duckduckgo.com, that worked, and then with a urlencoded parameter (http://www.duckduckgo.com/?q=php+is+cool)... that worked too.
It was when I tried the secure side of things, https://www.duckduckgo.com that it failed, and, with the same error message in the log as I have been receiving with my other queries.
So, now I have a refined question and I may need to update the question title to reflect it.
Does anyone know how to get a parameterized relative url to work with file_get_contents? (i.e. 'file_get_contents(urlencode('../xdirectory/index.php?id=' . urlencode('100'))); )
Unless you provide a full-blown absolute protocol://host/path-type url to file_get_contents, it WILL assume you're dealing with a local filesystem path.
That means your urlencode() version is wrongly doing
file_get_contents('..%2Fxdirectory%2Findex.php');
and you are HIGHLY unlikely to have a hidden file named ..%2Fetc....
call url with domain, try this
file_get_contents('https://www.example.com/inventory/index.php?id=100');
From reading your comments and additional notes, I think you don't want file_get_contents but you want include.
see How to execute and get content of a .php file in a variable?
Several of these answers give you useful pointers on what it looks like you're trying to achieve.
file_get_contents will return the contents of a file rather than the output of a file, unless it's a URL, but as you seem to have other issues with passing the URI absolutely....
So; you can construct something like:
$_GET['id'] = 100;
//this will pass the variable into the index.php file to use as if it was
// a GET value passed in the URI.
$output = include $_SERVER['DOCUMENT_ROOT']."/file/address/index.php";
unset($_GET['id']);
//$output holds the HTML code as a string,
The above feels hacky trying to incorporate $_GET values into the index.php page, but if you can edit the index.php page you can use plain PHP passed values and also get the output returned with a specific return $output; statement at the end of the included file.
It has been two years since I used PHP so I am just speculating about what I might try in your situation.
Instead of trying fetching the parsed file contents with arguments as a query string, I might try to set the variables directly within the php script and then include it (that is if the framework you use allows this).
To achive this I would use pattern:
ob_start -> set the variable, include the file that uses the variable -> ob_get_contents -> ob_end_clean
It is like opening your terminal and running the php file with arguments.
Anyway, I would not be surprised if there are better ways to achieve the same results. Happy hacking :o)
EDIT:
I like to emphasize that I am just speculating. I don't know if there are any security issues with this approach. You could of course ask and see if anyone knows here on stackoverflow.
EDIT2:
Hmm, scrap what I said last. I would check if you can use argv instead.
'argv' Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. http://php.net/manual/en/reserved.variables.server.php
Then you just call your php script locally but without the query mark indicator "?". This way you can use the php interpreter without the server.
This is likely to be the most general solution because you can also use argv for get requests if I am understanding the manual correctly.

jQuery load php file as text?

Is it possible to load a php file as text with jquery?
$('#loader').load('somefile.php', function(e){
console.log(e);
});
This always interprets/execute the php file but I'm looking for a way to only load it as text, without to resort to renaming my php file as .txt
Is it possible?
Cheers
It is not possible without making any server side modification. The web server will always interpret the php file and return the output. However does not matter what solution you find it'll be very dangereous since you'll be dumping content of your php file to public.
Possible solutions with server side modifications:
Create a PHP file that dumps the content of a file, which name is specified by a url argument
Rename the file (I know the op does not want this, just included since it's an option)
As #nicholas-young suggested, get rid of the PHP tags.
I'm not sure why you need this type of need but I want to emphasize that this might not be a good idea in most of the cases since you'll be make a working PHP file available to public. If you can explain more why you need this we might offer better solutions.
Update:
Create a dumper.php that requires authorization and call this file from the javascript side with passing the filename that you want to be dumped as a parameter (dumper.php?file=index.php)
echo file_get_contents($_GET['file']);
It is of course not possibile.
.load will make an HTTP request to yourwebsite.com/somefile.php hence you will obtain the result of your script not the PHP code inside it.
If you really need the raw code inside your javascript as a string you should output it from the php itself:
<script>
var yourCode = <?=json_encode(file_get_contents('somefile.php')) ?>;
</script>
NO! Would be a major security problem if possible. The header will not matter. If making request towards php file, it will execute prior to delivery.
Use some parameter to print out contents from file instead. But do it in the file itself.

Get all content from a file, including PHP code

I'm making a small CMS for practice. I am using CKEDITOR and is trying to make it avaliable to write something like %contactform% in the text, and then my PHP function will replace it with a contactform.
I've accomplished to replace the text with a form. But now I need the PHP code for the form to send a mail. I'm using file_get_contents(); but it's stripping the php-code.
I've used include(); to get the php-code from another file then and that works for now. I would like to do it with one file tho.
So - can I get all content from a file INCLUDING the php-code?
*UPDATE *
I'll try to explain in another way.
I can create a page in my CMS where I can write a header and some content. In the content I am able to write %contactform%.
When I get the content from the database I am replacing %contactform% with the content from /inserts/contactform.php, using file_get_contents(); where I have the form in HTML and my php code:
if(isset($_POST['submit'])) {
echo 'Now my form is submitted!';
}
<form method="post">
<input type="text" name="email">
<input type="submit" name="submit">
</form>
Now I was expecting to retrieve the form AND the php code active. But If I press my submit button in the form it's not firing the php code.
I do not wan't to show the php code I want to be able to use it.
I still have to guess, but from your update, I think you ultimatly end up with a variable, which contains the content from the database with %contactform% replaced by file_get_contents('/inserts/contactform.php').
Something like:
$contentToOutput = str_replace(
'%contactform%',
file_get_contents('/inserts/contactform.php'),
$contentFromDatabase
);
If you echo out that variable, it will just send it's content as is. No php will get executed.
Though it's risky in many cases, if you know what you're doing you can use eval to parse the php code. With mixed code like this, you maybe want to do it like the following.
ob_start();
eval('; ?>' . $contentToOutput);
$parsedContent = ob_get_clean();
$parsedContent should now contain the results after executing the code. You can now send it to the user or handle it whatever way you want to.
Of course you'll have to make sure that whatever is in $contentToOutput is valid php code (or a valid mixture of php with php-tags and text).
Here is a link to the symfony Templating/PhpEngine class. Have a look at the evaluate method to see the above example in real code.
yes...
$content = file_get_contents( 'path to your file' );
for printing try
echo htmlspecialchars( $content );
From reading the revised question, I think the answer is "You can't get there from here." Let me try to explain what I think you will encounter.
First, consider the nature of HTTP and the client/server model. Clients make requests and servers make responses. Each request is atomic, complete and stateless, and each response is complete and usually instantaneous. And that is the end of it. The server disconnects and goes back to "sleep" until the client makes a new request.
Let's say I make a request for a web page. A PHP script runs and it prepares a response document (HTML, probably) and the server sends the document to my browser. If the document contains an HTML form, I can submit the form to the URL of the action= script. But when I submit the form, I am making a new request that goes back to the server.
As I understand your design, the plan is to put both the HTML form and the PHP action script into the textarea of the CKeditor at the location of the %contactform% string. This would be presented to the client who would submit the form back to your server, where it would run the PHP script. I just don't think that will work, and if you find a way to make it work, you're basically saying, "I will accept external input and run it in PHP." That would represent an unacceptable security exposure for me.
If you can step back from the technical details and just tell us in plain language what you're trying to achieve, we may be able to offer a suggestion about the design pattern.

using file get contents on a url that requires post data

i need to do a "file_get_contents" on a URL and there has to be data posted to the url before the contents are retrieved. is this possible? maybe something like
$contents = file_get_contents($_POST"http://www.example.com/");
so that i can then work with the $contents variable?
You cannot*** POST data using file_get_contents, you must use something like cURL
* I mark this because it is actually possible taking advantage of the third parameter which uses http context(see example one). However it really isn't worth your trouble if you have something like cURL.
Ah, I have tried to do this. Simply put you can't unless you install new extra software on your sever and go through A LOT of hassel and server load.
Best bet is to use GET if at all possible!
:)

Problem with AJAX and PHP

I have a small problem, I want to load data from a PHP file and put them on a DIV.
Here's the Jquery code
// Store the username in a variable
var jq_username = $("#txt_checkuser").val();
// Prepare the link variable
var link = 'user.php?action=check&username=' + jq_username;
$('div #checkuser_hint').load(link);
So it works! but instead of loading the result (compiled PHP) it loads the PHP code.
If I write the long URL "http://localhost/project..." it doesn't load anything!
Any idea how to do that?
I think you might be accessing your javascript file as a file on your local filesystem, a request to the same directory would go through the filesystem and not through your webserver, processing the PHP into the desired output. This also explains why http://localhost/project for the AJAX call doesn't work: Javascript might be enforcing the same-origin policy on you.
Verify that you're actually accessing this javascript file through http://localhost/ (as opposed to something like file://C:/My PHP Files/ ).
Does the page return anything when you use your browser?
Are you sure it should not be 'div#checkuser_hint' instead of 'div #checkuser_hint' ?
And this looks like the correct way according to the documentation.
var link = 'user.php';
$('div#checkuser_hint').load(link, {'action':'check', 'username':jq_username});
Are you able to access the script manually on your own? (try accessing it via your browser: htp://localhost/...) It may be the case that you're missing your opening <?php and/or closing ?> in the script-file itself.

Categories