I am using a PHP script to read some folders in directory and based on their names retrieve their posters. All of this works fine on localhost. However, when opening externally, this does not work and results in blank images.
A screenshot from localhost:
The problem can be found at 89.241.171.100/Prac/.
PHP generating img tag:
while (false !== ($entry = readdir($handle))) {
$counter++;
echo "<span class='title'>
<img src='holder.js/200x280/text:$entry'
alt='$entry'
onload='loader(this, \"$entry\")' />
</span>";
if($counter == 5) break;
}
PHP fetching the src for the images called via ajax from loader():
if($_POST['title']) {
$title = $_POST['title'];
$imdb = new Imdb();
$movieArray = $imdb->getMovieInfo("$title");
$link = $movieArray["poster_large"];
echo $link;
}
Loader() function:
$.ajax({
type: 'post',
url: 'loader.php',
data: 'title='+title,
success: function(data) {
img.src = data;
}
});
This looks like an issue with the way you're loading it. These images are being provided via Akamai's CDN and it's not liking the referrer that it's getting.
Here's what's being returned instead of the image payload.
<HTML><HEAD>
<TITLE>Referral Denied</TITLE>
</HEAD><BODY>
<H1>Referral Denied</H1>
You don't have permission to access "http://ia.media-imdb.com/images/M/MV5BMTM5NjM0ODY1NF5BMl5BanBnXkFtZTcwMjk5NjI0Ng##._V1._SY500.jpg" on this server.<P>
Reference #24.24c633b8.1366714063.2a353f15
</BODY></HTML>
I'm not encouraging breaching anyone's terms but this might be of some use to you, I suspect that passing an empty referrer will fix the problem as when you visit the image URL directly it works (and doesn't send a referrer).
EDIT:
This fiddle is a working example of what I was suggesting earlier. You'll notice the image directly linked is dead, but the one with no referrer loads perfectly.
U could use the Imdb API
Just request the data with : http://imdbapi.org/?id={id}&type=json&plot=simple&episode=1&lang=en-US&aka=simple&release=simple
{id} being the imdb id of the movie. Then u can access the picture with :
$data = json_decode(file_get_contents("http://imdbapi.org/?id={id}&type=json&plot=simple&episode=1&lang=en-US&aka=simple&release=simple"));
$img = $data->poster;
Related
I'm attempting to write a small image proxier script on my website, because imgur is blocked on my current network and want to be able to see images from Stack Overflow.
I've got this code on my personal website:
$image = $_GET['url'];
$imageData = base64_encode(file_get_contents($image));
echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
This should take the URL of an image, have my server download the image and then display it (by itself) on the page.
This works, for example, if I was trying to proxy my Stack Overflow account profile picture, I could use this link, which, as you can see works totally fine to display the picture on the page. I can see this image even on my blocked network.
Now, I've created a userscript that automatically transverses all images and links on a loaded page, and switches it's source/href link with a proxied version.
This is the part that is not working for me, when supplied with a proxied link, the image does not show in the element.
Here is my userscript:
function runProxier() {
$('img').each(function() {
var image = $(this);
if(!image.data('image_proxier_converted')) {
image.attr('src', getProxyLink(image.attr('src')));
image.attr('data-image_proxier_converted', 1);
}
});
$('a').each(function() {
var link = $(this);
if(!link.data('image_proxier_converted')) {
link.attr('href', getProxyLink(link.attr('href')));
link.attr('data-image_proxier_converted', 1);
}
});
}
function getProxyLink(givenLink) {
if (givenLink) {
if (replace_from.some(function(v) {
return givenLink.indexOf(v) >= 0;
})) {
return proxy_link + encodeURI(givenLink);
} else {
return givenLink;
}
}
}
When ran on my example, my profile picture, the link is properly converted.
<img src="//grumpycrouton.com/other/image_proxy/?url=https://i.stack.imgur.com/YkRwP.png?s=48&g=1" alt="" width="24" height="24" class="-avatar js-avatar-me" data-image_proxier_converted="1">
But the image does not show, it's still blank in my menu bar.
Why is my image not displayed?
I was able to resolve this problem by using this code on my server:
<?php
if(!isset($_GET['url'])) {
die('No image given');
}
header('Content-Type: image/jpeg');
readfile($_GET['url']);
?>
The header() call tells the client that it should serve an image, and readfile() will download (but not store on my server) and display the image.
I also noticed my URL was not properly encoding to be sent to the server, so I altered my userscript like so:
function getProxyLink(givenLink) {
if (givenLink) {
if (replace_from.some(function(v) {
return givenLink.indexOf(v) >= 0;
})) {
var new_link = proxy_link + encodeURIComponent(givenLink);
console.log(new_link);
return new_link;
} else {
return givenLink;
}
}
}
I am trying to render an image using php for my website that will dynamically display images straight from the Google Places API (Reference https://developers.google.com/places/web-service/photos?hl=en)
The image source looks like the following example:
https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=API_KEY
If you visit this URL via your browser it will render an image and this is no longer the URL you see.
My issue is that when viewing the page source, this is exactly the image source URL you see which is bad because my key is then publicized. What is the proper way to render images while keeping my key private? I have searched the API and the web for this but to no avail. I did see some tricks using file_get_contents and file_put_contents but my web host does not allow that. Finally, saving the images is against the api rules so that is not an option.
Any tips would be appreciated. Thanks in advance.
You may send a HEAD-request to the particular URL and extract the content of the Location-header:
<?php
$context = stream_context_create(array('http' =>array('method'=>'HEAD')));
$fp = fopen('desiredPlacesApiImgUrl', 'rb', false, $context);
$meta = stream_get_meta_data($fp);
if(isset($meta['wrapper_data'])){
$location=preg_grep('#^\s*Location:#',$meta['wrapper_data']);
if(count($location)){
$imgUrl=trim(preg_replace('#^Location:#i','',reset($location)));
die($imgUrl);//the desired img-url
}
}
fclose($fp);
?>
But when file_get_contents isn't allowed on your server I'm afraid fopen also isn't allowed for external URLs.
Another option: use the Maps-Javascript-API, request the place and the response should contain the desired URL (without using any key).
Demo:
function loadPlacePhotos() {
var photos = document.querySelectorAll('img[data-place]'),
service = new google.maps.places
.PlacesService(document.createElement('div'));
for (var i = 0; i < photos.length; ++i) {
(function(photo) {
service.getDetails({
placeId: photo.getAttribute('data-place')
}, function(r) {
if (r.photos.length) {
google.maps.event.addDomListener(photo, 'click', function() {
photo.setAttribute('src', r.photos[0].getUrl({
maxHeight: 100
}));
photo.style.visibility = 'visible';
if (r.photos.length > 1) {
r.photos.push(r.photos.shift());
photo.setAttribute('title', 'click to see next photo');
photo.style.cursor = 'pointer';
} else {
google.maps.event.clearListeners(photo, 'click');
}
});
google.maps.event.trigger(photo, 'click');
}
});
}(photos[i]));
}
}
body::before {
content: url(https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white2.png);
}
img[data-place] {
visibility: hidden;
display: block;
}
<ul>
<li>
Google: Mountain View
<img data-place="ChIJj61dQgK6j4AR4GeTYWZsKWw" />
</li>
<li>
Google: Sydney
<img data-place="ChIJN1t_tDeuEmsRUsoyG83frY4" />
</li>
<li>
Google: Berlin
<img data-place="ChIJReW1rcRRqEcRaY3CuKBdqZE" />
</li>
</ul>
<script defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=loadPlacePhotos"></script>
The demo uses a custom attribute for images data-place which will be assigned to a placeId of a particular place. It parses these images, requests the photos and displays them(when there ar more than 1 photo the user can switch between the photos by clicking on the image )
However, it must not be a problem when your key is visible, set the allowed referers for your (browser)-key and you can use the key without a risk on your own domain.
So I'm making a website for a client, and the client has tons of photos from tons of different bands they photographed in the 80s and 90s that they would like to try and sell.
Instead of making a page for each band (theres over 100) like the previous site did, I am trying to make one page that uses Javascript/PHP to change the image directory to that band when the text for that band is clicked.
So far, I am able to use a PHP function to find photos in the slideshow folder, but I have been unable to update this function to search through a sub directory in the slideshow folder. (For example, when 'Metallica' is clicked, I empty #imageGal, and then I would like to append all the new metallica images from the metallica folder to the gallery).
My PHP code is:
<?php
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
This PHP code seems to work great.
I get the images using this JQuery code:
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
When a user clicks on a band (ie Metallica), this code is executed.
$('.options').mousedown(function() {
var name = $(this).attr('id');
//$('#output').html(name);
$.ajax({
type: "POST",
url: "slideshow/getimages.php",
data: {
imageDir: name
}, success: function(msg){
alert( "Data Saved: " + msg );
}
});
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
});
I am unable to get the $imagesDir variable to change, but if I were to manually enter "Metallica" in $imagesDir = "Metallica" variable, it loads those images perfectly.
Can anyone offer any help/advice? I've been at this for a many hours now. Thanks for anything!
Unless you have register_globals on then you need to reference the variable through the global $_POST array. $_POST['imagesDir'] instead of $imagesDir.
However I would state in it's current form it would be a very bad idea to simply replace it as someone could attempt to exploit your code to list any directory on the server.
You should append the parent directory to prevent an exploit. Something like this:
EDIT you have to chdir() to the path before glob will work. I've updated my code below.
<?php
$imagesDir = $_SERVER['DOCUMENT_ROOT']; // this is the root of your web directory
$images = array();
// and this line ensures that the variable is set and no one can backtrack to some other
// directory
if( isset($_POST['imagesDir']) && strpos($_POST['imagesDir'], "..") === false) {
$imagesDir .= "/" . $_POST['imagesDir'];
chdir($imagesDir);
$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
}
echo json_encode($images);
?>
I'm not an ajax expert but you seem to be posting imageDir.
So your PHP code should be looking for $_POST['imageDir'].
<?php
$imagesDir = $_POST['imageDir'];
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
Does this solve it?
I want to send an array from javascript to php via ajax function.
And I don't want show the result as callback, but immediately open the target php file and show the images.
I mean, I want open the php file directly on the server side.
I think this is quite simple, but I just have no idea.
My javascript looks like:
var stringArray = new Array("/images/1.jpg", "/images/2.jpg", "/images/3.jpg");
$.ajax({
url: 'test.php',
data: {stringArray:stringArray},
success: function() {
window.open('test.php'); // It opens test.php in a window but shows nothing!
},
});
the test.php file:
$stringArray = $_GET['stringArray'];
foreach($stringArray as $value) {
echo "<img src=" . $value . "></img>";
}
Thanks for any help!
Likely the window.open command is being called without the POST data needed.
Now, I don't know what you want to do here but, why send an Ajax request when you don't really want to make use of it?.
Edit: just to make it a bit clearer, you seem to be calling the php file with no data trough POST. There is no clean way of opening a window in JS with POST data, just try GET for no critical information. Let is know how it goes.
As I can see, You are sending data by post method and accessing in test.php
but when u open file via window.location it doesn't get POST data hence no data get populated
You can achieve it via $_SESSION.
in test.php
session_start();
if(!empty($_POST['stringArray'])) {
$_SESSION['stringArray'] = $_POST['stringArray'];
}
$stringArray = (isset($_SESSION['stringArray']) && $_SESSION['stringArray'] != '') ? $_SESSION['stringArray'] : $_POST['stringArray'];
foreach($stringArray as $value) {
echo "<h3>" . $value . "</h3>";
}
Hope this will work for you...
you should write
var stringArray = new Array("apple", "banana", "orange");
$.ajax({
type: 'post',
url: 'test.php',
data: {stringArray:stringArray},
success: function(message) {
window.open(message); // It will open a window with contents.
},
});
I doesn't show the output because when you open the page on the callback you are not sending anything through to the test page through the post variable. Why you would want to do this I don't know. Send the information through the url, get.
I'm looking for a php script server side that load an image in a div on client side.
first shot:
ajax.php
if((isset($_POST['id'])) && ($_POST['id']=="loadphoto") && (ctype_digit($_POST['idp']))) {
$query=mysql_query("SELECT articleid, photoid FROM articles_photos WHERE id='".$_POST['idp']."'", $mydb);
if(mysql_num_rows($query)!=0){
while($row=mysql_fetch_array($query, MYSQL_NUM)) {
$path="./articles/photos/".$row[0]."/".$row[1];
}
echo $path;
}
}
myjs.js
function loadPhoto(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'idp='+escape(mexid)+'&id=loadphoto',
success: function(msg) {
$('.articleviewphoto1').find("img").each(function(){
$(this).removeClass().addClass('photoarts');
});
$('#'+mexid).removeClass().addClass('photoartsb');
$('#visualizator').html('<img src="'+msg+'" class="photoartb" />');
}
});
return false;
}
Are you looking to host a list of possible images in the PHP file and load different images based on the id you send? If so, you can set:
$Img = $_POST['idp'];
And use a switch statement to pass back the image file path:
switch ($Img){
case (some_value):
echo 'images/some_file.jpg';
break;
case (another_value):
echo 'images/another_file.jpg';
break;
}
Then place the file path in an tag and load that into $('#visualizator').html();
Am I on track at least with what you want? If so, I can flesh the answer out a bit.
I'm assuming the image already exists somewhere and isn't being generated on the fly. In the PHP script, you can access the variables with $_POST['idp'] and $_POST['id']. Do whatever processing you need, and then simply echo the URL. The variable msg in the javascript will be everything echo'd by the PHP script. Then, you could just do this:
$('#visualizator').html('<img src="' + msg + '" />');