What are the best practices for implementing a proxy script in PHP to ensure security and efficiency?

When implementing a proxy script in PHP, it is important to ensure both security and efficiency. To do so, use proper input validation to prevent malicious requests and ensure that the proxy server is not being misused. Additionally, consider implementing rate limiting to prevent abuse and optimize the script for performance.

<?php
// Validate input URL
if (filter_var($_GET['url'], FILTER_VALIDATE_URL) === false) {
    http_response_code(400);
    exit('Invalid URL');
}

// Rate limiting to prevent abuse
$ip = $_SERVER['REMOTE_ADDR'];
$limit = 100; // requests per hour
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'proxy:' . $ip;
$count = $redis->incr($key);
$redis->expire($key, 3600);
if ($count > $limit) {
    http_response_code(429);
    exit('Rate limit exceeded');
}

// Proxy request
$ch = curl_init($_GET['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>