Solved

File Uploads

Posted on 2006-06-18
10
255 Views
Last Modified: 2008-03-10
Hi!

I'm wondering what's the best way to check/restrict file types of uploaded files via POST method server-side...

Could use $_FILES['userfile']['type'] but this is passed from client-side and cannot be trusted...
0
Comment
Question by:Julian Matz
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 10

Accepted Solution

by:
Khanh Doan earned 500 total points
ID: 16931973
<?php
$song['song_url'] = chop(trim($_POST['url']));

$lastdot = strrpos($song['song_url'], '.');
$filetype = strtoupper(substr($song['song_url'], $lastdot+1));

$allow_file = array('MP3', 'AVI', 'MPG', 'WMA'); //Define your file types that you allow user upload

(empty($song['song_url'])) ? $err = 'Empty url' : '';
(!in_array($filetype, $allow_file)) ? $err .= '<br>Not support' : '';

if (empty($err))
{
      $lastdot = strrpos($song['song_url'], '.');
      $filetype = strtoupper(substr($song['song_url'], $lastdot+1));
      $lastx = strrpos($song['song_url'], '/');
      $filename = 'music/' . substr($song['song_url'] ,$lastx+1);
      $filename = str_replace('%20', '_', $filename);
      $filename = str_replace(' ', '_', $filename);
      $filename = str_replace('&amp;', '_', $filename);
      $filename = str_replace('&', '_', $filename);
      $filename = str_replace(';', '_', $filename);
      $tt = 1; $i = 1;

      while ($tt == 1)
      {
            (file_exists($filename)) ? $filename = 'music/' . substr($song['song_url'], $lastx+1) : $tt = 0;
            $i++;
      }

      $file = @fopen($filename, 'w');
      $f = @fopen($song['song_url'], 'r');

      while (!@feof($f))
      {
            @fwrite($file, fread($f, 1024));
      }

      @fclose($f); @fclose($file);
}
else
{
      echo $err;
}
?>

this is my code I use for uploading music file.
Goodluck.
Bonmat86
0
 
LVL 12

Expert Comment

by:str_kani
ID: 16932113
I see the esiest and way is to restirct using javascript... so that the user can be prompted well before the upload starts (i.e the form submits.)
0
 
LVL 12

Expert Comment

by:str_kani
ID: 16932118
You can use the following if you don't know how to do this using javascript...
http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21495872.html
function validate(obj) {
  var not_allowed = new Array("asp", "htm", "html", "js", "vbs");
  var reg = new RegExp("\.("+not_allowed.join("|")+")", "i");
  if(reg.test(obj.File1.value)) {
    alert("That file extension is not allowed.");
    return false;
  } else {
    //Don't use document.all, find the correct form path to your button.
    document.yourform.yourbutton.disabled = true;
    return true;
  }
}
0
 
LVL 1

Expert Comment

by:FunnyMan
ID: 16933488
Javascript's all well and good, but make sure you validate it on the server end as well.  Some poeple have JS turned off, and there's even a chance that someone will bypass the JS intentionally, if they can do something that's normally not allowed by uploading a particular file type.
-FM
0
 
LVL 21

Author Comment

by:Julian Matz
ID: 16980073
No, I cannot rely rely on JS for security...

bonmat86, can you explain what you're doing there when opening the file for reading and writing?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 10

Expert Comment

by:Khanh Doan
ID: 16980789
when you can want to read or write data from/to file, first of all, you have to open it. $f = @fopen($song['song_url'], 'r'); will open the file you want to upload with "read" mode and $file = @fopen($filename, 'w'); will create a file in your host for writing.

while (!@feof($f))
     {
          @fwrite($file, fread($f, 1024));
     }

The loop while will check the current pointer that point to the data in the file is at the end of file or not. While it's not at the end of file, we use fwrite($file, fread($f, 1024)); to read data from file in local and then write it to the file in your host. The sign @ will ignore any error that appear when upload the file.
After upload the file, you have to close it by fclose() function. You can come to PHP Manual for more information (http://www.php.net/manual/en/). Sorry for my bad english.

Bonmat86.
0
 
LVL 21

Author Comment

by:Julian Matz
ID: 16980818
Thanks, bonmat86. I know about reading and writing to/from files and all that, but I was wondering why you were doing it :)

I just use the move_uploaded_file() function to save the uploaded file to a certain location...

You showed how to check the extension of the file, but is there any way to actually check whether the extension might be fake or real?
0
 
LVL 10

Expert Comment

by:Khanh Doan
ID: 16980837
I'm not sure about checking the ext is real or not. I just base on the file name and check it.
When i wrote code above, i didn't know about move_upload_file() function :p.

Bonmat86.
0
 
LVL 21

Author Comment

by:Julian Matz
ID: 16980993
Ok, no problem... The upload function is in a password protected admin backend anyway, so it wouldn't be of any benefit to admins to upload fake files :)

Ya, move_uploaded_file() seems like a handy function...
Another handy function, for added security is this one:
http://php.net/manual/en/function.is-uploaded-file.php
0
 
LVL 10

Expert Comment

by:Khanh Doan
ID: 16981023
It's good rite ?
I'll try it. Thanks

Bonmat86.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now