Search code examples
phphtmlcurlphp-curl

Display image from curl request in html<img> tag


One of the pages of a website I'm working on should display information about a manga such as it's cover image. I'm trying to display an image I got by making a curl request.

<?php
    if(isset($_GET['info'])) {
        $postedData = $_GET["info"]; //json object containing info about manga such as author/title etc.
        $info = json_decode($postedData, true);
        $mangacoverid = $info['im']; //id of the cover image that i'm getting from json object

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://cdn.mangaeden.com/mangasimg/" . $mangacoverid); //link of API i'm using and adding cover id to it
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $picture = curl_exec($ch);
        curl_close($ch);
        header('Content-type: image/jpeg');
        echo $picture; //displays image in browser
    }
        ?>

Some 'mangacoverid' for testing purposes:

ff/ff94bb880357b6b811bccbbfd3356c5ec41fbb184291323f0ed6a86a.jpg
c1/c1b0173d8986681f23ecf5a69d26aa9dab4a04db4d40f99bed539198.jpg
0c/0cf6ebf78074e748ab2aeea3a0fcb9e0dd43040974c66e24fa46703f.jpg
5d/5dcfed2e033c2da62e7ac89367533ebbc344373c46a005e274a16785.png
18/18b1f0b13bccb594c6daf296c1f9b6dbd83783bb5ae63fe1716c9091.jpg
35/35bf6095212da882f5d2122fd547800ed993c58956ec39b5a2d52ad4.jpg

While I am able to display the image in the page, the whole page background becomes black with the image in the middle of the page. (i.e. <body> style="margin: 0px; background: #0e0e0e;>).

What I am trying to do is to insert the image in an HTML <img> tag, so that I can place it somewhere else in the page.

I tried just putting the normal cdn link with 'mangacoverid' attached to it in an <img src=""> tag but the image provider doesn't allow hotlinking and it throws 403 error.


Solution

  • I tested your code and it seems to be working correctly when the cover ID is hard coded. Could the issue be that the JSON passed via query param is not getting parsed correctly (due to URL encoding)?

    Does it work correctly for you with a cover ID hard coded?

    File image.php

    <?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, sprintf('https://cdn.mangaeden.com/mangasimg/%s', $_GET['id']));
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $picture = curl_exec($ch);
    curl_close($ch);
    header('Content-type: image/jpeg');
    echo $picture;
    

    And in your script that generates the page displaying the image:

    // Assuming $info holds the decoded json for the manga
    echo(sprintf('<img src="image.php?id=%s>', $info['im']);