[Happy to learn php100 days] Day 3: unlimited PHP file operations _ PHP Tutorial

Source: Internet
Author: User
Tags what php
[Happy to learn php100 days] Day 3: unlimited php file operations. This motto: When no database exists in the past, reading and writing files is one of the only tasks that our programmers can do on an empty night (maybe not necessarily ~~~). So even now the motto:

When no database exists in the past, reading and writing files is one of the only tasks that our programmers can do on an empty night (maybe not necessarily ~~~). Therefore, even if this technology is so simple, fast, and common, we still need to maintain a meticulous attitude and strict ethics, and never ignore its importance and rigor.

Body start:

I have a little story about reading files. At the early stage of the studio, when the business was panic, a friend on QQ told me that he had a friend to do a website and introduced it to me. I was so excited that I immediately cut my hair and cut off my cigarette butts, because my friend said that the customer was waiting for a video with me (so busy ?). IT is also said that he is the IT director of a large enterprise and is very formal. I should pay attention to IT and not be too decadent. I took out my electric razor and shaved my beard.

At that time, I liked this kind of thousands of oceans website business. Basically, I made css on the layout interface, with no more than 100 php codes. Just one week for a newbie. Although the reusability and subsequent business expansion are not at all possible, the money for one month of tobacco, alcohol, and tea will surely be enough. Of course, I have to talk about it. let new users talk about it. in the evening, I can only eat spicy food in the food stalls.

The video opened, and a handsome man appeared on the opposite side. the appearance of the face was euphemistic and the vocal cords were very fine. He proudly introduced the factory where he was located, because the development scale was too fast, too fast, and too fast, now I want to build a website (I don't know how fast it is and how big it is) to fit the scale. I finally sent an Excel file to me, and I have drawn the homepage structure of the website, he used to make small software in the company. he was too busy recently, too busy, and too busy. so he wanted to develop a network company this time, at the end of the speech, Qingxiu male told me that he knew the technology very well ~ ".

A cold wind blew through ~~~.

I opened an Excel Project. I admire qingxiu's "sketch" skills. it is rare to draw a picture of the page structure in Excel. I agree and said that I could deliver the product on time. at the same time, I have sent the Excel file to my artist and programmer and asked him to take the photo for three days. However, Qingxiu asked me to almost cover the desktop display. he asked me to paste the pictures and text in the Excel file, then, create multiple workbooks in the Excel file (I was already blind and I don't know whether to use $ sheet or shit to express the "Workbook"). The home page only needs one PHP page, read the workbooks in Excel according to their settings. In this way, the homepage opened by the user is different at intervals. This shows the "diversity" and innovation of their factory business from multiple perspectives.

The smiling face of qingxiu male in the video made me very skeptical about my own design ideas of "configurable and productized. I want to reject this alien thinking, but Qingxiu male insisted on his "concept". He said that his design has been fully "highly praised" by his director.

Thanks to the magic of qingxiu male's "transfer check", I was able to surrender to his "configurable" idea. I just want to say that he is too good. I cannot be the IT supervisor of a large enterprise because I really don't want to use this method to implement template switching in the CMS concept.

Of course, I am not a fool (it is not easy to read Office files). I used a very simple solution to this problem. The transfer cheque was successfully obtained. The method is simple. use the html basic page to design five different Qingxiu male-requested pages and save them as five different Excel files (note: Although the file suffix is xls, but it is actually an html file). use php to read and display the files separately. The code at that time is as follows:

$ FileIndex = rand (); // Obtain a random number ranging from 1 to 5.

$ FileName = 'index'. $ fileIndex. 'XLS '; // piece together a file name. note: From index1.xls....index5.xls to the root directory of the website, it is the same as index. php.

$ GetIndex = file_get_contents ($ fileName); // read the file,

Exit ($ getIndex); // output and display the file content

?>

Here are some knowledge points:

1. rand functions

Random number. the parameter is in the range of rand (minimum value, maximum value ). In this example, a number is randomly generated from 1 to 5. Then splice a file name. For example, index1.xls,index2.xls,index3.xls,index4.xls,index5.xls indicates that I have designed 5 pages for Qingxiu male and saved 5 xls files respectively.

