Home > Enterprise >  SVG from PHP script is not working in img src
SVG from PHP script is not working in img src

Time:11-04

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 = \yii\web\Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'image/svg xml');

CodePudding user response:

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']);

CodePudding user response:

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

  • Related