1

How can i use php to get an image url from database (based on user id) and display it out as an image. http://mysite.com/img.php?id=338576

The code below shows a php script goes to a database , check whether the specific user(using the id in the link above) exist then get the image url out of that user's row.

 <?php
    //connect to database
    include ("connect.php");

    //Get the values
       $id = mysql_real_escape_string($_GET['id']);


    //get the image url
      $result = mysql_query("SELECT * FROM users WHERE id='$id'")
      or die(mysql_error()); 
      $row = mysql_fetch_array($result);
      if($row)
      {
        $img_url = row['imgurl'];
        mysql_close($connect);

      }
      else{
      }

    ?>

The $Img_url is an actual image link www.asite.com/image.jpg

The problem is how can i use php to make an image from the image link($img_url)? By which http://mysite.com/img.php?id=338576 will turn into an image.

I hope someone could guide me

Thanks!

1

2 Answers 2

3

The easiest way:

header('Location: url/to/image');

You could also proxy the request, which uses your bandwidth:

echo(file_get_contents('url/to/image'));
Sign up to request clarification or add additional context in comments.

3 Comments

@micha - No, his image is a file whose location is listed in a database. Big difference.
@micha Yeah, so maybe you can +1 my answer now, instead of -1. By the way, you're a pretty cool guy, deleting all your critical comments after you were proven wrong.
for the second method header("Content-type: image/" + $type); is required
-1

This is pretty basic stuff. Am I understanding you correctly? I would just do this:

<?php

$img_html = '<img src="' . $img_url . '" />';


echo $img_html;

?>

Or check this answer: How do I script a php file to display an image like <img src="/img.php?imageID=32" />?

8 Comments

that wont work because i need to use mysite.com/img.php?id=338576 as an image src elsewhere.
Why do you need to do that? In that "elsewhere", can't you just use the id to find the actual image location in the database, and then just show the link to the image directly? @micha - Ok, well let's see your answer then!
I.e. use the same query you did above to get the image location. You could store that query in a function and use it wherever you need an image to match an id.
@ButtleButkus, There are perfectly good reasons why you may want to serve images directly with PHP, rather than outputting HTML. Not everything you do with PHP ends up on a web page...
Why can't i do elsewhere? i have my own reasons to do so. Btw i found an answer to my problem
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.