Solved

File Uploads

Posted on 2006-06-18
10
254 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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Creating a slider 12 35
Wordpress update causing pages to crash 1 21
SQL inner join confusion 15 23
PHP JSON Clean up 5 11
Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
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…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

743 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

14 Experts available now in Live!

Get 1:1 Help Now