Home >Backend Development >PHP Tutorial >[Happy 100 days of learning PHP] Day 3: Unruly PHP file operations_PHP tutorial

[Happy 100 days of learning PHP] Day 3: Unruly PHP file operations_PHP tutorial

WBOY
WBOYOriginal
2016-07-14 10:09:55890browse

Motto for this issue:

When databases did not exist, reading and writing files was one of the only things we programmers could do in the empty nights (maybe not necessarily~~~). So no matter how simple, fast and common this technology has become now, we still need to maintain a meticulous attitude and strict ethics, and never ignore its importance and rigor.
Text begins:
I have a little story about reading files. In the early days of the studio's establishment, when business was in a rush, a friend on QQ introduced that he had a friend who wanted to build a website for his company, and he recommended it to me. I was very excited when I heard this, and immediately fixed my hair and put out my cigarette butts, because my friend said that the client wanted to video chat with me later (so trendy?). It is also said that he is the IT director of a large company and is very formal. I should pay attention to it and not be too decadent. I deliberately took out the electric razor and shaved.
I was very fond of this kind of website business that cost thousands of dollars. Basically, I arranged the interface and made CSS, with no more than 100 sentences of php code. Just send a newbie to get it done in a week. Although reusability and subsequent business development are not at all possible, you will definitely get a month's worth of tobacco, alcohol and tea. Of course, I have to talk about it, let the newbies do it. Basically, I can only eat Malatang at the food stalls at night.
The video started, and a handsome man with a gentle appearance and thin vocal cords appeared on the opposite side. After exchanging polite polite words, he proudly introduced the factory he worked in. It was very big, and because it was growing too fast, too fast, too fast, too fast, he now wanted to build a website (I don’t know what the difference between being too fast and wanting to build a website was). (Too big a relationship) to fit the scale, and finally sent me an Excel with a structure diagram of the website homepage. He used to make all the company’s small software, because he has been too busy, too busy, too busy, too busy recently, so this I wanted to find an Internet company for development for the first time. At the end of the conversation, the handsome man told me tactfully that he "knows a lot about technology~".
A gust of cold wind blew by~~~.
I clicked on Excel. I admired the handsome man's "sketching" skills. It is rare to be able to draw the page structure in Excel and do it so vividly. I expressed my approval and said that the product could be delivered on time. At the same time, I sent the Excel to my artist and programmer and asked him to do it. The time is 3 days. But then the handsome man's request made me almost want to cover the desktop display. His request was to paste pictures and text directly into Excel, and then create multiple workbooks in the Excel (I was already confused at the time) , I don’t know whether to use $sheet or shit to express "workbook"). The homepage only needs one PHP page, and the workbooks in Excel are read separately according to its settings. In this way, the homepage that users open every once in a while is different. This shows the "diversification" and innovation of their factory's business from multiple angles.
The handsome man’s proud smile in the video made me doubt my own design ideas of “configuration and productization” to a large extent. I wanted to reject this kind of alien thinking, but the handsome man insisted on his "concept". He said that his design had been fully "highly praised" by his factory director.
Because of the magic power of the handsome man’s “transfer check”, I surrendered to his “configurable” idea. I just want to say that he is so awesome. I can’t be the IT director of a large enterprise because I really can’t think of this way to implement template switching in the CMS concept.
Of course I am not a fool (reading Office files is not a simple matter), I used a very simple method to solve this problem. And got the transfer check smoothly. The method is very simple. Use the basic HTML page to design five different pages required by the handsome man, and then save them as five different Excels (note: although the saved file suffix is ​​xls, it is actually still an HTML file), and use PHP to read them respectively. File display. The code at that time was as follows:
$fileIndex=rand(1,5); //Take a random number, ranging from 1 to 5
$fileName='index'.$fileIndex.'xls'; //Piece together a file name, note: index1.xls...index5.xls are placed in the root directory of the website, and index.php Same level
$getIndex=file_get_contents($fileName); //Read the file,
exit($getIndex); //Output the content of the read file and display it
?>
Here are a few knowledge points:
1. rand function
Get a random number, the parameter is the range rand (minimum value, maximum value). In the example, a number is randomly generated from 1 to 5. Then piece together a file name. Such as index1.xls, index2.xls, index3.xls, index4.xls, index5.xls, which means that I designed 5 pages for the handsome man and saved 5 xls files respectively.
Now that we have talked about the rand function, we have to expand our knowledge: array_rand function, (array--array, we have already talked about it in detail the previous day, so we will not go into details here)
The above method of randomly piecing together files can also be done in the following way
$file=array("index1.xls","index2.xls","index3.xls","index4.xls","index5.xls");
$fileName='index'.$file[array_rand($file,1)].'xls';
This shows that array_rand returns the key value of the incoming array, and the second parameter represents how many are returned. If it is 1, a character or numeric variable will be returned. If it exceeds 1, an array will be returned, which will contain 2 random key values.
2. file_get_contents function
This function is very important. We must remember it. It is also a very commonly used file content reading function. It means reading the contents of the file at once and reading it into an array.
Remember: one-time use. You can't interfere with it while it's being read. If you want it to stop halfway through and do something else, two words: "No."
Remember: the return must be a string.
Such as $getFileContent=file_get_contents("index1.xls"); This shows that I have satisfied the handsome man's request.
The prototype of this function is: file_get_contents(path,include_path,context,start,max_length)
Path: The path of the file. Remember to calculate the path from the page where your "code" is finally executed. Here "./" represents the current directory, "../" represents the upper-level directory, "http:/ /www.cnblogs.com/http://www.cnblogs.com/http://www.cnblogs.com/" This represents N-level directories (please count them yourself)
include_path: Many textbooks and online articles include a sentence to fill in 1 if you want to use include_path. Nothing else. I think in this era of rampant copycats, everyone is copying too much. In fact, include_path is a settable environment variable. You can set it with set_include_path or obtain it with get_include_path. What does it do? It's actually very simple. include_path is a bunch of folder paths you set for the convenience of reference or indexing. Taking the above example, if your website is deployed in D:/web/, and there is index.php in it, theoretically your index1..index5.xls will also be placed in D:/web/, so you only need to use file_get_contents("index1.xls"). That's fine, but suppose Qingxiu Man insists that you put it in another directory, that is, not in the website directory,
For example, if it is c:/ BT file of handsome man/, we must not write file_get_contents("c:/BT file of handsome man/index1. The word "male" is so obscene. If the website is transplanted to Linux in the future, it will not run.
The correct way is to modify php.ini
include_path = .:c:/Qingxiu Man’s BT file:./other folders. Just transplant it to Linux and change the configuration file.
In this case, the above program can still be written as file_get_contents ("index1. .
context: This is a god-like parameter. Many textbooks say this: "A set of options that can modify the behavior of the stream." This sentence is even more difficult to understand than the concept of "capitalism" in textbooks and the concept explanation of another similar "ism".
Actually this parameter is like this. file_get_contents can not only read local files, but also web files. If we want to read the homepage source code of www.shenyisyn.org (note: the author's humble studio website), then we will need to set some parameters, such as http parameters:
$options = array(
'http'=>array(
'method'=>'GET',//represents using GET mode to access
'header'=>'Content-Type:text/html;charset=gb2312'.PHP_EOL.//The representative encoding is Chinese gb2312
'Cookie:xxxxx'.PHP_EOL //With cookie, if you want to attack my website, you will probably use it
)
);
$context = stream_context_create($options);
Then you can use file_get_contents("www.shenyisyn.org",0,$context"); to get it directly.
Since it is not recommended to use this function to actually obtain web content, and there is no real crawler or indexing software that uses PHP to do it, there is no further explanation here of how this function is used to obtain remote addresses. PHP should be allowed to do what it is most suitable for, especially when I saw some experts using the PHP desktop runtime library to make desktop software. Jesus Christ’s research spirit is commendable, but I definitely do not recommend that everyone spend too much energy on research. If you have extra time, you can take care of your children and cheat on your wife, or you can discuss together how to "further deepen and develop" the construction of spiritual civilization to be more practical and noble.
start,max_length: Start indexing and get the maximum number of bytes. It's easy to understand but not very useful.
3. PHP_EOL
This knowledge point is still a little important.
n Soft return: In Windows, it means a line break and returns to the beginning of the next line. In Linux and Unix, it only means line break, but it will not return to the beginning of the next line.
r soft space:
In Linux and Unix, it means returning to the beginning of the current line. In Mac OS, it means breaking a line and returning to the beginning of the next line, which is equivalent to the effect of n in Windows.
t tab (move to next column)
They are valid in strings represented by double quotes or delimiters, but not in strings represented by single quotes.
rn is generally used together to represent the Enter key on the keyboard (in Linux and Unix). You can also just use n (in Windows). In Mac OS, use r to represent Enter! t represents the "TAB" key on the keyboard.
Newline symbol in file: windows: n linux, unix: rn
I’ve been talking nonsense for a long time, so I’ll summarize it to ensure the convenience of porting to different platforms in the future. You should use PHP_EOL instead of r or n or rn. PHP will automatically parse it for you on different platforms. Programmers must learn to leave tedious tasks to the system. Don't remember these things that are likely to get mixed up.
4. Other functions for file processing in PHP are briefly listed here, because in general real projects rarely do too many operations on files, so some functions are not used very much. So here are just a few:
file(path,include_path,context) ---Read the file into an array and split it according to newlines. I handed it in last day. This function is really good. For txt files, it can be read directly into an array, saving us the need to separate according to newline characters.
fopen(filename,mode,include_path,context). Open the file and return the handle. Some people may ask what a handle is,
$file=fopen("file name"); This $file is the handle. For example, my name is Shen Yi, I am this file, and my name is the handle. There is no special meaning, don’t be too entangled, otherwise you will easily get up too many times at night.
fwrite(file,string,length). Write file function. You can use Du Niang to see the difference between file_put_contents and this function.
Readfile(filename,include_path,context) This function reads a file and writes it to the output buffer. The characteristic of this function is that it also outputs the number of bytes of the read file. I rarely use it because I used it as the file_get_contents function when I was very good at it. As a result, a strange number always appeared on the page. After reflection day and night, I discovered the clue and was extremely annoyed.
filesize returns the file size (number of bytes). This function is useful, but it will be cached. Why? For example, according to the request of Qingxiu Man, the file size of index1.xls was calculated to be 12306KB. By accident, Qingxiu Man manually added some data to or deleted index1.xls while I was eating. If I finished the meal, I would execute filesize again. ('index1.xls') will find that it is still 12306KB. This is cache. To clear the cache, you need to use clearstatcache(); functions such as
$size=filesize('index1.xls');
echo $size;
.....The handsome man here quietly came to make changes. After making the changes, he irresponsibly went home to wash up and sleep. . . .
clearstatcache();//I must clear the cache.
echo filesize('index1.xls'); //That's it,
The feof(file) function detects whether the end of the file has been reached. It is not commonly used. The official textbook says it is useful for traversing files of unknown length, which is misleading. You should never use PHP to operate files of "unknown length". This is not what PHP should do.
unlink(filename,context) delete file. Stop talking, you will understand even if I don’t understand.
copy(source,destination) copy the file. Just remember one thing: if the file doesn’t exist, it won’t exist. If it exists, it will exist. Anyway, “the decisive one will overwrite it”.
mkdir(path,mode,recursive,context) creates a directory. This is easy to understand. The main thing to note is mode: default full permissions. There is also recursive: whether to be recursive. For example, if you want to create folders with levels like 1/2/3/4/5, the most important thing is that you want to create the folder "5". If this parameter is false, then if the previous 1/2/3/ If 4 is not set, the creation will fail. If true is set, the system will automatically create 1/2/3/4/ for you.
rmdir(path). Delete folder. By the way, this function is still safe. If the folder is not empty, it will not bother you.
Let’s start with this. This article contains most of the PHP file operations. Of course, there are many more. Due to the space, we cannot list them all. You are welcome to add file operation functions that have stories, characteristics, and need to be used with caution. If there are any incomplete, inappropriate, inadequate or nonsense parts in the above, please understand and correct me.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477564.htmlTechArticleMotto for this issue: When databases did not exist, reading and writing files was what we programmers did in the empty nights. One of the only things that can be done (maybe not necessarily~~~). So even now...
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