繁体   English   中英

获取同一服务器中另一个域中一个域的文件内容

[英]Get file contents of a domain in another domain in the same server

我在同一服务器上有两个域。 www.domain1.com和www.domain2.com。

在www.domain1.com中,有一个名为“图片”的文件夹。 用户可以通过按ID创建一个文件夹,将照片上传到该文件夹​​。 (www.domain1.com/Pictures/User_iD)缩略图是使用上传的图像同时创建的,并保存到此路径,该路径是动态创建的。(www.domain1.com/Pictures/User_iD/thumbs)

这是在我们的系统中使用PHP脚本进行的。

所以我的问题是,我需要在www.domain2.com中显示那些用户上传的图像。 我已经使用下面的代码来做到这一点,但它不起作用。

$image_path="http://www.domain1.com/Pictures/"."$user_id";


$thumb_path="http://www.domain1.com/Pictures/"."$user_id/"."thumbs";

$images = glob($image_path.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);

得到这样的图像,

               foreach ($images as $image) {
      // Construct path to thumbnail
        $thumbnail = $thumb_path .'/'. basename($image);

     // Check if thumbnail exists
    if (!file_exists($thumbnail)) {
    continue; // skip this image
    }

但是当我尝试这样做时,图像不会显示在www.domain2.com/user.php上。 如果我使用相同的代码显示相同域中的图像,则图像看起来很好。

希望我能正确解释情况。 请帮忙。

提前致谢

Glob需要文件访问。 但是由于它在另一个域上。 它没有文件访问权限(也不应)。 即使它们位于同一服务器上,由于多种原因,它们也不应该能够访问彼此的文件。

您可以做的是在domain1.com上编写一个小型API,该API返回特定用户的图像列表。 然后,您可以使用非对称卷曲访问该信息

在存储图片的domain1.com上:

<?php
//get the user id from the request
$user_id = $_GET['user_id'];

$pathToImageFolder = 'path_to_pictures' . $user_id ;

$images = glob($pathToImageFolder.'/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
//return a JSON array of images
print json_encode($images,true); #the true forces it to be an array

在domain2.com上:

<?php
//retrieve the pictures
$picturesJSON = file_get_contents('http://www.domain1.com/api/images.php?user_id=1');
//because our little API returns JSON data, we have to decode it first
$pictures = json_decode($picturesJSON);
// $pictures is now an array of pictures for the given 'user_id'

笔记:

1)我使用file_get_contents而不是curl,因为它更易于使用。 但并非所有主机都允许file_get_contents到其他域。 如果他们不允许,它会使用curl(互联网上有很多教程)

2)您应该检查$ user_id是否正确,甚至向请求添加一个秘密密钥以防止hack0rs。 例如: file_get_contents('http://www.domain1.com/api/images.pgp?user_id=1&secret=mySecret')然后在domain1.com上进行简单检查以查看密码是否正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM