Search code examples
phpamazon-s3aws-sdkaws-php-sdk

AWS S3 get images via Proxy - PHP


I have a bucket at S3 where i have uploaded the images. Now i am fetching the images using AWS - SDK. Now i want to bypass the image via Proxy

$client = new Aws\S3\S3Client([
            'version'     => 'latest',
            'region'      => 'us-east-1',
            'debug'       => TRUE, // enable debug info
            'stats'       => TRUE, // enable stats
            '@http'  => [
            'proxy' => 'http://192.168.16.1:10'
            ],
            'credentials' => [
                'key'    => base64_decode(KEY),
                'secret' => base64_decode(SECRET)
            ]
        ]);

Here is my bucket settings and when i did wireshark it still showing AWS ip address in request.

Can anybody tell me how to bypass S3 images with proxy.


Solution

  • If I understand you correctly you want to set up a reserve proxy for your images E.G your system downloads the images send to the browser so it can render them, and you don't want users to know your path / you don't want public read access on your bucket.

    If that is the case you can use the following code to download the file via

    $result = $client->getObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname
    ));
    
    header("Content-Type: {$result['ContentType']}");
    echo $result['Body'];
    

    this could then be set up on a specific URL with the key as a parameter or if your bucket is correctly secured you could just use the key name via GET E.G URL image.php?key=some/key/on/aws.jpg and use $keyname = $_GET['key'] inside your file.

    If you're using a MySQL table to use a lookup it would be $id = $_GET['id']; and create a function that protects against SQL Injection and returns the key column then use that for your $keyname an example table would be $keyname and that can be set by a mapping database table E.G

    CREATE TABLE `proxy_map`(
       `id` INT(11) NOT NULL PRIMARY KEY,
       `key` TEXT NOT NULL
    )
    

    If you want to limit it so only this specific site can use it you can use a referrer check

    $url = parse_url($_SERVER['HTTP_REFERER'] , PHP_URL_HOST);
    if($url !== $_SERVER[HTTP_HOST]){ // assuming that the images are only loaded on the same site as this php script
        http_response_code(404);
        echo "<h1>File Not Found</h1><p>Sorry the file you were looking for could not be found</p>";
    }
    

    If you wish to allow the images from a set of sites E.G you have a subdomain setup you can use.

    $url = parse_url($_SERVER['HTTP_REFERER'] , PHP_URL_HOST);
    $allowedDomains = array(
        $_SERVER[HTTP_HOST],
        "www.example.com"
    );
    if(!in_array($url, $allowdDomains))