True to form, encapsulating the previous file uploading script into a single custom PHP function is a straightforward process that can be performed without major problems, since most of the pertinent business logic has already been implemented before. However, let me go one step further and show you the signature of this brand new user-defined PHP function, called “uploadFile().” It looks like this: // define 'uploadFile()' function function uploadFile($uploadDir='C:uploaded_files'){ if(!is_dir($uploadDir)){ throw new Exception('Invalid upload directory.'); } if(!count($_FILES)){ throw new Exception('Invalid number of file upload parameters.'); } if(!in_array($_FILES['userfile']['type'],array throw new Exception('Invalid MIME type of target file.'); } $uploadFile=$uploadDir.basename($_FILES['userfile']['name']); if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadFile)){ return true; } // throw exception according to error number switch($_FILES['userfile']['error']){ case 1: throw new Exception('Target file exceeds maximum allowed size.'); break; case 2: throw new Exception('Target file exceeds the MAX_FILE_SIZE value specified on the upload form.'); break; case 3: throw new Exception('Target file was not uploaded completely.'); break; case 4: throw new Exception('No target file was uploaded.'); break; case 6: throw new Exception('Missing a temporary folder.'); break; case 7: throw new Exception('Failed to write target file to disk.'); break; case 8: throw new Exception('File upload stopped by extension.'); break; } } As you can see, the above “uploadFile()” PHP function encapsulates all the logic required to upload a selected file to the web server within its structure. And it takes up the directory in the web server as its unique input parameter - where the file in question will be moved. Based on this concept, the function checks to see if this directory is valid or not, and then uses “move_uploaded_file()”, a PHP built-in function, to complete the pertinent file uploading process. In addition, any error that might occur when these tasks are performed will trigger different exceptions that can be easily caught by a conventional “try-catch()” block. Quite simple to understand, right? Well, at this point I’m pretty sure that you've grasped how the previous “uploadFile()” does its thing. So I'm going to demonstrate how it can be used in the context of a practical example. You will see how useful it can be, when it comes to uploading a file via PHP. This hands-on demonstration will take place in the next section, so click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|