Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Limit the types of files uploaded 1

Status
Not open for further replies.

nat1967

Technical User
Feb 13, 2001
287
US
Hi everyone,

Here's a newbie question for ya.

How can I limit the types of files a person can upload to my server? I only want the user to upload .gif, .jpg, or .bmp files.

here is the php i'm using:

if (is_uploaded_file($file_array['tmp_name'])) {
move_uploaded_file($file_array['tmp_name'],
"$file_dir/$rnd-$file_array[name]") or die ("Couldnt copy");
print &quot;file was moved!<br><br>&quot;;
}
}

works great but it allows any file to be uploaded. i have looked at PHP.net and searched through Tek-Tips. I am just missing what I need.

Can anyone point me in the right direction?

Thanks in advance..


Have A Great Day!!!, [bigglasses]

Nathan
Software Testing Lead
 
You can easily rename a file (such as a .exe) to a .jpg, and the mime type identifier passed by the browser will be *wrong*.

Instead, trust a Unix shell tool called &quot;file&quot;.

<?

$allowed=array(
'PHP script text',
'ASCII text',
'JPEG image data');

$fname=escapeshellarg($_FILE[varname][tmp_name]);
$type=`file $fname`;
foreach($allowed as $allow)
if (stristr($type, $allow)!==false)
{
// It's an acceptable type - move on!
}

?>

the &quot;file&quot; shell command will accept whatever type of file and completely disregards the name of the file, mime-type, or anything else. This provides a much greater degree of trustability.



Bastien

Any one have a techie job in Toronto, I need to work...being laid off sucks!
 
Hi Bastien,

I have been trying and trying to get this to work. it makes so much sense but ... since i am new to php... i am having so many problems.

here is my code:

$allowed=array(
'PHP script text',
'ASCII text',
'JPEG image data');

$fname=escapeshellarg($_FILE[varname][tmp_name]);
$type=`file $fname`;
foreach($allowed as $allow)
if (stristr($type, $allow)!==false)

{
// It's an acceptable type - move on!
foreach($_FILES as $file_name => $file_array) {
$rnd = sprintf(&quot;%08d&quot;, floor(rand(0,100000000)));
print &quot;path: &quot;.$file_array['tmp_name'].&quot;<br>\n&quot;;
print &quot;name: &quot;.$file_array['name'].&quot;<br>\n&quot;;
print &quot;type: &quot;.$file_array['type'].&quot;<br>\n&quot;;
print &quot;size: &quot;.$file_array['size'].&quot;<br>\n&quot;;
print &quot;Confirmation Number: &quot;.$rnd.&quot;<br>\n&quot;;
}
}

nothing happens. the file never uploads even if it should be acceptable. (jpg file)

