在img src中授予用户输出访问权限是否危险?

here is the situation. I'm building a small site and no file is confidential in it. In many pages, I needed to isolate and print an image for the user. So, I made a small script this way:

<?php
    echo '<img src="'. $_GET['src'] .'" />';
?>

And I like the image source in the URL so it's easy for me to reuse. I am wondering if somebody could try to access other file in the server (for example mysite.com?src=../../SECRET_FILE.txt). I tried to break it myself and couldn't do anything dangerous with this but I'm wondering if it has any flaw? (In the perspective that no image is secret in this website, they are all public and it wouldn't bother me at all if they would find any of these)

Note that the code is not saved in anyway, here is the full script of this page (really just used to save time for user that wants to print an image on the website)

<?php
    echo '<img src="'. $_GET['src'] .'" />';
?>
<script>
    window.print();
</script>

Never trust user input. If every file or script you expose is safe to run, there is no danger of unsafe server-side code running. But you're allowing users to alter your HTML in any way they desire, which is unsafe.

I would check they enter something valid, such as:

echo '<img src="/path/to/images/'. basename($_GET['src']) .'" />';

This will confirm they are only requesting a file from your images directory. Even better would be to confirm the file exists:

$image = '/path/to/images/' . basename($_GET['src']);
if (file_exists($image)) {
     echo '<img src="'. $image .'" />';
} else {
     header("HTTP/1.0 404 Not Found");
}

It's safe server side wise, but your users could use a cross site scripting attack to inject html in it. Think of inserting an script tag to send your site's cookie to the attacker website.

https://www.owasp.org/index.php/Testing_for_Cross_site_scripting

I suggest to be extremely careful when implementing such methods. In this case I would change the implementation to

  1. Check the input to be in a valid/allowed range: store the filenames of allowed images in an array. Work with indices into that array as user parameters. Indices are very easily checked and validated. Thus, no external user can access images he is not allowed to access.

  2. Check the argument to be (1.) numeric and (2.) within the allowed range (0 - array length-1)

I strongly recommend to never ever implement functionality that enables users to scan server directories.