skip to Main Content

I’m trying to open SVG file first in PHP and then return this data:

$file = dirname(__FILE__) . $_GET["file"] . ".svg";

if (!file_exists($file)) {
    $file = dirname(__FILE__) . $_GET["file"] . ".png";
    if (!file_exists($file)) {
        throw new NotFoundHttpException();
    } else
        header('Content-Type: image/png');
} else
    header('Content-Type: image/svg+xml');

$content = file_get_contents($file);
return $content;

And in HTML:

<img src="script.php?file=someimage">

Problem is that its not showing SVG images in the tag. It works, if I set script.php?file=someimage to the URL string of my browser, but not inside the tag. PNG works fine. If i set just

<img src="someimage.svg">

it also works perfect.

embed and object tags works, but I need img.

UPDATE:

The problem was in Yii2, I send headers wrong way. In some reason it works for PNG, but not for SVG.

It should be done like that:

Yii::$app->response->format = yiiwebResponse::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'image/svg+xml');

2

Answers


  1. Looks like you forgot the /. Try replacing these lines where appropriate:

    $file = dirname(__FILE__) . '/' . $_GET["file"] . ".svg";
    // ...
    $file = dirname(__FILE__) '/' . $_GET["file"] . ".png";
    

    dirname() gives back a string without a trailing slash, so it was trying to open /path/to/scriptdirsomefile.svg.

    Security

    Also, I noticed that your script can be made to do bad things, such as exposing arbitrary files on the server. You can prevent a lot of exploits by doing some basic sanitizing of $_GET['file'] before starting:

    $_GET['file'] = preg_replace('#/#', '_', $_GET['file']);
    
    Login or Signup to reply.
  2. Change return $content; to echo $content;

    So if the image files are on the same directory, it will be:

    <?php
    $file =  $_GET["file"] . ".svg";
    
    if (!file_exists($file)) {
        $file =  $_GET["file"] . ".png";
        if (!file_exists($file)) {
            throw new NotFoundHttpException();
        } else
            header('Content-Type: image/png');
    } else
        header('Content-Type: image/svg+xml');
    
    $content = file_get_contents($file);
    echo $content;
    ?>
    

    Working example #1 (showing svg):

    http://www.createchhk.com/SOanswers/subc/index.php

    Working example #2 (showing png):

    http://www.createchhk.com/SOanswers/subc/index2.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search