• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 273
  • Last Modified:

File Uploads

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
Julian Matz
Asked:
Julian Matz
  • 4
  • 3
  • 2
  • +1
1 Solution
 
Khanh DoanSenior DeveloperCommented:
<?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
 
str_kaniCommented:
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
 
str_kaniCommented:
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
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
FunnyManCommented:
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
 
Julian MatzJoint ChairpersonAuthor Commented:
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
 
Khanh DoanSenior DeveloperCommented:
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
 
Julian MatzJoint ChairpersonAuthor Commented:
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
 
Khanh DoanSenior DeveloperCommented:
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
 
Julian MatzJoint ChairpersonAuthor Commented:
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
 
Khanh DoanSenior DeveloperCommented:
It's good rite ?
I'll try it. Thanks

Bonmat86.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now