Instead of using foreach I’d rather make the script to write each image in the second while statement. (Line 26)
When you’re using $file it might be undefined, so you should write it when it should be defined. If that doesn’t work, try to see if $file gets defined at all.
Also, when you view the page source, what does the <img src=""> say? That can tell you what PHP is defining $file as.