I need to implement a simple PHP proxy in a web application I am building (Its flash based and the destination service provider doesn't allow edits to their crossdomain.xml file)
Can any php gurus offer advice on the following 2 options? Also, I think, but am not sure, that I need to include some header info as well.
Thanks for any feedback!
option1
$url = $_GET['path'];
readfile($path);
option2
$content .= file_get_contents($_GET['path']);
if ($content !== false)
{
echo($content);
}
else
{
// there was an error
}
First of all, never ever ever include a file based only on user input. Imagine what would happen if someone would call your script like this:
http://example.com/proxy.php?path=/etc/passwd
Then onto the issue: what kind of data are you proxying? If any kind at all, then you need to detect the content type from the content, and pass it on so the receiving end knows what it's getting. I would suggest using something like HTTP_Request2 or something similar from Pear (see: http://pear.php.net/package/HTTP_Request2) if at all possible. If you have access to it, then you could do something like this:
// First validate that the request is to an actual web address
if(!preg_match("#^https?://#", $_GET['path']) {
header("HTTP/1.1 404 Not found");
echo "Content not found, bad URL!";
exit();
}
// Make the request
$req = new HTTP_Request2($_GET['path']);
$response = $req->send();
// Output the content-type header and use the content-type of the original file
header("Content-type: " . $response->getHeader("Content-type"));
// And provide the file body
echo $response->getBody();
Note that this code hasn't been tested, this is just to give you a starting point.
Here's another solution using curl
Can anyone comment??
$ch = curl_init();
$timeout = 30;
$userAgent = $_SERVER['HTTP_USER_AGENT'];
curl_setopt($ch, CURLOPT_URL, $_REQUEST['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
} else {
curl_close($ch);
echo $response;
}