Home Backend Development PHP Tutorial Encapsulation of PHP single file upload function

Encapsulation of PHP single file upload function

Jul 25, 2016 am 08:43 AM

  1. //Encapsulation of single file upload function
  2. //Principle of file upload: Upload client files to the server, and then move the temporary files on the server to the specified directory.
  3. //Direction of the file: Client -> Server (temporary file) -> Specify the directory. When the file enters the server, it becomes a temporary file. At this time, the name of the temporary file tmp_name should be used in the operation.
  4. //It is unsafe to set upload file restrictions (file type and size) on the client because customers can modify the restrictions through source code, so set restrictions here on the server.
  5. //Set encoding to UTF-8 to avoid Chinese garbled characters
  6. header('Content-Type: text/html;charset=utf-8');
  7. //Receive uploaded file information through $_FILES
  8. $fileInfo = $ _FILES['myFile'];
  9. function uploadFile($fileInfo,$uploadPath='uploads',$flag=true,$allowExt=array('jpeg','jpg','png','gif'),$maxSize = 2097152){
  10. //Judge the error number, it can only be 0 or UPLOAD_ERR_OK, no error occurs, the upload is successful
  11. if($fileInfo['error']>0){
  12. //Attention! The error message is no 5
  13. switch($fileInfo['error']){
  14. case 1:
  15. $mes= 'The uploaded file exceeds the value of the upload_max_filesize option in the PHP configuration file';
  16. break;
  17. case 2:
  18. $mes= 'Exceeded the size of the HTML form MAX_FILE_SIZE limit';
  19. break;
  20. case 3:
  21. $mes= 'The file was partially uploaded';
  22. break;
  23. case 4:
  24. $mes= 'No option to upload the file';
  25. break;
  26. case 6:
  27. $mes= 'Temporary directory not found';
  28. break;
  29. case 7:
  30. $mes= 'File writing failed';
  31. break;
  32. case 8:
  33. $mes= 'The uploaded file was deleted by PHP Extension program break';
  34. break;
  35. }
  36. exit($mes);
  37. }
  38. $ext=pathinfo($fileInfo['name'],PATHINFO_EXTENSION);
  39. //$allowExt=array('jpeg',' jpg','png','gif');
  40. //Detect the type of uploaded file
  41. if(in_array($ext,$allowExt)){
  42. exit('illegal file type');
  43. }
  44. // Check whether the file size of the uploaded file meets the specification
  45. //$maxSize = 2097152;//2M
  46. if($fileInfo['size']>$maxSize){
  47. exit('The uploaded file is too large');
  48. }
  49. //Check whether the picture is a real picture type
  50. //$flag=true;
  51. if($flag){
  52. if(!getimagesize($fileInfo['tmp_name'])){
  53. exit('not a real picture Type');
  54. }
  55. }
  56. //Check whether it is uploaded through HTTP POST
  57. if(!is_uploaded_file($fileInfo['tmp_name'])){
  58. exit('The file is not uploaded through HTTP POST ');
  59. }
  60. //$uploadPath='uploads';
  61. //If there is no such folder, create one
  62. if(!file_exists($uploadPath)){
  63. mkdir( $uploadPath, 0777, true) ;
  64. chmod( $uploadPath, 0777 );
  65. }
  66. //The new file name is unique
  67. $uniName = md5 ( uniqid( microtime(true),true) ).'.'.$ext;
  68. $destination = $uploadPath. '/'.$uniName;
  69. //The @ symbol is to prevent customers from seeing error messages
  70. if(! @move_uploaded_file($fileInfo['tmp_name'], $destination )){
  71. exit('File move failed') ;
  72. }
  73. //echo 'File uploaded successfully';
  74. //return array(
  75. // 'newName'=>$destination,
  76. // 'size'=>$fileInfo['size'],
  77. // 'type'=>$fileInfo['type']
  78. //);
  79. return $destination;
  80. }
  81. ?>
Copy code

File upload, PHP


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

See all articles