Now that we have talked about the rand function, we have to extend the knowledge point: the array_rand function (array-array we spoke about it in the last day, so we won't go into details here)

The above method can also be used to randomly splice files

$ File = array ("index1.xls", "index2.xls", "index3.xls", "index4.xls", "index5.xls ");

$ FileName = 'index'. $ file [array_rand ($ file, 1)]. 'XLS ';

This indicates that array_rand returns the key value of the input array, and the second parameter indicates the number of returned values. If the value is 1, a character or numeric variable is returned. if the value is greater than 1, an array is returned, which contains two random key values.

2. file_get_contents function

This function is very important. we must remember that it is also a very common function for reading file content. It means reading the content in the file at a time and reading it into an array.

Remember: one time. You cannot interfere with the read process. If you want it to stop and do other things, the two words "no" will not work ".

Remember: the return value must be a string.

For example, $ getFileContent = file_get_contents ("index1.xls"); this indicates that I have met the requirements of qingxiu male.

This function is prototype: file_get_contents (path, include_path, context, start, max_length)

Path: file path. remember to calculate the path from the page where your "code" is executed. Here ". /"indicates the current directory ,".. /"indicates the upper-level directory," http://www.cnblogs.com/http://www.cnblogs.com/http://www.cnblogs.com/ "indicates the N-level Directory (please count it yourself)

Include_path: many textbooks and online articles contain one sentence. if you want to use include_path, enter 1. Nothing else. I think in this age of shanzhai, we copied a lot. In fact, include_path is a configurable environment variable. you can set it using set_include_path or get_include_path. What is the role? in fact, it is very simple. include_path is a bunch of folder paths you have set for reference or indexing convenience. In the preceding example, if your website is deployed on D:/web/, there is an index in it. php. In theory, your index1..index5.xls will also be stored in D:/web/. in this way, you only need to use file_get_contents ("index1.xls") to read data "). however, if Qingxiu male requires you to put it in another directory, that is, not in the website directory,

For example, if it is a c:/Qingxiu male BT file/, we cannot write file_get_contents ("c:/Qingxiu male BT file/index1.xls"). The reason is very simple: in a pure program, the word "Qingxiu male" is so cool that the website cannot run after being transplanted to Linux.

The correct method is to modify php. ini.

Export de_path =.: c:/Qingxiu male BT File:./Other folders. In Linux, just change the configuration file.

In this case, the above program can still be written as file_get_contents ("index1.xls", 1); the same-level file contains no index1.xls, but the system will search for index1.xls in the BT file/under c:/Qingxiu male.

Context: this is a God-like parameter. Many textbooks say this: "A set of options for modifying stream behaviors ". This sentence is more difficult than the concept of "capitalism" in textbooks and the interpretation of another similar concept of "capitalism.

In fact, this parameter is like this. File_get_contents can read not only local files, but also web files. For example, if we want to read the source code of www.shenyisyn.org (note: The author's simple Studio website) homepage, we need to set some parameters, such as http parameters:

$ Options = array (

'Http' => array (

'Method' => 'GET', // indicates access in GET mode.

'Header' => 'Content-Type: text/html; charset = gb2312 '. PHP_EOL. // indicates that the encoding is Chinese gb2312.

'Cookie: xxxx'. PHP_EOL // with Cookie. if you want to attack my website, it is very likely to be used.

)

);

$ Context = stream_context_create ($ options );

Then you can use file_get_contents ("www.shenyisyn.org", 0, $ context "); to get it directly.

It is not recommended to use this function to obtain webpage content, and there is no real crawler or the indexing software will use php to do so, therefore, there are not many extensions to explain how this function is used to obtain remote addresses. Php should let it do what it is most suitable for. in particular, I have seen some Daniel use the php desktop runtime library to do desktop software. The study spirit of Jesus Christ is commendable, however, we do not recommend that you spend too much effort on research. There is extra time to cheat your wife with your children, or you may discuss how to "further deepen and develop" The Spiritual Civilization Construction to be more practical and noble.

Start, max_length: start indexing and obtain the maximum number of bytes. It's easy to understand, but it's useless.

3. PHP_EOL

This knowledge point is a little important.

\ N soft carriage return: indicates a line break in Windows and returns to the start position of the next line. In Linux and unix, it only indicates line breaks, but does not return to the starting position of the next line.

\ R soft space:

In Linux and unix, return to the starting position of the row. In Mac OS, line breaks are displayed and returned to the start position of the next line, which is equivalent to \ n in Windows.

\ T hop (move to the next column)

They are valid in double quotes or delimiters, and are invalid in single quotes.

\ R \ n is generally used together to represent the carriage return key (in Linux and Unix) on the keyboard. \ n (in Windwos) can also be used only, and \ r is used to represent the carriage return in Mac OS! \ T indicates the "TAB" key on the keyboard.

File line break: windows: \ n linux, unix: \ r \ n

I 've been talking nonsense for a long time. to sum up, I want to ensure the convenience of porting to different platforms in the future. You should use PHP_EOL to replace \ r or \ n or \ r \ n. PHP to automatically resolve the issue on different platforms. Programmers must learn to give tedious tasks to the system. Do not remember these things that may be confusing.

4. other functions for file processing in PHP, which are briefly listed here, are rarely used to perform too many operations on files in real projects. Therefore, some functions are not really used. So the following is just a list:

File (path, include_path, context) --- read the file and read it as an array, which is separated by line breaks. I handed in the last day. This function is really good. for txt files, it can be directly read into arrays, saving us the need to separate them based on line breaks.

Fopen (filename, mode, include_path, context). open the file and return the handle. Someone will ask what is a handle,

$ File = fopen ("file name"); this $ file is the handle. For example, my name is Shen Yi, I am the file, and my name is the handle. There is no special meaning. do not tangle too much; otherwise, it is easy to get up too many times at night.

Fwrite (file, string, length). write the file function. You can see the difference between file_put_contents and this function through du Niang.

Readfile (filename, include_path, context) this function reads a file and writes it to the output buffer. this function also outputs the number of bytes to read the file. I rarely use it because I used to treat it as a file_get_contents function. as a result, there was always a strange number on the page. after my day and night reflection, I found a clue, very upset.

Filesize returns the file size (number of bytes). This function is useful, but it will be cached. Why? Or 12306KB. This is the cache, clear the cache needs to use clearstatcache (); functions such

Inclusizeinclufilesize('index1.xls ');

Echo $ size;

Here, Qingxiu male quietly modified it. after the modification, she went home very irresponsibly and went to bed ....

Clearstatcache (); // you must clear the cache.

Echo filesize('index1.xls '); // This is correct,

The feof (file) function checks whether it has reached the end of the file. It is not commonly used. it is misleading and useful for traversing unknown length files in official textbooks. Php should never be used to operate some "unknown length" files. this is not what php should do.

Unlink (filename, context) deletes a file. If you don't understand it, you will understand it.

Copy (source, destination. Remember: if there is no file, there will be one. if there is no file, there will be one. a single sentence will be overwritten decisively ".

Mkdir (path, mode, recursive, context) to create a directory. This is easy to understand. pay attention to mode: all permissions are granted by default. There is also recursive: whether to recursion. For example, if you want to create a folder at the level of 1/2/3/4/5, the most important thing is to create the "5" folder. If this parameter is false, if the preceding values are not set to 1/2/3/4, the creation fails. if the value is set to true, the system automatically creates the values 1/2/3/4.

Rmdir (path). delete the folder. This function is safe. If the folder is not empty, it will not bird you.

Write so much first. This includes most of the operations on php files. of course, there are many other File operation functions. due to the limited space, you are welcome to add File operation functions with stories, features, and caution. If any part of the above is missing, inappropriate, inadequate, or nonsense, please forgive and correct it.

When there was no database in the past, reading and writing files was one of the only tasks that our programmers could do on an empty night (maybe not necessarily ~~~). So even now...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.