Php Proxy Example

jenssegers/php-proxy – GitHub

This is a HTTP/HTTPS proxy script that forwards requests to a different server and returns the response. The Proxy class uses PSR7 request/response objects as input/output, and uses Guzzle to do the actual HTTP request.
Installation
Install using composer:
composer require jenssegers/proxy
Example
The following example creates a request object, based on the current browser request, and forwards it to The RemoveEncodingFilter removes the encoding headers from the original response so that the current webserver can set these correctly.
use Proxy\Proxy;
use Proxy\Adapter\Guzzle\GuzzleAdapter;
use Proxy\Filter\RemoveEncodingFilter;
use Laminas\Diactoros\ServerRequestFactory;
// Create a PSR7 request based on the current browser request.
$request = ServerRequestFactory::fromGlobals();
// Create a guzzle client
$guzzle = new GuzzleHttp\Client();
// Create the proxy instance
$proxy = new Proxy(new GuzzleAdapter($guzzle));
// Add a response filter that removes the encoding headers.
$proxy->filter(new RemoveEncodingFilter());
try {
// Forward the request and get the response.
$response = $proxy->forward($request)->to(”);
// Output response to the browser.
(new Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($response);} catch(\GuzzleHttp\Exception\BadResponseException $e) {
// Correct way to handle bad responses
(new Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($e->getResponse());}
Filters
You can apply filters to the requests and responses using the middleware strategy:
$response = $proxy
->forward($request)
->filter(function ($request, $response, $next) {
// Manipulate the request object.
$request = $request->withHeader(‘User-Agent’, ‘FishBot/1. 0’);
// Call the next item in the middleware.
$response = $next($request, $response);
// Manipulate the response object.
$response = $response->withHeader(‘X-Proxy-Foo’, ‘Bar’);
return $response;})
->to(”);
Design Patterns: Proxy in PHP - Refactoring Guru

Design Patterns: Proxy in PHP – Refactoring Guru

Proxy is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc. ) and then passes the request to a service object.
The proxy object has the same interface as a service, which makes it interchangeable with a real object when passed to a client.
Usage examples: While the Proxy pattern isn’t a frequent guest in most PHP applications, it’s still very handy in some special cases. It’s irreplaceable when you want to add some additional behaviors to an object of some existing class without changing the client entification: Proxies delegate all of the real work to some other object. Each proxy method should, in the end, refer to a service object unless the proxy is a subclass of a service.
Conceptual Example
This example illustrates the structure of the Proxy design pattern and focuses on the following questions:
What classes does it consist of?
What roles do these classes play?
In what way the elements of the pattern are related?
After learning about the pattern’s structure it’ll be easier for you to grasp the following example, based on a real-world PHP use case.
Conceptual example
realSubject = $realSubject;}
* The most common applications of the Proxy pattern are lazy loading,
* caching, controlling the access, logging, etc. A Proxy can perform one of
* these things and then, depending on the result, pass the execution to the
* same method in a linked RealSubject object.
if ($this->checkAccess()) {
$this->realSubject->request();
$this->logAccess();}}
private function checkAccess(): bool
// Some real checks should go here.
echo “Proxy: Checking access prior to firing a real request. \n”;
return true;}
private function logAccess(): void
echo “Proxy: Logging the time of request. \n”;}}
* The client code is supposed to work with all objects (both subjects and
* proxies) via the Subject interface in order to support both real subjects and
* proxies. In real life, however, clients mostly work with their real subjects
* directly. In this case, to implement the pattern more easily, you can extend
* your proxy from the real subject’s class.
function clientCode(Subject $subject)
//…
$subject->request();
//… }
echo “Client: Executing the client code with a real subject:\n”;
$realSubject = new RealSubject();
clientCode($realSubject);
echo “\n”;
echo “Client: Executing the same client code with a proxy:\n”;
$proxy = new Proxy($realSubject);
clientCode($proxy);
Execution result
Client: Executing the client code with a real subject:
RealSubject: Handling request.
Client: Executing the same client code with a proxy:
Proxy: Checking access prior to firing a real request.
Proxy: Logging the time of request.
Real World Example
There are countless ways proxies can be used: caching, logging, access control, delayed initialization, etc. This example demonstrates how the Proxy pattern can improve the performance of a downloader object by caching its results.
Real world example
namespace RefactoringGuru\Proxy\RealWorld;
* The Subject interface describes the interface of a real object.
*
* The truth is that many real apps may not have this interface clearly defined.
* If you’re in that boat, your best bet would be to extend the Proxy from one
* of your existing application classes. If that’s awkward, then extracting a
* proper interface should be your first step.
interface Downloader
public function download(string $url): string;}
* The Real Subject does the real job, albeit not in the most efficient way.
* When a client tries to download the same file for the second time, our
* downloader does just that, instead of fetching the result from cache.
class SimpleDownloader implements Downloader
public function download(string $url): string
echo “Downloading a file from the Internet. \n”;
$result = file_get_contents($url);
echo “Downloaded bytes: “. strlen($result). “\n”;
return $result;}}
* The Proxy class is our attempt to make the download more efficient. It wraps
* the real downloader object and delegates it the first download calls. The
* result is then cached, making subsequent calls return an existing file
* instead of downloading it again.
* Note that the Proxy MUST implement the same interface as the Real Subject.
class CachingDownloader implements Downloader
* @var SimpleDownloader
private $downloader;
* @var string[]
private $cache = [];
public function __construct(SimpleDownloader $downloader)
$this->downloader = $downloader;}
if (! isset($this->cache[$url])) {
echo “CacheProxy MISS. “;
$result = $this->downloader->download($url);
$this->cache[$url] = $result;} else {
echo “CacheProxy HIT. Retrieving result from cache. \n”;}
return $this->cache[$url];}}
* The client code may issue several similar download requests. In this case,
* the caching proxy saves time and traffic by serving results from cache.
* The client is unaware that it works with a proxy because it works with
* downloaders via the abstract interface.
function clientCode(Downloader $subject)
$result = $subject->download(“);
// Duplicate download requests could be cached for a speed gain.
echo “Executing client code with real subject:\n”;
$realSubject = new SimpleDownloader();
echo “Executing the same client code with a proxy:\n”;
$proxy = new CachingDownloader($realSubject);
Executing client code with real subject:
Downloading a file from the Internet.
Downloaded bytes: 1270
Executing the same client code with a proxy:
CacheProxy MISS. Downloading a file from the Internet.
CacheProxy HIT. Retrieving result from cache.
Simple PHP proxy script - GitHub

