PHP include from URL that redirects
I've inherited a bad sitation where at our network we have many (read: many) hosted sites doing this:
include "http://www.example.com/news.php";
Yes, I know that this is bad, insecure, etc, and that it should be echo file_get_contents(...);
or something like that (the output of "news.php" is just HTML), but unfortunately this is what they use now and we can't easily change that.
It used to work fine, until yesterday.开发者_开发技巧 We started to 301-redirect all www.example.com requests to just example.com. PHP does not appear to follow this redirect when people include the version with www, so this redirect breaks a lot of sites.
To sum it up: Is there a way to get PHP to follow those redirects? I can only make modification on the example.com side or through server-wide configuration.
You said, in a comment: "I can go and change all the includes, but it'd just be a lot of work".
Yes. That's the "bad, insecure, but-I-don't-have-a-reason-to-change-it code" coming back to bite you. It will be a lot of work; but now there is a compelling reason to change it. Sometimes, cleaning up an old mess is the simplest way out of it, although not the easiest.
Edit: I didn't mean "it's your code and your fault" - rather, "bad code is often a lot of work to fix, but it's usually less work than to keep piling hacks around it for eternity, just to keep it kinda-working".
As for "going and changing it", I'd recommend using cURL - it works much better than PHP's HTTP fopen wrappers.
Can't you use curl? In curl_setopt it has an option to follow redirects.
Let's start with the redirecting http repsonse.
<?php
error_reporting(E_ALL);
var_dump( get_headers('http://www.example.com/news.php') );
// include 'http://www.example.com/news.php'
The output should contain HTTP/1.0 301 Moved Permanently
as the first entry and Location: http://example.com/news.php
somewhere.
I don't think any of those solutions provided by PHP itself would help... I just don't think any of them follow headers and what not. For what it's worth, I do think, though, that this behaviour is correct: you're asking for the result of a certain request and you got it. The fact that the result is telling you to look elsewhere is, in and of itself, a valid result.
If I were you, I'd look at cURL. There's a PHP extension for it and it will allow you to tell it to follow headers and get to where you're trying to get. If this is not usable (as in, you absolutely, positively have to use the approach you currently are), you will need to revert the redirects on the 'source' server: maybe you could have it return the information or the redirect based on requesting IP address or something similar?
精彩评论