在我自己的域中加载远程图像而不复制

时间:2016-12-24 10:59:19

标签: php

我想在我的域中加载外部图像,而不是在我的服务器上复制图像,就好像它看起来我正在托管这个图像。

我尝试过使用curl将其复制到我的服务器。但我想要它而不复制。即外部图像位置为http://example.com/image.jpg

现在我想将此图像加载为http://examplemydomain.com/image.jpg而不复制我服务器中的文件。任何建议如何在PHP中实现这一点?

2 个答案:

答案 0 :(得分:0)

在我的工作场所,我们使用这样的东西。注意:它的尺寸更大,因为图像大小适合150x150平方头像。只需删除该部分,然后使用width$height代替$newwidth即可获得原创内容。我会自己删除它,但是在圣诞节的早晨,我只是没心情。

的.htaccess

RewriteEngine On
RewriteRule ^photo/(.*)$ photo.php?fn=$1 [QSA,L]

.photo.php

<?php

// Images (not the safest way to check though )
$allowed_ext = array(
    'gif' => 'image/gif',
    'png' => 'image/png',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg'
);
$square_size = 150;

// Get file data
$file_name = trim($_GET['fn']);
$file_path = 'http://example.com/' . urlencode($file_name);
list($width, $height) = @getimagesize($file_path);

// Do something ONLY if file is found
if (!empty($width) && !empty($height)) {
    $ext = pathinfo($file_path, PATHINFO_EXTENSION);

    // We accept only predefined images. if not image extension - DIE!
    if (empty($allowed_ext[$ext])) {
        die();
    } else {
        $mtype = $allowed_ext[$ext]; // Set our predefined meme types ¯\_(ツ)_/¯
    }

    // Get new image ratio
    $ratio = ($width > $height) ? $square_size / $width : $square_size / $height;

    // Resize only if original is larger then allowed
    if ($ratio < 1) {
        $new_width = $width * $ratio;
        $new_height = $height * $ratio;
    } else {
        $new_width = $width;
        $new_height = $height;
    }

    // Resample
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($file_path);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Output
    header('Content-Type: ' . $mtype);
    imagejpeg($image_p, null, 100);
}
die;

设置完成后,您只需打开http://examplemydomain.com/photo/image.jpg即可加载远程图像。

答案 1 :(得分:0)

如果您的图像具有特定的目录结构,例如:它们都存在于/ public / images下,那么您可以编辑服务器设置(httpd.conf或apache2.conf,具体取决于您的服务器)并添加类似的代理到下面:

ProxyPass /public/images http://examplemydomain.com/public/images

记得在进行更改后重新启动apache / httpd

相关问题