note 85949 added to function.move-uploaded-file

From: Date: Fri, 26 Sep 2008 00:34:44 +0000
Subject: note 85949 added to function.move-uploaded-file
Groups: php.notes 
Request: Send a blank email to php-notes+get-144719@lists.php.net to get a copy of this message
Here's a function I wrote to take care of business. <?php # Written by Sean Nall <all.marx {at} gmail> # and placed into the public domain. # @function upload_file # # @param $field string the name of the file upload form field # @param $dirPath string the relative path to which to store the file (no trailing slash) # @param $maxSize int the maximum size of the file # @param $allowed array an array containing all the "allowed" file mime-types # # @return mixed the files' stored path on success, false on failure. function upload_file($field = '', $dirPath = '', $maxSize = 100000, $allowed = array()) { foreach ($_FILES[$field] as $key => $val) $$key = $val; if ((!is_uploaded_file($tmp_name)) || ($error != 0) || ($size == 0) || ($size > $maxSize)) return false; // file failed basic validation checks if ((is_array($allowed)) && (!empty($allowed))) if (!in_array($type, $allowed)) return false; // file is not an allowed type do $path = $dirPath . DIRECTORY_SEPARATOR . rand(1, 9999) . strtolower(basename($name)); while (file_exists($path)); if (move_uploaded_file($tmp_name, $path)) return $path; return false; } ?> DEMO: <?php if (array_key_exists('submit', $_POST)) // form has been submitted { if ($filepath = upload_file('music_upload', 'music_files', 700000, array('audio/mpeg','audio/wav'))) echo 'File uploaded to ' . $filepath; else echo 'An error occurred uploading the file... please try again.'; } echo ' <form method="post" action="' .$_SERVER['PHP_SELF']. '" enctype="multipart/form-data"> <input type="file" name="music_upload" id="music_upload" /> <input type="submit" name="submit" value="submit" /> </form> '; print_r($_FILES); // for debug purposes ?> ---- Server IP: 69.147.83.197 Probable Submitter: 71.189.190.163 ---- Manual Page -- http://www.php.net/manual/en/function.move-uploaded-file.php Edit -- https://master.php.net/note/edit/85949 Del: integrated -- https://master.php.net/note/delete/85949/integrated Del: useless -- https://master.php.net/note/delete/85949/useless Del: bad code -- https://master.php.net/note/delete/85949/bad+code Del: spam -- https://master.php.net/note/delete/85949/spam Del: non-english -- https://master.php.net/note/delete/85949/non-english Del: in docs -- https://master.php.net/note/delete/85949/in+docs Del: other reasons-- https://master.php.net/note/delete/85949 Reject -- https://master.php.net/note/reject/85949 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#144719) next »