phploadingbroken-image

I'm programming a php system to load an image depending on the parameters given to the method. The image is loading as a broken image


I'm programming a php system to load an image depending on the parameters given to the method. This code was working fine until recently, when I modified it. It's one of those classic "It was working, but now, all of the sudden, it's not" cases. I can't figure out what I did to mess it up, that is if I did anything to mess it up.

public function image($parameters) {

    //default values for parameters
    $param1 = ' ';
    $param2 = ' ';

    if(!empty($parameters)) {

        foreach($parameters as $key => $value){

            if(!empty($parameters[$key+1])) {

                $value = $value . '/';

            }

            switch($key) {

                case 2:
                    $param1 = $value;
                break;
                case 3:
                    $param2 = $value;
                break;

            }
        }

    }

    $dir = '/resources/images/';
    $file = VIEWDIR . $dir . $param1 . $param2;
    echo $file;
    if(file_exists($file)) {

        $file = file_get_contents($file);
        header("Content-type: image/png");
        echo $file;

    }

}

The code above results in the following HTML


Solution

  • You can't echo $file before you set the header as that will break the output.

    From php.net:

    "Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. "