what am i doing wrong? :-(

any help or suggestions would be greatly appreciated.

Have A Great Day!!!, [bigglasses]

Nathan
Software Testing Lead
 
What does your HTML form tag look like? It should specify the &quot;method&quot; attribute of &quot;post&quot; and a &quot;enctype&quot; of &quot;multipart/form-data&quot; else the files will not be uploaded.

Also, to more easily examine the values in $_FILES, I recommend you use the recursive print function, print_r().
Want the best answers? Ask the best questions: TANSTAAFL!!
 
hi sleipnir214,

<form action=&quot;testing.php&quot; enctype=&quot;multipart/form-data&quot; method=&quot;post&quot;>
File to Upload: <input type=&quot;file&quot; name=&quot;fileupload&quot;><br><br>
<input type=&quot;submit&quot; value=&quot;upload&quot;>

all i want to do is limit what types of files are uploaded. i only want the user to upload jpg, bmp, or tif formats. all others should be rejected. it just shouldnt be this hard. i have read pages and pages of articles at PHP.net and other websites. i just dont see something that fits what i am doing.

if i was doing this in VB, it would have been easy but alas... i'm not.

can anyone give me an example to look at? i am sure if i saw something actually working the way i need it, all the pieces would start to fall into place and i would understand how the different PHP global functions work. it seems as if there will be multiple parts from $_Files globals to is_file(). i just cant seem to piece it together.

---->new to this and very frustrated.... :-(

Have A Great Day!!!, [bigglasses]

Nathan
Software Testing Lead
 
On what platform are you running PHP?

Bastien's solution requires that you run PHP on a unix-type OS, because the external command &quot;file&quot; that you are running in the line which reads &quot;$type=`file $fname`;&quot; is only going to be available on a unix-type OS.



Want the best answers? Ask the best questions: TANSTAAFL!!
 
the webhosting company uses UNIX for their server. is this the best approach or should i be using another?

Have A Great Day!!!, [bigglasses]

Nathan
Software Testing Lead
 
HI,

my problem lies well before $type. to be honest, i have no clue how to put all this together.

here is what i currently use to upload the files. this took some doing but i finally got it figured out.

'****begin form1****

<form action=&quot;ordersubmit.php&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;>

<input name=&quot;fileupload&quot; type=&quot;file&quot;>
<strong>Step 3: Click the &quot;Upload&quot; button to send your image to SkyLinePrints.com for processing.</strong></p>
<p align=&quot;left&quot;>
<center><input name=&quot;frmSubmit&quot; type=&quot;submit&quot; id=&quot;frmSubmit&quot; value=&quot;upload&quot;></center>
 </p>
</form>

'*****begin form2 (ordersubmit.php)*****

<html>
<head>
<title>Order Submited for Custom Product!</title>
<meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot;>
<script language=&quot;JavaScript&quot; type=&quot;text/JavaScript&quot;>
<!--
function MM_reloadPage(init) { //reloads the window if Nav4 resized
if (init==true) with (navigator) {if ((appName==&quot;Netscape&quot;)&&(parseInt(appVersion)==4)) {
document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
//-->
</script>
</head>
<?php

$file_dir = &quot;/local/vips/home0/nathan/skylineprints.com/form/email_attachments/attachments&quot;;

foreach($_FILES as $file_name => $file_array) {
$rnd = sprintf(&quot;%08d&quot;, floor(rand(0,100000000)));


if (is_uploaded_file($file_array['tmp_name'])) {
move_uploaded_file($file_array['tmp_name'],
&quot;$file_dir/$rnd-$file_array[name]&quot;) or die (&quot;Couldnt copy&quot;);

}
}

?>
<body>
<strong>ORDER
CONFIRMATION: <?php echo $rnd; ?></strong></td>
<td width=&quot;124&quot; height=&quot;37&quot; valign=&quot;top&quot;></td>
</tr>
</body>
</html>
'***end****

At the present, this allows all file types to be uploaded. all i want to do is allow jpg, bmp, or tif extensions to be uploaded.

i have tried to implement Bastien's suggestion but i just dont understand how it comes into play or where to put it. I am sure at some point this will all make sense but right now, it doesnt. :-(

can you show me how to implement bastien's suggestion? i would be very very grateful if you or someone could show me.

Have A Great Day!!!, [bigglasses]

Nathan
Software Testing Lead
 
Bastien's suggestion makes use of standard unix app that can analyze a file and determine what type of file it is, regardless of file extention (in unix, file extensions don't mean as much as they do in Win32). His suggestion prevents someone from uploading a PDF that has been renamed with a &quot;.jpg&quot; extension.

Whether or not this is necessary depends on who is going to be uploading files. If you can trust your users not to mess with your site, then just check the extension on the files.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
I think what nathan really wants is more direction on how the code flows rather than how the actual function is to work(though I am sure he wants to figure that out too)

One method, Nathan, that I use for a lot of pages is to break the pages into functions and then use if/then control structures to direct the flow of the code. For this page I would suggest something like this:

Code:
if ($_POST['submit']){

    //submit button pressed and file is uploaded
    //call the [b]process_file[/b] function to confirm the
    //upload and validate the file type
    process_file();

}else{

    //no submit button, so the page is opened with the form
    //code to allow the user to choose the file to upload
    show_form();
}
//function section
function show_form()
{
   //html [and php] code as needed to show the form

}
//
function process_file()
{
   //php code to process the uploaded file
   $allowed=array( 
            'PHP script text', 
            'ASCII text', 
            'JPEG image data'); 

   $fname=escapeshellarg($_FILE[varname][tmp_name]); 
   $type=`file $fname`; 
   foreach($allowed as $allow) 
   if (stristr($type, $allow)!==false) 
   { 
       // It's an acceptable type - move on! 
       //call the confirm upload function
       confirm_upload();

    }else{

       //file is not acceptable - wrong file type
       //so call the rejected_file function
       rejected_file();

    }

}
function confirm_upload()
{
   //html and php code to confirm upload to user
   echo &quot;<html><body><h1>Upload accepted</h1></body></html>&quot;;
}
function reject_upload()
{
   //html and php code to confirm upload to user
   echo &quot;<html><body><h1>Upload rejected. Wrong file type</h1></body></html>&quot;;
}

Note: you will need to pass some variables around the functions to pass the required information like file name



Bastien

Any one have a techie job in Toronto, I need to work...being laid off sucks!
 
Bastien,

you are absolutely correct. it is the code flow that i am having trouble with. i have been programming VB and VBA for years and just now getting into PHP. The concepts you and sleipnir214 have presented make sense. it is just getting things in the right order and making the right calls.

i believe sleipnir214 is trying to &quot;teach a man to fish&quot; instead of just showing me how to do the code. i understand the approach and use it often myself. unfortuately, i have been reading and trying for over a month. at some point in the learning curve, you have to &quot;show a man how to fish&quot;. everyday i pick up more and more of the PHP logic. Soon, I will be flying along.

I will take your information, Bastien, and work with it. Now that i see your function laid out, i see that i was making it more complex than i needed. i am assuming the PHP has a &quot;built-in&quot; function that does the uploads and then we are just checking and moving the uploads. if this is correct, then it explains why i havent been able to get my mind around this. i keep looking for the upload code. In VB, i have to call the FileSystemObject. i guess thats not needed over here....

Thanks again,

Have A Great Day!!!, [bigglasses]

Nathan
Software Testing Lead
 
here is some code to handle the uploads. hope this may lead you in the right direction
Code:
function uploadFile() {
        // import form data into local function
        global $ulFile, $ulFile_name, $ulFile_type;
        
        // check for form data
        if (isset($ulFile) && $ulFile_name) {
                // check uploaded file is one of supported types
                if ($ulFile_type == &quot;image/png&quot; ||
                                $ulFile_type == &quot;image/jpeg&quot; ||
                                $ulFile_type == &quot;image/pjpeg&quot;) { 
                        
                        $fn = getUniqueName($ulFile_name); // generate a unique file name
        
                        /* move file to the photo directory. Notice we now use move_uploaded_file
                         * instead of copy. It includes a check to make sure the file came from
                         * the right source, making it more secure
                        */
                        if (move_uploaded_file($ulFile, PHOT_DIR.&quot;/$fn&quot;)) {
                                print &quot;<p>$ulFile_name successfully uploaded</p>\n&quot;;
                                saveThumbnail($fn); // generate tumbnail image
                        } else {
                                print &quot;<p>Oops! Couldn't upload $ulFile_name</p>\n&quot;;
                                unlink($ulFile); // remove temporary file
                        }
                } else {
                        print &quot;<p>Sorry, file type $ulFile_type not supported. Try a JPEG or PNG image.</p>\n&quot;;
                        unlink($ulFile); // remove temporary file
                }
        }
}
--------------------------------------------------------------------------------

and the form code 

--------------------------------------------------------------------------------
<?php
        /* album.php - version 3
         * .net magazine ([URL unfurl="true"]www.netmag.co.uk),[/URL] issue 83
         * Matt Kynaston, 2001
         * Distributed under the GNU Public License - [URL unfurl="true"]www.gnu.org/copyleft/gpl.html[/URL]
         *
         * The PHP Photo Album displays the contents of a thumbnail directory,
         * linked to full size images in the photo directory. It gives the user
         * the opportunity to upload their own photos to the album, automatically
         * creating tumbnails.
         *
         * Requires PHP4 with the GD and ZLIB extensions installed (php_gd.dll and php_zlib.dll
         * on Windows). These are available from the full download of PHP at [URL unfurl="true"]www.php.net[/URL]
         * Modify your php.ini file (C:\WINDOWS\PHP.INI in Windows systems) to point at them
        */
         
        /* constant declaration section
         * change these to modify the album directories or image sizes
        */
        define(&quot;NUM_COLS&quot;, 4); // number of columns in table
        define(&quot;PHOT_DIR&quot;, &quot;photos&quot;); // photo directory, relative to this page
        define(&quot;THUMB_DIR&quot;, &quot;thumbs&quot;); // thumbnail directory, relative to this page
        define(&quot;MAX_XY&quot;, 150); // maximum width or height of thumbnail image

        /* all the functions used on this page have been split off into a 
         * seperate file. The include statement below makes them available to this
         * page.
        */
        include(&quot;album_functions.php&quot;); 

?>
<html>
<head>
<title>Photo Album</title>
<link href=&quot;album.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;>
</head>

<body bgcolor=&quot;#FFFFFF&quot; text=&quot;#000000&quot;>
<h1>PHP Photo Album</h1>
<h3>(final version)</h3>

<?php uploadFile() ?>

<form name=&quot;form1&quot; method=&quot;post&quot; action=&quot;<?php print $PHP_SELF?>&quot; enctype=&quot;multipart/form-data&quot;>
  <p>Add your own image to the album:<br>
    <input type=&quot;file&quot; name=&quot;ulFile&quot;>
        <input type=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot; value=&quot;512000&quot;>
  </p>
  <p>
    <input type=&quot;submit&quot; name=&quot;Submit&quot; value=&quot;Upload&quot;>
  </p>
</form>

<p> </p>

<?php makeAlbumTable(); ?>

</body>
</html>

Bastien

Any one have a techie job in Toronto, I need to work...being laid off sucks!
 
Bastien,

you deserve more stars than i can give you in this forum. i will take a look and see what happens but my gut feeling is, you have shown me how to fish.

i will let you know how it goes.

Thank you!!


Have A Great Day!!!, [bigglasses]

Nathan
Software Testing Lead
 
in my core php book (for v5) it mentions a function called exif_imagetype whichif you give it a file it looks at the header and determines what the type is. Give that a go it will at the least tell you jpg and gif.

If you want to get up to speed with php core php is a good book, a little long but it does have good examples
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top