Locking mechanism, uploading and downloading of summary files
1. File Locking is now in the attention of what distributed, concurrency, and so on, in fact, the operation of the file is also concurrent, in the network environment, multiple users at the same time to access the page, The same server on the same file to read, if the user just read half, another user wrote the message, then the previous user read the error data, in the database appears to be called dirty data, and if a user writes half, another user also writes to the file, Then it creates confusion and errors in writing data, so PHP has a lock mechanism, similar to the database lock, when a user in the operation of the file with some kind of lock, so that at the same time other users can not operate the file or only limited operation, to ensure that the file data in these cases are correct. Mainly uses the Flock function, prototype: BOOL Flock (Resource $handle, int $operation [, int & $wouldblock]), the first parameter is a pointer to the The handle variable of the file, the second is the way of locking, for &NBSP;LOCK_SH: Shared lock (Share), the lock is added when the file is read, and the other user can no longer write to the file after lock, but the content of the file may be read; &NBSP;LOCK_EX: Exclusive lock (exclude), or exclusive lock, used when writing a file, after adding the lock, only the current user to write, other users can not read and write; Lock_nb: Additional locks, a large number of user access operations in a short period of time file locking may cause flock blocking when locked, if the lock can avoid the situation (is not so much to solve the problem of a large number of read and write operations, afraid not ...) ); lock_un: Release the lock and unlock it once for the various locks in front. If it is easy to block, you can also use the third parameter wouldblock, if it is set to 1, after locking will block other processes to do some operations, but not supported on Windows, additional lock LOCK_NB, Windows is also not supported. In addition, fclose operations that turn off handle variables can also release these locks. Talk less, see Code copy Code <?php function readfiledata ($filename) { if (true = = ($handle = fopen ($filename, ' R '))) { i F (Flock ($handle, lock_sh+lock_nb)) { //Plus shared lock and additional lock, additional lock prevent blocking &NBS p; $str = '; while (!feof ($handle)) { &NBSP ; $str. = Fread ($handle, +); &NBS P } flock ($handle, lock_un); Release the lock fclose ($handle); & nbsp return $str; } &nbs P Else{ echo ' Add a share lock failed '; &NBSP ; return '; } } else{ return '; & nbsp } } Copy code Note the way to use multiple locks is lock_sh+lock_nb, which is also used for exclusive locks, which are enumerated variables. For write operations like copy code <?php function Writeinfile ($filename, $data) { if (true = = ($ Handle = fopen ($filename, ' a ')) { if (Flock ($handle, lock_ex)) { //Plus exclusive lock &nbs P fwrite ($handle, $data); & nbsp Flock ($handle, lock_un); //release lock fclose ($handle);   } else{ echo ' add E Xclusive Lock failed '; return; &N Bsp } } Copy code Actually this is also the way to solve PHP to implement multi-process/thread read files, PHP does not have multi-threading to say, However, the locking mechanism can be used to simulate this way, to achieve the processing of certain operations of the file queue, interview don't say you don't know-_- 2. File Upload File upload is the local files uploaded to the server, we are in the field of cloud, Goose Farm, cloud upload files are so, of course, the actual situation is certainly more complicated than this simple program. HTTP protocol implementation of the file upload mechanism, the first to select the local upload file, uploaded to the server, the service side to do some processing, for this client and service side to do some settings. 1, client File upload the most basic method is through the form form to post the file, in fact, through the Put method can also upload files, Only this method is unsafe, you need to configure some security authentication mechanism, here only write the most common way. The input label of form form can be set to File Upload button type= "files", directly solve the problem of how to select files, next need to set the form of the two properties: Enctype and method Enctype: Set to multipart/form-data method: Set to post About Enctype property settings refer to W3school's explanation &NBSP;&NBsp; The first is the default value, when we use the HTTP protocol to pass generic form data, the data is actually chunked encoded by default, such as the default UrlEncode mode (space to +, other non-alphabetic characters to% Plus two hexadecimal capitals); When Enctype is set to the second, character encoding is not performed, the file is uploaded using the upload control (that is, when the input tag type is set to file), and the third is the value of a space encoded as +, but not a non-alphabetic character encoding. We know that the Get method is generally used to get data, and the pass data size is limited, and the post method can pass much larger data than get. form After the property setting is complete, pass a value past, use the hidden field (<input type= "hidden" >), its Name property is set to Max_file_size, The reason to set this value, is to first approximate a file size value, to avoid the user to send a large file for half a day and then tell him: Sorry, your file is too large-_-its Value property is the size of the file, in bytes. Of course, some books say that this value is only as a reference, can be easily deceived, here is only a symbolic expression, it is a pity that my rookie on the safety of little knowledge, only know common injection, XSS, etc., for the moment. Then you can write a simple page, as a client: <form method= "POST" action= "upload.php" enctype= " Multipart/form-data "> <input type=" hidden "name=" max_file_size "value=" 1000000 "/> Select File: <input type= "file" Name= "UploadFile" value= "upload"/><br/> & nbsp; <input type= "Submit" Name= "Submit" value= "upload"/></form> 2, service side file uploaded to the server also through a number of processing procedures, Like online shopping delivery Express, to the destination also scored a class, confirm the next destination right and wrong bar. The subsequent processing of the destination requires a PHP script, which specifies the processing script for the commit when the form is submitted with the Action property. We know that in PHP, $_post saves post-delivered data, and the information about the uploaded file is stored in $_files, assuming the server-side script is: <?php echo ' _files: <pre > '; print_r ($_files); echo ' _post: <pre> '; Print_r ($_post); Regardless of how the server handles it, let's look at what the two arrays have: See the options for the files array to guess, these are the names, types, sizes, error messages, and so on, and this file is a two-dimensional array. Before figuring out these options it is necessary to understand a few PHP configuration options, open the php.ini file, and find the following four items (actually see the annotation also understand): File_uploads: Whether the file is allowed to be passed through HTTP, The default is on allow; Upload_max_filesize: Allows the maximum size of files to be passed, in M, which is the option for server-side profile settings; Max_file_uploads: The number of long files allowed to be passed on a single request; Post_max_size: The maximum size of the data passed through post, because file delivery is also post mode, Also counted as post delivery, it is important to note that it must be larger than the upload_max_filesize option, because during a post delivery process, it is notOnly uploading files and passing other values, such as the data in the post array above, must be taken into account, such as Upload_max_filesize set to 150M, which can be set to 200m; Upload_ Tmp_dir: The temporary directory to upload files, the configuration file default is empty, will use the operating system default temporary directory, so the above files array of tmp_name in the familiar path can be explained, using the Windows default storage temporary files directory, and the server defaults to the file name modification. So where does the uploadfile in the files array come from, why use it as a key name, because the Name property of the upload control is uploadfile, which marks the upload file information for this control, So we can put more than one upload control, set a different name, of course, set the same name can be, completely put them all in an array inside, such as <input type= "file" name= "upload[" ">. Now look back at the information that the key name of the file array represents, type is the MIME type, with/delimited, preceded by the main type, followed by the specific file type, error must indicate an error, there are several cases, 0: no error, Upload succeeded; 1: The file exceeds the size specified by upload_max_filesize in the PHP configuration Directive, 2: The file exceeds the max_file_size specified in the HTML form, 3: The file is only partially uploaded; 4: no file upload. Now the questions about the files array are all clear. The question is, is not the upload success does not do any processing, of course, not always in a temporary directory, the upload is more than necessary to move the file to another place, and PHP provides a special and safe function. The Is_uploaded_file function, which determines whether HTTP post uploads can be used to ensure that malicious users cheat scripts and manage those files, such as/etc/pass (again Linux ...). As to how it is, I am not sure. The Move_uploaded_file function, which moves the uploaded file to a new location, also determines whether the file is a legitimate upload, that is, through HTTP POST, which returns the Boolean type True when they run successfully. for half a day, uploading a file probably goes through a few steps: 1, client write upload control script, and pass a limit file size hidden value; &NBSP;2, the server first judge the files array error value, see if there is an error; &NBSP;3, determine whether to allow the type of upload (can not be judged); 4, determine whether the server-side script inside the specified file size; 5, upload to a temporary location, generate a new file name (prevent overwriting the file with the same name), check and move to the new directory. Client preparation has just been done, look at the server-side processing code: copy Code <?php $typeWhiteList = array (' txt ', ' Doc ', ' php ', ' zip ', ' exe '); //Type whitelist, filter file types not allowed to upload $max _size = 1000000; //size limit is 1m $upload _path = ' d:/wamp/upload/'; //Specify the directory to move to //1 to determine if the server was successfully uploaded $error = $_files[' Uploadfil E ' [' Error ']; if ($error > 0) { switch ($error) { case 1:exit (' Maximum file upload limit over PHP configuration '); case 2:exit (' more than HTML Maximum file upload limit for the form '); case 3:exit (' file only partially uploaded '); &nbsP case 4:exit (' No files uploaded '); default:exit (' Unknown type error '); } } //2 to determine if the type of upload is allowed &NBSP ; $extension = PathInfo ($_files[' uploadfile ' [' name '], pathinfo_extension); Get extensions if (!in_array ($extension, $typeWhiteList)) { if ($extension = = ") &N Bsp exit (' not allowed to upload empty type files '); else &NB Sp exit (' Do not allow uploads '. $extension. ' Type file '); } //3, determine if the allowable size if ($_files[' uploadfile ' [') Size '] > $max _size) { exit (' More than allowed to upload '. $max _size. ' Bytes '); } //4, to the specified location $filename = date (' YMD '). Rand (1000, 9999); //Generate a new file name to prevent overwriting if (Is_uploaded_file ($_files[' uploadfile ') [' Tmp_name ')) { //determine if HTTP POST upload if (!move_uploaded_file ($_files[' uploadfile '] [' Tmp_name '], $upload _path. $filename. '. $extension) { exit (' Unable to move to specified position '); } else{ echo ' File upload success <br/> '; & nbsp echo ' filename: '. $upload _path. $filename. '. $extension. ' <br> '; } } else{ e XIT (' File not uploaded by legal means '); } Copy code I want to quickly experience a piece, the results reported a warning, said time-dependent system ... bug always so unexpected, After setting the time, try,perfect! 3. File Download File download is relatively simple, simple file download only need to use an HTML link is enough, using the <a> tag, href attribute to specify the resource location, a little. However, this approach can only handle MIME types that are not recognized by the browser, such as RAR, 7z, and other compressed data. Copy Code
Locking, uploading and downloading of PHP files