Question

Image Display from non web root folder

Asked by: highlawn

I have been reading up on file upload security and the guidance (see here: http://www.scanit.be/uploads/php-file-upload.pdf but also it appears elsewhere) is to do the following:
1. Keep uploaded files in a folder NOT accessible by the browser - i.e. out of your webroot.
2. Change the file names so that they are not the same as the uploaded file and not easily guessed

In my script I check that it is an image file (as that is what I am uploading) and I check sizes and the like but that is not enough. I do number 2 above as I have to keep them in a database attached to the members' profiles.

However, I am having some difficulty sorting out how exactly to do number 1.

When the image is uploaded it is stored in the file area, but when I want to display it, I don't just want to send the raw image. I want it to be resized to thumbnail and to also be part of a lightbox object so that when clicked it is accessible. It is all currently working with the directory within the webroot, but I can't get it to work if the directory is outside the webroot.

Presumably, this is because the browser cannot find the location (not in webroot) and so I can't use html to tell the browser how to treat it. So, I could use PHP to send the stream (imagejpeg for eg) to the browser, but I also want to be able to pass the resize parameters and the lightbox links.

Now, I could always hold copies of the images as thumbnails and remove the first issue, but I can't see quite how I can wrap the html around an image stream from PHP.

I thought about using a temporary file in the webroot - so picking it up from outside, creating a temp in a webroot folder and then using that for the html. It seems a lot of messing around.

So, first question is - is this necessary? Is the security chap correct here? Should the files be stored outside the webroot for security?

If so, then how best may I achieve the equivalent of the following code which uses a file in the webroot.

Many Thanks - and I hope I've explained that clearly!

For info my web root is under /srv/public/html/domain.com - which maps to domain.com in the browser. I currently have the files under domain.com/images - I was intending to put them under /var/www/images - /var not being accessible by the browser.

while ($img = mysql_fetch_array($gallery))                      // Get the images
        {
            $cap=stripslashes($img['caption']);                               // Image caption for lightbox
            $ttl=str_replace("'","",$img['title']);                                 // Gallery title to group images
            $imp="images/".$img['path'];                                         // image for html
            $is = img_resize("images/".$img['path'],90);                // make thumbnail
            $img ="<img src ='images/".$img['path']."'".$is.">";      // construct html for output
            $lightbox=" rel='lightbox[gal]' title='".$cap."'";              // lightbox parameters
            echo "<td width='25%'>";
            echo "<a href=\"$imp\" rel=\"lightbox[$ttl]\" title=\"$cap\">".$img."</a></td>";  // o/p to brw
            $nl++;                                                                         // four images per line
            if ($nl == 4) { echo "</tr><tr>"; }
        }

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-15 at 02:35:06ID24654957
Tags

HTML PHP

Topics

Web Images

,

Hypertext Markup Language (HTML)

,

PHP Scripting Language

Participating Experts
2
Points
250
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. incremental naming/numbering of images and thumbnails
    The code below uploads an image and generates a thumbnail. It works perfectly. (It's from a tutorial I'm working my way through.) Currently, the names for the image and thumbnail are given random names, such as "809abc8134nfnf98348875fcdfsdfef.jpg" and I would pref...
  2. How to Create a Vedio Thumbnails image in PHP
    How to create a vedio thumbnail image using php

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: spulePosted on 2009-08-15 at 03:22:17ID: 25104759

My opinion: Upload these files somewhere outside yout web root. When they are uploaded, your PHP script should check them. If they're really just images, move them inside your web root so that they are accessible. Otherwise, throw them away.

 

by: spulePosted on 2009-08-15 at 03:27:22ID: 25104769

For testing whether they are images, you can:

  1. check and/or correct their extension
     
  2. try loading them with a graphics library like libgd -- if it succeeds, it's an image and you don't have to fear it 
Or you don't have to check the file, but you must in some way make sure that your server will not try to execute it as a PHP or SQL script or something like that.

 

by: highlawnPosted on 2009-08-15 at 04:24:41ID: 25104952

OK - let me check out just what libgd is - not heard of that and I'll get back to it. Many Thanks. I'm just trying to ensure that no-one injects php/other executables into my files and if they did then they couldn't use it.

If that makes sense... Probably could have written that better!

Cheers. Laters

 

by: highlawnPosted on 2009-08-15 at 05:13:15ID: 25105108

When you say "try loading then with  <snip> libgd" - how would you actually do that?

 

by: spulePosted on 2009-08-15 at 05:26:37ID: 25105152

LibGD is a graphics library that you can use from PHP. It allows you to create and modify images. You can use e. g.:

$img = @imagecreatefromjpeg("filename.jpg"); //note that this is only for JPEG -- but you could load the file into a string and then open it using imagecreatefromstring($data)

if(!$img){
   //image loading has failed, we can throw it away
}else{
   //image OK, you can move it inside your web root
}

See the manual: http://cz2.php.net/manual/en/ref.image.php

 

by: Slick812Posted on 2009-08-15 at 11:45:12ID: 25106429

Hello highlawn, I agree with spule, about the suggestion to first place uploaded files in a non-web accessible folder , ONLY for testing, and or manipulation  (thumbnails, watermarks), and then place the checked files, and or thumbs, in a web accessible folder. BUT you may have other concernes for having non accessible image flies. here is some code I have used to get images in non accessible folders to a web page -
first is the code for the imggif.php

<?php
$fname = (empty($_GET['ifn'])) ? 'hili' : $_GET['ifn'];
//the file path below can be any that the PHP can access
if (!file_exists('home/images3/'.$fname.'.gif')) $fname = 'hili';
//be sure to have an error image
header('Content-Type: image/gif'); 
// warning, you MUST have the right header type, this is ONLY for GIF
//images, but you can code it so it changes the header type
readfile('home/images3/'.$fname.'.gif');
?>
 
- - - - - -  
-below code to get an Image in html
<img src="imggif.php?ifn=fluer2">

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: highlawnPosted on 2009-08-15 at 23:15:32ID: 25107959

OK, many thanks I will give this a go. So, effectively, what we are saying is that the libgd "test" will prove conclusively that the image is a bona fide image with no injected code whereas the construct

list($width, $height, $type, $attr) = getimagesize($_FILES['imgfile']['tmp_name']);

would return good even if code were in it?

As a consequence if we get the libgd seal of approval from any of the following (depending on image type)

$imgjpg = @imagecreatefromjpeg("filename.jpg");
$imggif = @imagecreatefromgif("filename.gif");
$imgpngg = @imagecreatefrompng("filename.png");

then we have no worries and it can be loaded into our web directory safely - thus obviating the need for any permanent off web storage?

Let's just hope my php has libgd compliled!

 

by: Slick812Posted on 2009-08-16 at 08:46:13ID: 25109315

OK, you seem to want an "ultimate" guarantee that all security risks are gone, but you can not ever get rid of all security risks. I have to consider security with my web sites. And I do some things, BUT, for me, some things (methods, checks) are just TOO MUCH.
I had time today to read more of the php-file-upload.pdf  that you reference above. In it he says -
"Checking that the file is an image is not enough to guarantee that it is not a PHP script"
and he uses the  getimagesize( )  for his image test, which I think is also a part of the php GD image lib. and may be just as good as the  imagecreatefromjpeg( ) test. . . What I would ask myself is, do I have information on my site (financial passwords, credit card numbers, bank account log-in) that a hacker would go to the considerable trouble of doing the perl,  php, shell, and other hacks that you are trying to prevent. If not, then you may only need moderate safeguards. All web servers have their own security methods set up, some will not allow the perl, and php hacks that he talks about.
For me, if I have concerns about Image security, I just use the GD functions to copy the upload Image to another image, and save that Image as the one that will be available for user viewing. This is also useful for User uploads from those that take those very Large digital camera pics, and have no Idea how to reduce them to a web page view size, and just upload a 10 mega-pixel image for a 100x100 user pic.

 

by: highlawnPosted on 2009-08-16 at 09:12:33ID: 25109392

Ultimate guarantee would be cool - but I'm realistic enough to understand that there is no such thing. I'm pretty new at this game so I just wanted to check I'd interpreted what you two had said.

I do take your point regarding numpty users uploading huge images though :(

I think also that changing the file name is a good idea as I'm loading user images against profiles and just to keep track ot the images, I call the file profile_id."-".image_number.".".xyz so things end up like 2187-17.xyz
so are pretty unguessable.

Thanks for assistance. I'll split the points.

 

by: highlawnPosted on 2009-08-16 at 09:14:44ID: 31616093

As slick says - on security issues - you can only ever get a partial answer...

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...