Slimore
  • Namespace
  • Class

Namespaces

  • None
  • Slimore
    • Cache
      • Exception
    • Captcha
    • Database
    • Debug
    • Http
    • Image
    • Log
    • Middleware
    • Mvc
    • Pagination
    • Upload

Classes

  • Slimore\Cache\File
  • Slimore\Captcha\Builder
  • Slimore\Database\Manager
  • Slimore\Debug\Simpler
  • Slimore\Http\Client
  • Slimore\Image\Gd
  • Slimore\Log\Writer
  • Slimore\Middleware\Exceptions
  • Slimore\Mvc\Application
  • Slimore\Mvc\Controller
  • Slimore\Mvc\Model
  • Slimore\Mvc\View
  • Slimore\Pagination\Paginator
  • Slimore\Upload\Uploader

Exceptions

  • Slimore\Cache\Exception\File
  • Slimore\Captcha\Exception
  • Slimore\Database\Exception
  • Slimore\Http\Exception
  • Slimore\Mvc\Exception
  • Slimore\Pagination\Exception
  • Slimore\Upload\Exception

Functions

  • arrayToObject
  • console
  • controller
  • ctl
  • currentUrl
  • decrypt
  • detectDevice
  • encrypt
  • fileFormatSize
  • getDirectoryItems
  • getDpi
  • hexToRGB
  • html
  • imageDataUrl
  • iPad
  • iPhone
  • iPod
  • isAndroid
  • isApache
  • isBlackberry
  • isChrome
  • isCli
  • isFirefox
  • isFreeBSD
  • isIE
  • isIIS
  • isJson
  • isLinux
  • isMacOSX
  • isMobile
  • isNginx
  • isOpera
  • isSafari
  • isTablet
  • isUnix
  • isUnixLike
  • isWebOS
  • isWindows
  • js
  • jsonToArray
  • linkTag
  • password
  • phoneMaskCode
  • randomCharacters
  • replaceDirSeparator
  • rgbToHex
  • script
  • shortUrl
  • style
  1 <?php
  2 
  3 /**
  4  * Slimore - The fully (H)MVC framework based on the Slim PHP framework.
  5  *
  6  * @author      Pandao <slimore@ipandao.com>
  7  * @copyright   2015 Pandao
  8  * @link        http://github.com/slimore/slimore
  9  * @license     MIT License https://github.com/slimore/slimore#license
 10  * @version     0.1.0
 11  * @package     Slimore\Upload
 12  */
 13 
 14 namespace Slimore\Upload;
 15 
 16 /**
 17  * Class Uploader
 18  *
 19  * @author Pandao
 20  * @package Slimore\Upload
 21  */
 22 
 23 class Uploader
 24 {
 25     /**
 26      * $_FILES array
 27      *
 28      * @var array
 29      */
 30     public $files;
 31 
 32     /**
 33      * Read and write authority mode
 34      *
 35      * @var int
 36      */
 37 
 38     public $mode = 0755;
 39 
 40     /**
 41      * @var string
 42      */
 43     public $lang = 'EN';
 44 
 45     /**
 46      * Filename extension
 47      *
 48      * @var string
 49      */
 50     public $fileExit;
 51 
 52     /**
 53      * Saved filename
 54      *
 55      * @var string
 56      */
 57     public $saveName;
 58 
 59     /**
 60      * Url path Saved to database
 61      *
 62      * @var string
 63      */
 64     public $saveURL;
 65 
 66     /**
 67      * Saved the local file path
 68      *
 69      * @var string
 70      */
 71 
 72     public $savePath;
 73 
 74     /**
 75      * Output result message
 76      *
 77      * @var string
 78      */
 79     public $message;
 80 
 81     /**
 82      * Generate the length of the random file name
 83      *
 84      * when the date is the date() format
 85      *
 86      * @var string|int
 87      */
 88 
 89     public $randomLength   = 'Ymd';
 90 
 91     /**
 92      * Generate the random form
 93      *
 94      * NULL to retain the original file name
 95      * 1 generated random strings
 96      * 2 generate the date file name
 97      *
 98      * @var int
 99      */
100 
101     public $randomNameType = 1;
102 
103     /**
104      * Timezone
105      *
106      * @var string
107      */
108 
109     public $timezone = 'PRC';
110 
111     /**
112      * Allow Upload file format
113      *
114      * @var array
115      */
116 
117     public $formats = ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'];
118 
119     /**
120      * Maximum upload file size, unit KB
121      *
122      * @var int
123      */
124 
125     public $maxSize = 1024;
126 
127     /**
128      * Whether to cover the same name file, true covered, false not covered
129      * @var bool
130      */
131     public $cover = true;
132 
133     /**
134      * Whether URL redirect
135      *
136      * @var bool
137      */
138     public $redirect = false;
139 
140     /**
141      * Redirect url
142      *
143      * @var string
144      */
145 
146     public $redirectURL = "";
147 
148     /**
149      * Errors message
150      *
151      * @var array
152      */
153     public $errors = [
154         'empty'      => 'The upload file can\'t be empty.',
155         'format'     => 'The uploaded file format does not conform to the regulations.',
156         'maxsize'    => 'The upload file size too large.',
157         'unwritable' => 'Save the directory not to write, please change permissions.',
158         'not_exist'  => 'Save the directory not exist.',
159         'same_file'  => 'There are already the same file exist.'
160     ];
161 
162     /**
163      * Constructor
164      *
165      * @access public
166      * @param array $configs
167      * @return  viod
168      */
169 
170     public function __construct(array $configs)
171     {
172         $this->config($configs);
173     }
174 
175     /**
176      * Set configs
177      *
178      * @access  public
179      * @param   array $configs
180      * @return  void
181      */
182 
183     public function config(array $configs)
184     {
185         foreach($configs as $key => $value)
186         {
187             if (property_exists($this, $key))
188             {
189                 $this->$key = $value;
190             }
191         }
192     }
193 
194     /**
195      * Execute upload
196      *
197      * @access  public
198      * @param   string $name  fileInput's name
199      * @return  bool
200      */
201 
202     public function upload($name)
203     {
204         // When $_FILES[$name]['name'] empty
205 
206         if ( empty($_FILES[$name]['name']) )
207         {
208             $this->error($this->errors['empty'], 0, true);
209 
210             return false;
211         }
212 
213         $this->files = $_FILES[$name];
214 
215         // When the directory is not exist.
216         if( !file_exists($this->savePath) )
217         {
218             $this->error($this->errors['not_exist'], 0, true);
219 
220             return false;
221         }
222 
223         // When the directory is not written
224         if( !is_writable($this->savePath) )
225         {
226             $this->error($this->errors['unwritable'], 0, true);
227 
228             return false;
229         }
230 
231         return $this->moveFile();
232     }
233 
234     /**
235      * Check and move the upload file
236      *
237      * @access  private
238      * @return  bool
239      */
240 
241     private function moveFile()
242     {
243         $this->setSeveName();
244 
245         $files = $this->files;
246 
247         if ($this->formats != "" && !in_array($this->fileExt, $this->formats))
248         {
249             $formats  = implode(',', $this->formats);
250             $message  = "Your upload file " . $files["name"] . " is " . $this->fileExt;
251             $message .= " format, The system is not allowed to upload, you can only upload " . $formats . " format's file.";
252 
253             $this->error($message, 0, true);
254 
255             return false;
256         }
257 
258         if ($files["size"] / 1024 > $this->maxSize)
259         {
260             $message = "Your upload file " . $files["name"] . "  The file size exceeds of the system limit size " . $this->maxSize . " KB.";
261             $this->error($message, 0, true);
262 
263             return false;
264         }
265 
266         // When can't covered
267         if (!$this->cover)
268         {
269             // The same file already exists
270             if (file_exists($this->savePath . $this->saveName))
271             {
272                 $this->error($this->saveName . $this->errors['same_file'], 0, true);
273 
274                 return false;
275             }
276         }
277 
278         if ( !@move_uploaded_file( $files["tmp_name"], iconv("utf-8", "gbk", $this->savePath . $this->saveName) ) )
279         {
280             switch ($files["error"])
281             {
282                 case '0':
283                     $message = "File upload successfully.";
284                     break;
285 
286                 case '1':
287                     $message = "The uploaded file exceeds the value of the upload_max_filesize option in php.ini.";
288                     break;
289 
290                 case '2':
291                     $message = "The size of the upload file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.";
292                     break;
293 
294                 case '3':
295                     $message = "Only part of the file is uploaded.";
296                     break;
297 
298                 case '4':
299                     $message = "No file is uploaded.";
300                     break;
301 
302                 case '6':
303                     $message = "Can't find upload temp directory.";
304                     break;
305 
306                 case '7':
307                     $message = "Error writing file to hard drive";
308                     break;
309 
310                 case '8':
311                     $message = "An extension has stopped the upload of the file.";
312                     break;
313 
314                 case '999':
315                 default:
316                     $message = "Unknown error, please check the file is damaged, whether the oversized and other reasons.";
317                     break;
318             }
319 
320             $this->error($message, 0, true);
321 
322             return false;
323         }
324 
325         @unlink($files["tmp_name"]); // Delete temporary file
326 
327         return true;
328     }
329 
330     /**
331      * Generate random file name
332      *
333      * @access  private
334      * @return  string $fileName
335      */
336 
337     private function randomFileName()
338     {
339         $fileName = '';
340 
341         // Generate the datetime format file name
342         if ($this->randomNameType == 1)
343         {
344             date_default_timezone_set($this->timezone);
345 
346             $date     = date($this->randomLength);
347             echo $dir      = $this->savePath . $date;
348 
349             if ( !file_exists($dir) ) {
350                 mkdir($dir, $this->mode, true);
351             }
352 
353             $fileName = $date . '/' . time();
354         }
355         elseif ($this->randomNameType == 2)    // Generate random character file name
356         {
357             $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
358             $max   = strlen($chars) - 1;
359             mt_srand( (double) microtime() * 1000000);
360 
361             for ($i = 0; $i < $this->randomLength; $i++)
362             {
363                 $fileName .= $chars[mt_rand(0, $max)];
364             }
365         }
366         else
367         {
368         }
369 
370         $this->fileExt = $this->getFileExt($this->files["name"]);
371 
372         $fileName = $fileName . '.' . $this->fileExt;
373 
374         return $fileName;
375     }
376 
377     /**
378      * Set Saved filename for database
379      *
380      * @access  private
381      * @return  void
382      */
383 
384     private function setSeveName()
385     {
386         $this->saveName = $this->randomFileName();
387 
388         if ($this->saveName == '')
389         {
390             $this->saveName = $this->files['name'];
391         }
392     }
393 
394     /**
395      * Get Saved filename for database
396      *
397      * @access  public
398      * @return  string
399      */
400 
401     public function getSeveName()
402     {
403         return $this->saveName;
404     }
405 
406     /**
407      * Get filename extension
408      *
409      * @access public
410      * @param string $fileName
411      * @return string
412      */
413 
414     public function getFileExt($fileName)
415     {
416         return trim( strtolower( substr( strrchr($fileName, '.'), 1) ) );
417     }
418 
419     /**
420      * Redirect for Upload success, failure or error
421      *
422      * @access  public
423      * @return  void
424      */
425 
426     public function redirect()
427     {
428         header('location: ' . $this->redirectURL);
429     }
430 
431     /**
432      * Errors message handle
433      *
434      * @access public
435      * @param string $message
436      * @param int $success
437      * @param bool $return false
438      * @return array|string
439      */
440 
441     public function message($message, $success = 0, $return = false)
442     {
443         $array = array(
444             'success' => $success,
445             'message' => $message
446         );
447 
448         $url = $this->saveURL . $this->saveName;
449 
450         // Cross-domain redirect to callback url
451         if ($this->redirect)
452         {
453             $this->redirectURL .= '&success=' . $success . '&message=' . $message;
454 
455             if ($success == 1)
456             {
457                 $this->redirectURL .= '&url=' . $url;
458             }
459 
460             $this->redirect();
461         }
462         else
463         {
464             echo "success =>" . $success;
465             if ($success == 1)
466             {
467                 $array['url'] = $url;
468             }
469 
470             $this->message = $array = json_encode($array);
471 
472             if ($return)
473             {
474                 return $array;
475             }
476             else
477             {
478                 echo $array;
479             }
480         }
481     }
482 
483     /**
484      * Set JSON mime header
485      *
486      * @return void
487      */
488 
489     public function jsonHeader()
490     {
491         header('Content-Type: application/json');
492     }
493 
494     /**
495      * Upload success message handle
496      *
497      * @param string $message Upload successfully.
498      * @param bool $return false
499      * @return array|string
500      */
501 
502     public function success($message = "Upload successfully.", $return = false)
503     {
504         return $this->message($message, 1, $return);
505     }
506 
507     /**
508      * Upload failed or error message handle
509      *
510      * @param string $message Upload failed.
511      * @param bool $return false
512      * @return array|string
513      */
514 
515     public function error($message = "Upload failed.", $return = false)
516     {
517         return $this->message($message, 0, $return);
518     }
519 
520     /**
521      * Error exit
522      *
523      * @return void
524      */
525 
526     public function errorExit()
527     {
528          exit;
529     }
530 }
Slimore API documentation generated by ApiGen