PHP - $_SERVER['QUERY_STRING'] has "&" - php

In my php script, I'm trying to get the query string ($_SERVER['QUERY_STRING']), append it to another url, and then make a redirect.
If I use the query string without any processing, the new url shows "& amp;" for all the "&'s." Therefore the new url won't work.
I print out the $_SERVER['QUERY_STRING'] and view the page source. It does use "& amp;" for all the "&'s." It doesn't make sense to me and I wonder why. Is it just my server's configuration or PHP's default?
UPDATE: I tested it on MODX CMS using snippet. If running on a regular PHP script, there is no such issue. I guess the problem is with MODX. Any idea?

Just an idea:
If you use TinyMCE to edit stuff, it changes all &'s to &'s - that has been driving me crazy for a lot of times. That happens in snippet calls and can be debugged if you either deactivate the rich text editor for a resource or "quick edit" a resource.
Also good practice: put snippet calls into a chunk. You can call that chunk without risking the syntax of the snippet call.

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.

How do I rewrite PHP code blocks before they are passed to the interpreter?

What I am trying to do is write a parser for PHP that interprets whitespace instead of brackets. I can do rewriting bit and output PHP, but what I'm not sure is how best to integrate this into an application.
In an ideal world, I imagine the best thing would be to put an include at the top of the file, which in turn rewrote all the code blocks that follow it into proper PHP syntax as they are passed to the interpreter, but I am not aware that blocks of code can be passed in this way.
Another alternative is to write it as a server extension, but I would prefer not to do this, as it makes it less accessible.
Is there an easy way to architect this?
There is a way to do this with Stream Wrappers.
With that you can basically read and re-write any code that is read by PHP before it is actually interpretted. with fopen(), fwrite(), include, require, file_get_contents() etc.
So in your case you could listen for any file that is require(_once) or include(_once) and do with the code you like. You will get the entire code in a variable and with that you can simply do all sorts of replacements in strings with regex and what not.
The only downside is, is that your index.php can't make use of this method since it is not catched by any include or require. But any other code file that is included from there can be catched by the stream wrapper.
Here is an article about a plugin system that uses that method. Maybe it can be of any help.
http://phpmyweb.net/2012/04/26/write-an-awesome-plugin-system-in-php/
In there you'll also find a link to a guthub page with the source of the plugin code. In there you can basically see how to setup your Stream Wrapper class. From there on you can make up your own code as you do not have to intercept any method calls etc. like the plugin is doing.
I don't think your include idea would work as described. Since the code would be missing braces, it probably would not make it through the normal PHP parser without throwing a 500 error. So the file you want to include could never do its work.
The opposite approach might work. Write a parser script and have it read and execute your "whitespace" PHP files.
URLs might look like this: mydomain.com/my-parsing-script.php?file=script/to/parse.php
Then you'd edit .htaccess to rewrite all your URLs to make that stuff invisible to the user.
The parsing script would simply open the "whitespace" file and do some regex magic before passing the script to eval();

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.

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:
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

Why is javascript not able to use a javascript variable I declared in a php file?

Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug

Categories