Created
March 31, 2011 12:03
-
-
Save greut/896241 to your computer and use it in GitHub Desktop.
A safe(r) upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (isset($_FILES['file'])) { | |
$file = $_FILES['file']; | |
// what the browser says | |
$type = $file['type']; | |
// what the file ready is | |
$finfo = new finfo(FILEINFO_MIME); | |
$file['mimetype'] = $finfo->file($file['tmp_name']); | |
unlink($file['tmp_name']); | |
} | |
?> | |
<!DOCTYPE html> | |
<html> | |
<meta charset=utf-8> | |
<title>Safe(r) upload</title> | |
<?php if (isset($file)): ?> | |
<pre><?php print_r($file) ?></pre> | |
<?php endif ?> | |
<form method=POST action="" enctype="multipart/form-data"> | |
<input type=file name=file> | |
<input type=submit> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import magic | |
from webob import Request, Response | |
from wsgiref.simple_server import make_server | |
def application(environ, start_response): | |
req = Request(environ, charset='utf-8') | |
if req.POST: | |
file = req.POST.get('file') | |
data = '''<pre> | |
filename: %s | |
type: %s | |
mimetype: %s | |
</pre>''' | |
data = data % (file.filename, | |
file.type, | |
magic.from_buffer(file.file.read(1024), mime=True)) | |
file.file.seek(0) | |
else: | |
data = '' | |
resp = Response( | |
''' | |
<!DOCTYPE html> | |
<html> | |
<meta charset=utf-8> | |
<title>Safe(r) upload</title> | |
%s | |
<form method=POST action="" enctype="multipart/form-data"> | |
<input type=file name=file> | |
<input type=submit> | |
</form> | |
''' % (data) | |
) | |
return resp(environ, start_response) | |
if __name__ == '__main__': | |
httpd = make_server('', 8000, application) | |
try: | |
httpd.serve_forever() | |
except KeyboardInterrupt: | |
print '^C' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment