Home  >  Article  >  Backend Development  >  PHP file locking, uploading and downloading_PHP tutorial

PHP file locking, uploading and downloading_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:13:10926browse

PHP file locking, uploading and downloading

Summary of file locking mechanism, uploading and downloading
1. File lock
Nowadays, we are all paying attention to distribution, concurrency, etc. In fact, file operations are also concurrent. In a network environment, multiple users access the page at the same time and read the same file on the same server. If , this user just finished reading halfway, and another user wrote the message, then what the previous user read was wrong data, which seems to be called dirty data in the database, and if a user writes halfway, another user Also writing to the file will cause confusion and errors in writing data. Therefore, PHP has a lock mechanism, which is similar to a database lock. When a user operates on a file, a certain lock is added, so that At the same time, other users cannot operate on the file or can only perform limited operations to ensure the correctness of the file data under these circumstances.
Mainly use flock function, prototype: bool flock(resource $handle, int $operation [, int &$wouldblock]), the first parameter is the handle variable pointing to the file, the second one is the locking method, respectively for
LOCK_SH: Shared lock (share), a lock added when reading a file. After locking, other users can no longer write to the file, but can read the file content;
LOCK_EX: Exclusive lock (exclude), or exclusive lock, used when writing files. After adding this lock, only the current user can perform writing operations, and other users cannot read or write;
LOCK_NB: Additional lock. When the file is locked, a large number of user access operations may cause the flock to be blocked during locking. If this lock is added, this situation can be avoided (can this be done to solve a large number of reads and writes? Operational issues, I’m afraid it won’t work...);
LOCK_UN: Release the lock, release and unlock the previous locks at one time.
If it is easy to block, you can also use the third parameter wouldblock. If it is set to 1, it will block other processes from performing some operations after locking, but it is not supported on Windows. In addition, the additional lock LOCK_NB is not supported on Windows. Supported.
In addition, the fclose operation that closes the handle variable can also release these locks.
Stop talking nonsense and look at the code
Copy code
function readFileData($filename){
if(true == ($handle = fopen($filename, 'r'))){
                                                                                                                                                                                                                                                             
$str = '';
            while(!feof($handle)){
                      $str .= fread($handle, 128);
        }
                  flock($handle, LOCK_UN); // Release the lock
                                                                                                                                                                                       
                    return $str;
      }
else{
echo 'add a share lock failed';
              return '';
      }
    }
else{
            return '';
    }
}
Copy code
Note that the way to use multiple locks is LOCK_SH+LOCK_NB, which can also be used for exclusive locks. They are all enumeration variables. Similar to
for write operations
Copy code
function writeInFile($filename, $data){
if(true == ($handle = fopen($filename, 'a'))){
                                                                                                                                                                                                                               
                fwrite($handle, $data);
              flock($handle, LOCK_UN); //Release lock
              fclose($handle);
      }
else{
echo 'add exclusive lock failed';
            return;
      }
}
}
Copy code
In fact, this is also a way to solve PHP to realize multi-process/thread reading files. PHP does not have multi-threading, but the locking mechanism can simulate this method and realize queue processing of certain operations on files. Don’t say you don’t know during the interview-_-
2. File upload
File upload is to upload local files to the server. This is the case when we upload files using Duchang's cloud and Echang's cloud. Of course, the actual situation is definitely more complicated than this simple procedure. The HTTP protocol implements the file upload mechanism. First, the uploaded file must be selected locally. After uploading to the server, the server must do some processing. For this purpose, both the client and the server must make some settings.
1. Client
The most basic method of file upload is to POST the file through the form. In fact, you can also upload files through the PUT method. However, this method is not safe and needs to be configured with some security verification mechanisms. Here we only write the most commonly used methods. . The input tag of the form can be set to the file upload button type="file", which directly solves the problem of how to select a file. Next, you need to set two attributes of the form: enctype and method
enctype: set to multipart/form-data
method: set to post
About enctype attribute setting, please refer to W3School’s explanation
The first one is the default value. When we use the HTTP protocol to transmit general form data, the data is actually encoded in blocks by default, such as the default urlencode method (spaces are converted to +, other non-letter characters are converted to Add two hexadecimal uppercase numbers to %); when enctype is set to the second one, character encoding will not be performed. Use the upload control (that is, when the input tag type is set to file) to upload files, which must be set to this value; the third value encodes spaces as + but does not encode non-alphabetic characters.
We know that the GET method is generally used to obtain data, and the size of the transferred data is limited, and the POST method can transfer much larger data than GET.
After the form attributes are set, a value needs to be passed, using a hidden field (). Its name attribute is set to MAX_FILE_SIZE. The reason for setting this value is First roughly determine a file size value to avoid telling the user after a long time of uploading a large file: sorry, your file is too big -_- Its value attribute value is the size of the file, in bytes. Of course, some books say that this value is only for reference and can be easily deceived. This is just a symbolic representation. It is a pity that I, a rookie, know very little about security. I only know about ordinary injection, XSS, etc., so I will use it for now.
Then you can write an extremely simple page to use as a client:
Select file:
         
2. Server
After the file is uploaded to the server, it still needs to go through some processing. Just like online shopping and express delivery, it is also divided into categories when it reaches the destination. Make sure the destination is correct. Subsequent processing at the destination requires a PHP script. The action attribute when submitting the form above specifies the submission processing script. We know that in php, $_POST saves the data passed by post, and the relevant information of the uploaded file is saved in $_FILES. Assume that the server script is like this:
echo '_FILES:
';
print_r($_FILES);
echo '_POST:
';
print_r($_POST);
No matter how the server handles it, let’s first take a look at what’s in these two arrays:
You can guess it by looking at the options of the FILES array. These are the name, type, size, error message, etc. of the uploaded file. Also, FILES is a two-dimensional array. Before figuring out these options, it is necessary to understand several PHP configuration options. Open the php.ini file and find the following four items (in fact, you can understand it by looking at the comments):
file_uploads: Whether to allow file transfer via HTTP, the default is On;
upload_max_filesize: The maximum size of files allowed to be transferred, in M, this is an option set by the server configuration file;
max_file_uploads: The number of multiple files allowed to be passed in one request;
Post_max_size: The maximum size of data transferred through POST, because file transfer is also a post method, and it is also considered a post transfer. Special attention should be paid to that it must be larger than the upload_max_filesize option, because not only files will be uploaded during a post transfer, Other values ​​will also be passed, such as the data in the POST array above, which must be taken into account. For example, if upload_max_filesize is set to 150M, this can be set to 200M;
upload_tmp_dir: The temporary directory for uploading files. The configuration file is empty by default. The default temporary directory of the operating system will be used. Therefore, the familiar path in tmp_name in the FILES array above can be explained. The default storage of windows is used. The directory of temporary files, and the file name is modified by the server by default.
So where does uploadFile in the FILES array come from, and why do we use it as the key name? This is because the name attribute of the upload control is uploadFile, which marks the upload file information of this control, so we can put multiple For the upload control, set different names. Of course, you can also set the same name. You can put them all in an array, such as .
Now look back at the information represented by the key name of the FILE array. Type is the MIME type, separated by /. The front is the main type, and the back is the specific file type. error definitely means an error. There are several situations, 0: None Error, the upload is successful; 1: The file exceeds the size specified by upload_max_filesize in the PHP configuration directive; 2: The file exceeds the size specified by MAX_FILE_SIZE in the HTML form, 3: The file is only partially uploaded; 4: No file is uploaded. Now I understand all the issues about the FILES array.
The question is, if the upload is successful, no processing will be done. Of course not, it cannot be piled up in a temporary directory. If you upload too many files, you will inevitably move the files to other places, and PHP provides a special Safe function. The is_uploaded_file function determines whether to upload via HTTP POST, which can ensure that malicious users can deceive scripts and manage these files, such as /etc/pass (linux again...). As for the specific details, I don't know yet. The move_uploaded_file function moves the uploaded file to a new location and can also determine whether the file is legitimately uploaded, that is, through HTTP POST. If they run successfully, they will return Boolean type true.
After talking for a long time, uploading files probably requires the following steps:
1. The client writes the upload control script and passes a hidden value that limits the file size;
2. The server first judges the error value of the FILES array to see if there is an error;
3. Determine whether it is a type that allows uploading (you don’t have to judge);
4. Determine whether the specified file size is exceeded in the server script;
5. Upload to a temporary location, generate a new file name (to prevent overwriting existing files with the same name), check and move to the new directory.
The client preparation work has just been done, look at the server processing code:
Copy code
$typeWhiteList = array('txt', 'doc', 'php', 'zip', 'exe'); // Type whitelist, filtering file types that are not allowed to be uploaded
$max_size = 1000000; // Size limit is 1M
$upload_path = 'D:/WAMP/upload/'; // Specify the directory to move to
// 1. Determine whether the upload to the server is successful
$error = $_FILES['uploadFile']['error'];
if($error > 0){
switch($error){
case 1: exit('Exceeded the maximum file upload limit configured by php');
case 2: exit('Exceeded maximum file upload limit of HTML form');
case 3: exit('Only part of the file was uploaded');
case 4: exit('No files uploaded');
default: exit('Unknown type error');
} }
}
// 2. Determine whether it is a type that allows uploading
$extension = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION); // Get extension
if(!in_array($extension, $typeWhiteList)){
if($extension == '')
exit('Uploading empty type files is not allowed');
else
exit('Not allowed to upload'.$extension.'type file');
}
// 3. Determine whether it is the allowed size
if($_FILES['uploadFile']['size'] > $max_size){
exit('Exceeded the allowed upload to '.$max_size.' bytes');
}
// 4. Arrive at the designated location
$filename = date('Ymd').rand(1000, 9999); // Generate a new file name to prevent overwriting
if(is_uploaded_file($_FILES['uploadFile']['tmp_name'])){ // Determine whether to upload via HTTP POST
if(!move_uploaded_file($_FILES['uploadFile']['tmp_name'], $upload_path.$filename.'.'.$extension)){
exit('Unable to move to the specified location');
} }
else{
                    echo 'File uploaded successfully
';
echo 'File name: '.$upload_path.$filename.'.'.$extension.'
';
} }
}
else{
exit('The file was not uploaded through legal channels');
}
Copy code
I wanted to try it out quickly, but a Warning was reported, saying that the time setting depends on the system...bugs always happen unexpectedly, set the time and try again, perfect!
3. File download
Copy code
                                                                                                                                                       
& lt; meta http-equiv = "Content-Type" Content = "Text /HTML"; Charset = "UTF-8" /& GT;
                                                                                                                                                                                       
                                                                                                                                                    
                                                                                                                               
                                                                     
Copy code
For these types of files that are not recognized by the browser, click on the link and it will directly pop up a box for you to download. Some browsers even download it directly. So for text, txt, jpg and other types of files that are recognized by browsers by default, Once clicked, it will be displayed directly on the page, such as header.txt and pic.ico above. How to download them without displaying them on the page? Use the header function.
The header function will notify you by sending header information. Please treat the file as an attachment, so that it will be downloaded when clicked.
Copy code
$filename = 'header.txt';
header('Content-Type: text/plain'); // The type is plain text
header('Content-Disposition:attachment; filename="$filename"'); // Content-Disposition:attachment, tell it this is an attachment
header('Content-Length:'.filesize($filename)); // Inform the file size
readfile($filename); // Read the file and output it directly for easy downloading
Copy code

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/917111.htmlTechArticle Summary of file locking, uploading and downloading in PHP File locking mechanism, uploading and downloading 1. File locking is now available No matter what distribution, concurrency, etc. are concerned about, in fact, file operations are also...
Statement:
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