Simple PHP proxy script – GitHub

This proxy script allows you to forward all HTTP/HTTPS requests to another server. Works for all common request types
including GET, POST requests with files, PATCH and PUT requests. It has minimal set of requirements
(PHP >=5. 6, libcurl, gzip) which are available even on the smallest free hostings and has its own simple authorization
and cookie support.
How to use
Copy the script to publicly-accessible folder of a PHP web server (the script is standalone and has no PHP dependencies)
Make a cURL request targeting this script
Add Proxy-Auth header with auth key found here
Add Proxy-Target-URL header with URL to be requested by the proxy
(Optional) Add Proxy-Debug header for debug mode
In order to protect using proxy by unauthorized users, consider changing Proxy-Auth token in proxy source file and in all your requests.
How to use (via composer)
This might be useful when you want to redirect requests coming into your app.
Run composer require zounar/php-proxy
Add Proxy::run(); line to where you want to execute it (usually into a controller action)
In this example, the script is in AppController – actionProxy:
use Zounar\PHPProxy\Proxy;
class AppController extends Controller {
public function actionProxy() {
Proxy::$AUTH_KEY = ‘‘;
// Do your custom logic before running proxy
$responseCode = Proxy::run();
// Do your custom logic after running proxy
// You can utilize HTTP response code returned from the run() method}}
Make a cURL request to your web
In the example, it would be
In order to protect using proxy by unauthorized users, consider changing Proxy-Auth token by calling
Proxy::$AUTH_KEY = ‘‘; before Proxy::run(). Then change the token in all your requests.
Usage example
Following example shows how to execute GET request to. Proxy script is at. All proxy settings are kept default, the response is automatically echoed.
$request = curl_init(”);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
‘Proxy-Auth: Bj5pnZEX6DkcG6Nz6AjDUT1bvcGRVhRaXDuKDX9CjsEs2’,
‘Proxy-Target-URL: ‘));
curl_exec($request);
Debugging
In order to show some debug info from the proxy, add Proxy-Debug: 1 header into the request. This will show debug info in plain-text containing request headers, response headers and response body.
‘Proxy-Target-URL: ‘,
‘Proxy-Debug: 1’));
Specifying User-Agent
Some sites may return different content for different user agents. In such case add User-Agent header to cURL request, it will be automatically passed to the request for target site. In this case it’s Firefox 70 for Ubuntu.
‘User-Agent: Mozilla/5. 0 (X11; Ubuntu; Linux x86_64; rv:70. 0) Gecko/20100101 Firefox/70. 0’,
Error 301 Moved permanently
It might occur that there’s a redirection when calling the proxy (not the target site), eg. during -> redirection. You can either modify/fix the proxy URL (which is recommended), or add CURLOPT_FOLLOWLOCATION option before curl_exec.
curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
Save response into variable
The default cURL behavior is to echo the response of curl_exec. In order to save response into variable, all you have to do is to add CURLOPT_RETURNTRANSFER cURL option.
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);

Frequently Asked Questions about php proxy example

What is a PHP proxy?

Proxy is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object.

How to write a proxy in PHP?

Simple PHP ProxyCopy the Proxy.php script to publicly-accessible folder of a PHP web server (the script is standalone and has no PHP dependencies)Make a cURL request targeting this script.Add Proxy-Auth header with auth key found here.Add Proxy-Target-URL header with URL to be requested by the proxy.More items…

What is miniProxy?

miniProxy is a simple web proxy written in PHP that can allow you to bypass Internet content filters, or to browse the internet anonymously.

Leave a Reply

Your email address will not be published. Required fields are marked *