note 94126 added to function.move-uploaded-file

From: Date: Sun, 18 Oct 2009 07:21:42 +0000
Subject: note 94126 added to function.move-uploaded-file
Groups: php.notes 
Request: Send a blank email to php-notes+get-161845@lists.php.net to get a copy of this message
I have looked at a lot of the file upload code listed below and other php documentation and have developed hopefully a robust single file upload routine. I will later update with a multi file upload. Any comments/corrections would be welcomed. I have modestly tested the code. <?php // 5MB maximum file size $MAXIMUM_FILESIZE = 5 * 1024 * 1024; // Valid file extensions (images, word, excel, powerpoint) $rEFileTypes = "/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx| ppt|pptx){1}$/i"; $dir_base = "/your/file/location/"; $isFile = is_uploaded_file($_FILES['Filedata']['tmp_name']); if ($isFile) // do we have a file? {// sanatize file name // - remove extra spaces/convert to _, // - remove non 0-9a-Z._- characters, // - remove leading/trailing spaces // check if under 5MB, // check file extension for legal file types $safe_filename = preg_replace( array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($_FILES['Filedata']['name'])); if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE && preg_match($rEFileTypes, strrchr($safe_filename, '.'))) {$isMove = move_uploaded_file ( $_FILES['Filedata']['tmp_name'], $dir_base.$safe_filename);} } } ?> I use $isFile and $isMove later in the code for error recording. Make sure your system has the appropriate file loading limits. This caused a lot of headeaches trying to figure out why some files loaded and some did not. In my case I have an .htaccess file in the root of the web site with: php_value post_max_size 16M php_value upload_max_filesize 6M You may also need to extend the execution time depending upon the amount of data being transferred. (sorry if spacing of code is a little off. it was hard to make the note editor like the code style.) ---- Server IP: 64.71.164.2 Probable Submitter: 67.188.179.86 ---- Manual Page -- http://www.php.net/manual/en/function.move-uploaded-file.php Edit -- https://master.php.net/note/edit/94126 Del: integrated -- https://master.php.net/note/delete/94126/integrated Del: useless -- https://master.php.net/note/delete/94126/useless Del: bad code -- https://master.php.net/note/delete/94126/bad+code Del: spam -- https://master.php.net/note/delete/94126/spam Del: non-english -- https://master.php.net/note/delete/94126/non-english Del: in docs -- https://master.php.net/note/delete/94126/in+docs Del: other reasons-- https://master.php.net/note/delete/94126 Reject -- https://master.php.net/note/reject/94126 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#161845) next »