Solved

File Uploads

Posted on 2006-06-18
10
260 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
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
 
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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
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…
The viewer will learn how to count occurrences of each item in an array.
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.

739 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