note 114004 added to features.file-upload

From: Date: Sun, 29 Dec 2013 11:09:29 +0000
Subject: note 114004 added to features.file-upload
Groups: php.notes 
Request: Send a blank email to php-notes+get-198046@lists.php.net to get a copy of this message
You'd better check $_FILES structure and values throughly. The following code cannot cause any errors absolutely. Example: <?php header('Content-Type: text/plain; charset=utf-8'); try { // Undefined | Multiple Files | $_FILES Corruption Attack // If this request falls under any of them, treat it invalid. if ( !isset($_FILES['upfile']['error']) || is_array($_FILES['upfile']['error']) ) { throw new RuntimeException('Invalid parameters.'); } // Check $_FILES['upfile']['error'] value. switch ($_FILES['upfile']['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: throw new RuntimeException('No file sent.'); case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new RuntimeException('Exceeded filesize limit.'); default: throw new RuntimeException('Unknown errors.'); } // You should also check filesize here. if ($_FILES['upfile']['size'] > 1000000) { throw new RuntimeException('Exceeded filesize limit.'); } // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !! // Check MIME Type by yourself. $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === $ext = array_search( $finfo->file($_FILES['upfile']['tmp_name']), array( 'jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', ), true )) { throw new RuntimeException('Invalid file format.'); } // You should name it uniquely. // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !! // On this example, obtain safe unique name from its binary data. if (!move_uploaded_file( $_FILES['upfile']['tmp_name'], sprintf('./uploads/%s.%s', sha1_file($_FILES['upfile']['tmp_name']), $ext ) )) { throw new RuntimeException('Failed to move uploaded file.'); } echo 'File is uploaded successfully.'; } catch (RuntimeException $e) { echo $e->getMessage(); } ?> ---- Server IP: 72.52.91.14 Probable Submitter: 72.52.91.14 ---- Manual Page -- http://php.net/manual/en/features.file-upload.php Edit -- https://master.php.net/note/edit/114004 Del: integrated -- https://master.php.net/note/delete/114004/integrated Del: useless -- https://master.php.net/note/delete/114004/useless Del: bad code -- https://master.php.net/note/delete/114004/bad+code Del: spam -- https://master.php.net/note/delete/114004/spam Del: non-english -- https://master.php.net/note/delete/114004/non-english Del: in docs -- https://master.php.net/note/delete/114004/in+docs Del: other reasons-- https://master.php.net/note/delete/114004 Reject -- https://master.php.net/note/reject/114004 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#198046) next »