Dustin James
Dustin James

Reputation: 571

Displaying an image from a directory in PHP

I'm trying to display an image file from a directory using a PHP echo command and an IMG tag.

Here is the code:

//These variables represent the file name extensions from a form element from a previous page

$bannerimg=$_POST["banimg"];
$adimage=$_POST["adimage"];

echo "<img src='imgdir/'".$bannerimg."/>";

When I echo out the file variables ($bannerimg and $adimage) I get the proper file name and extension.

In theory, will this work? If so, what is the proper syntax to handle that echo statement?

Thanks for all the help.

Dustin

Upvotes: 0

Views: 351

Answers (3)

phpmeh
phpmeh

Reputation: 1792

It should work.

To Sandeep's comment, I would have gone the other way.

echo '<img src="imgdir/'.$bannerimg.'/>';

Using " means the parser needs to check to see if there is anything to evaluate.

Upvotes: -1

yannis
yannis

Reputation: 6335

Yes it would work, but you should have tested that already.

Alternative syntaxes to the echo statement that I find a little bit more readable would be:

echo "<img src='imgdir/{$bannerimg}/>";
echo "<img src='imgdir/$bannerimg/>";

You can read all about variable parsing in the manual, the first syntax is the complex one and the second the simple. I prefer the complex one as the end of the variable is clearly defined and you can use it for complex expressions, not just simple variables.

Upvotes: 1

Sandeep Bansal
Sandeep Bansal

Reputation: 6394

You're doing it right but you can use the following just to keep it clean.

echo "<img src='imgdir/$bannerimg' />";

Upvotes: 1

Related Questions