3

I'm fairly new to PHP and I need to know how to display a file as an image. For example, opening http://example.com/script.php will show an image.

My reasoning for this is I need to put it in the src attribute of <img>. I want the image to change depending on what time it is.

I currently have 3 images to cycle between.

What I currently have:

<?php

    $w = date('W');         # week
    $d = date('N');         # day
    $t = date('G');             # time

    dealWithTime($d);

    function dealWithTime(day) {
        if (day == 1) {
            # Monday
            if ($w == 13) {
                # Week 13

            } else if ($w == 14) {
                # Week 14
                if ($t >= 0 && $t <= 6) {
                    # Image = 1.png
                } else if ($t > 6 && $t <= 10) {
                    # Image = 2.png
                } else if ($t > 10 && $t <= 14) {
                    # Image = 3.png
                } else if ($t > 14 && $t <= 18) {
                    # Image = 1.png
                } else if ($t > 18) {
                    # Image = 2.png
                }
            }
        } else if (day == 2) {
            # Tuesday
        } else if (day == 3) {
            # Wednesday
        } else if (day == 4) {
            # Thursday
        } else if (day == 5) {
            # Friday
        } else if (day == 6) {
            # Saturday
        } else if (day == 7) {
            # Sunday
        }
    }

?>
Spedwards
  • 4,167
  • 16
  • 49
  • 106
  • hope [this link](http://stackoverflow.com/questions/901201/create-a-dynamic-png-image) will help you a lot. – Arka Mar 29 '14 at 04:57

3 Answers3

2

Firstly, you are right with the src part. You can simply use a .php file as src of your image and have a nice image displayed. So, once you have figured out what image you want to show the user, here are a few ways you can do this:

  1. readfile - you read the contents of the image, out put it with proper headers.
  2. You redirect to the image file. But there is a caveat here: you have to send a 302 Found header instead of 301 Moved Permanently, because, browsers these days cache permanent redirects!
Community
  • 1
  • 1
Prasanth
  • 5,230
  • 2
  • 29
  • 61
0

Use PHP's GD library. PHP's website has some examples to get you started:

http://www.php.net/manual/en/book.image.php

crunch
  • 675
  • 3
  • 8
0

After you are done with the logic, then have PHP set the content-type of script.php.

Right now script.php's content-type is the default text/html - but you want it to display an image, so you would need to do the following:

 header( "Content-type: image/png" );

Then from whatever file you got from the logic, I would use the file_get_contents() function and echo or print() the image.

hrgui
  • 590
  • 2
  • 5