Get file contents of a domain in another domain in the same server

旧街凉风 提交于 2019-12-02 09:28:59

Glob needs file-access. But since it is on another domain. It doesn't get file-access (and it shouldn't). Even if they are on the same server, they shouldn't be able to access each others files for so many reasons.

What you can do is write a small API on domain1.com that returns a list of images for a certain user. You then access that information using for isntance curl

on domain1.com where the pictures are stored:

<?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

on 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'

Notes:

1) I used file_get_contents instead of curl here since it is easier to use. But not all hosts allow a file_get_contents to a different domain. If they don't allow it use curl (there are a lot of tutorials on the internet)

2) You should check if the $user_id is correct and even add a secret key to the request to keep the hack0rs out. e.g.: file_get_contents('http://www.domain1.com/api/images.pgp?user_id=1&secret=mySecret') And then on domain1.com do a simpel check to see or the secret is correct.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!