What Is the Most Secure Method for Uploading a File

What is the most secure method for uploading a file?

The best solution, IMHO, is to put the directory containing the uploaded files outside of the "web" environment and use a script to make them downloadable. In this way, even if somebody uploads a script it can not be executed by calling it from the browser and you don't have to check the type of the uploaded file.

What is the Most Secure php file upload method that can handle all filetypes?

Checking the filename extension is recommended, although be aware that the mime type can easily be spoofed, so this is not a good check for security.

What you have so far is good, my additional tips would be:

  • Virus scan all uploads - this is more to protect other users of your application rather than your server.
  • Store images outside of the web root totally, and use an approach such as this one to proxy the files to be served. This has the advantage that any additional permission checks can be carried out in code (so Bob can't download Alice's files) and as the files are accessed as data, there is no chance of execution.
  • Serve files with the X-Content-Type-Options: nosniff header to prevent any XSS attacks via IE's mime sniffing.
  • Store images using server generated names. For example, you could name each file after the primary key of its database entry. This will mitigate against any directory traversal attacks (like this one) and if a user does manage to upload something malicious they will be less likely to find it on the server.
  • Load all images into an image library and resave them to ensure they don't have any exploits embedded for popular browsers.
  • Have some sort of manual monitoring system in place to watch for any uploaded illegal content.
  • Protect your form against CSRF.

What is the most secure method to upload image file to server with PHP?

Here you go, this covers the basic ideas of what you want to do:

<?php
$allowedTypes = array("image/jpg", "image/jpeg", "image/png");
$maxSize = 3 * 1024 * 1024; // 3Mb

$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];

// check if there was an error
if ($_FILES["file"]["error"] > 0)
{
die($_FILES["file"]["error"]);
}

// check if the filetype is valid
if (!in_array($fileType, $allowedTypes))
{
die("Invalid file type: $fileType");
}

// check if the size doesn't exceed the limitations
if ($fileSize > $maxSize)
{
die("The file was too big: $fileSize");
}

$name = $_FILES["file"]["name"];
$tmpfile = $_FILES["file"]["tmp_name"];

// check if the filename is valid
if (preg_match("/[\w-]+\.(jpg|jpeg|png)$/", $name) != 1)
{
die("Invalid file name: $name");
}

// create unique name if needed

$path = "/var/www/images/" . $name;

move_uploaded_file($tmpfile, $path);

// add the filepath to mysql
mysql_connect("localhost", "username", "password");
mysql_select_db("imagedb");
mysql_query("INSERT INTO images (Location, Size) VALUES ('$path', '$size');");
?>

This is meant to show how it could be done.

Best and Secure way to upload file using php

This question is already asked here.
but you can use my own code for same it is simple and secure.

function hc_upload($f,$username='',$verify_type=1,$size=2048)
{
$f=$_FILES[$f];
$file_name=strtolower($f['name']);
$file_type=strtolower($f['type']);
$file_size=strtolower($f['size']);
$file_extenstion =end(explode('.',$file_name));
$file_extenstion2=strtolower(pathinfo(basename($file_name),PATHINFO_EXTENSION));

if($file_extenstion2!=$file_extenstion){
$err["error"]=true;
$err["message"]="Invalid file extension.";
return $err;
}
if($file_size > $size*1000){
$err["error"]=true;
$err["message"]="File is too large.";
return $err;
}

$ext_verify=0;
if(gettype($verify_type)!='array')
{
$verify_type=(string)$verify_type;
if((strpos($verify_type,"1") > -1 || $verify_type=="*") && $ext_verify==0)
{
$mimes['ext']=array("jpg","jpeg","gif","png");
$mimes['mime']=array("image/jpg","image/jpeg","image/gif","image/png");
if(in_array($file_extenstion,$mimes['ext']) && in_array($file_type,$mimes['mime'])){$ext_verify=1;}
}
if((strpos($verify_type,"2") > -1 || $verify_type=="*") && $ext_verify==0)
{
$mimes['ext']=array("doc","docx","pdf","xls","xlsx","ppt","pptx");
if(in_array($file_extenstion,$mimes['ext'])){$ext_verify=1;}
}

if((strpos($verify_type,"3") > -1 || $verify_type=="*") && $ext_verify==0)
{
$mimes['ext']=array("mp3","wav","weba","3gp","mp4","mov","mpeg","avi");
$mimes['mime']=array("audio/mpeg","audio/wav","audio/webm","audio/3gpp","video/3gpp","video/mp4","video/quicktime","video/mpeg","video/x-msvideo");
if(in_array($file_extenstion,$mimes['ext']) && in_array($file_type,$mimes['mime'])){$ext_verify=1;}
}
}
else
{
if(array_key_exists("mime",$verify_type) && array_key_exists("ext",$verify_type)){
if(in_array($file_extenstion,$verify_type['ext']) && in_array($file_type,$verify_type['mime'])){$ext_verify=1;}
}
elseif(array_key_exists("ext",$verify_type)){
if(in_array($file_extenstion,$verify_type['ext'])){$ext_verify=1;}
}
elseif(array_key_exists("mime",$verify_type)){
if(in_array($file_type,$verify_type['mime'])){$ext_verify=1;}
}
else{
if(in_array($file_extenstion,$verify_type)){$ext_verify=1;}
}
}

if($ext_verify==0){
$err["error"]=true;
$err["message"]="Seems your file is not valid";
return $err;
}

$upload_dir='upload/'.$username.'/';
if(!is_dir($upload_dir)){
if(!mkdir($upload_dir,0777,true)){
$err["error"]=true;
$err["message"]="Unknown error, kindly contact admin";
return $err;
}
}

$upload_file=$upload_dir.sha1_file($f['tmp_name']);
if(!file_exists($upload_file)){
if(!move_uploaded_file($f['tmp_name'], $upload_file)){
$err["error"]=true;
$err["message"]="Unknown error, kindly contact admin";
return $err;
}
}

$err["error"]=true;
$err["message"]="SUCCESS";
$err["dir"]=$upload_file;
return $err;
}

