I have two domains in same server. www.domain1.com & www.domain2.com.
in www.domain1.com, there is a folder called 'Pictures'. To that folder user can upload their pictures by creating a folder by their ID. (www.domain1.com/Pictures/User_iD) A thumbnail is created using uploaded image at the same time and being saved to this path which is created dynamically.(www.domain1.com/Pictures/User_iD/thumbs)
This is happening using PHP script in our system.
So my problem is, i need to display those User uploaded images in www.domain2.com. i have used following code to do that, but it is not working.
$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);
getting images like this,
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
}
but when i try to do that, images wont display on the www.domain2.com/user.php. if i use the same code to display images which are in the same domain, images are appearing fine.
Hope i explain the situation correctly. Please help.
Thanks in advance
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.
来源:https://stackoverflow.com/questions/17464345/get-file-contents-of-a-domain-in-another-domain-in-the-same-server