Simply put, the first step that I’m going to take concerning the creation of a modular file uploading class with PHP 5 will consist of defining the skeleton of the class in question, while also implementing its pertinent constructor. This way you can grasp how it works more easily. Having said that, take a close look at the signature of the following brand new file uploading class, which, driven by my astounding creativity (I’m kidding), I called “FileUploader.” Here it is: // define 'FileUploader' class class FileUploader{ private $uploadFile; private $name; private $tmp_name; private $type; private $size; private $error; private $allowedTypes=array public function __construct($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.'); } foreach($_FILES['userfile'] as $key=>$value){ $this->{$key}=$value; } if(!in_array($this->type,$this->allowedTypes)){ throw new Exception('Invalid MIME type of target file.'); } $this->uploadFile=$uploadDir.basename($this->name); } // upload target file to specified location in the web server public function upload(){ / / code to perform file uploads goes here } } As you can see, the structure of the above “FileUploader” class looks quite simple, since it’s comprised of only two methods: the corresponding constructor and an additional one, called “upload()”, which, for now, hasn’t been concretely implemented. Returning to the constructor, you can clearly see that this method accepts the directory in the web server where the pertinent uploaded file will be finally moved as its unique input parameter. In addition, it performs a few other useful initialization tasks, such as checking to see whether or not the inputted directory is valid, and whether or not the MIME type of the target file is allowed. In this case, I instructed the class to accept only the most common image MIME types, like JPG and GIF, and a couple of additional ones as well, including “text/plain” and “application/msword.” But this condition can be easily modified to either accept more types or, on the other hand, to refuse some of the valid ones. All right, at this point you've hopefully grasped the logic implemented by the constructor of the previous “FileUploader()” class. Therefore, it’s time to implement the only method of this class that remains undefined, that is the one called “upload()”. However, to learn the details about how this class method will be implemented in a useful fashion, you’ll have to read the following section. Don’t you worry, since it’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|