And HTML Sample Code is

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

So simply call this function in php

hc_upload('fileToUpload','',123)
you can create folder for each username by giving value two second parameter
and third parameter two check for file is image or document or audio/video media and also can pass array of extensions for manually check

Is it safe in terms of security when uploading files to amazon s3 via http not the https?

Its not safe, and its not a good practice. What's more you should enforce any uploads to S3 to be https, which is good practice as explained in Enforce encryption of data in transit:

You can use HTTPS (TLS) to help prevent potential attackers from eavesdropping on or manipulating network traffic using person-in-the-middle or similar attacks. You should allow only encrypted connections over HTTPS (TLS) using the aws:SecureTransport condition on Amazon S3 bucket policies.

Is this file uploading method secure via PHP?

Randomly-generated safe filenames are definitely a good thing. However if you allowing the file extension through to the webroot you'll still need to ensure that the extension is something that won't cause any problems on the server, such as .php (OK, PHP handling should be disabled in the web server for upload directories, but still). There are also problems if you are on a Windows server, where trailing dots and spaces will confuse the filesystem; make sure you lock down the extension to a few ‘known good’ values.

Unfortunately the ['type'] property cannot be relied on at all. Some browsers won't fill a content-type in, others will put the wrong type because their OSes are set up badly (an infamously unhelpful one is that IE on Windows by default calls JPEG image/pjpeg), some will always say application/octet-stream or even text/plain.

Even the ['name'] property is unreliable; apart from browsers lying or obfuscating the value, there's always the chance a given type will have an unexpected file extension on that particular machine. Or, for Mac and Linux clients, it's entirely possible an uploaded file won't have an extension at all (or may even have the wrong extension for the type the OS sees it as).

So yeah, this is all a bit of a mess. Whilst sniffing for type from the Content-Type submission or filename extension can be useful to guess what default type a file should be, it's entirely unreliable, so it's a good thing to provide a manual method to choose the type of a file in addition. Alternatively, if you are serving the uploaded files as attachments (eg. through a PHP script setting Content-Disposition: attachment), you can often get away with just calling everything application/octet-stream and letting the user sort it out when they save it.

If you're not serving as an attachment, you may have a security problem. IE will happily sniff many filetypes you serve it for <html> tags and treat those files as HTML even if you tell it they're something else. Then it can display them inline in the browser, and lets them inject script into your security context. If you have anything significant in your security context, such as user accounts and cookies, that's a cross-site-scripting security hole. The workarounds for this are serving as attachment and/or serving from a different hostname that is not in your main site's security context (typically, a subdomain is used).

Allowing users you don't completely trust to upload files to your server turns out to actually be a much more difficult task than the trivial example code in PHP tutorials would lead you to believe. :-(



Related Topics



Leave a reply



Submit