PHP Session (Files, directories and PHP, Working with files)
Before making operations with a file, it is often necessary to make sure that the specified file exists at all. This is what the file_exists function does. This function can return only two values, as you understand, TRUE (if the specified file exists) and FALSE. Usually the use of this function looks like this:
Note that the function acts only on local files, that is, if you want to check if Yandex has acquired the robot.txt file, then your efforts will be in vain. But it is possible to check any file lying on the local server, regardless of the directory of its location.
As the name implies, the function determines the file size and returns it in bytes. It is useful if you want to check the file for information in it (as you understand, an empty file contains 0 bytes), and it is also possible to check the file size to exceed a certain limit.
This function already works directly with the file. It returns the contents of the specified file, and it does so in the form of an array, where each of its elements is a string of the file. The function is useful when in the same file you need to save several different values that should not overlap. Then each value is stored on a separate line and read by the file function, which returns an array, as a result of which the reference to the specified variable occurs by reading the value of the array element with the index corresponding to the line in the file.
In addition, it is possible to reunite all elements of the returned array into one variable. This is done using the implode array function.
Like the previous function, readfile displays the contents of the specified file, and also returns the number of characters in the file (or the number of bytes, as you like, since one character is one byte). But note that, unlike file, this function does not provide for assigning the read contents of a file to a variable. If you try to do this, the variable will be assigned only the number of characters read.
If the previous function is self-sufficient and in general is not related to other functions, then the subsequent file handling functions work in conjunction with fopen. This function opens the specified file and returns the ID of the connection with the file that is used for business purposes. This function is not associated with the contents of the file.
The fopen function has several modes of operation with a file. They appear after the file name and are the following notation:
"r +" Opening a file for both reading and writing.
"w" The file is opened for the purpose of recording.
"w +" Open file for reading and writing.
"a" The file is opened for writing to the end of the file (record).
"a +" Opens for recording and reading.
The function of reading the file opened by the fopen function. But unlike file, this function for each time of its execution returns only one line of the file, while it moves the internal file pointer to the next line, which it reads the next time the function is accessed. Therefore, if you need to read the entire file, you must use this function in a loop.
Notice that the fgets function uses the optional parameter length, which indicates the maximum length of the file string to be read. If the volume of the string exceeds this number, the function will return it in a "truncated" form of one-byte length. By default, this parameter is set to 1024 bytes, or one kilobyte. Moreover, pay attention to this parameter if you are using large files, since reading these files may overflow the PHP execution buffer (its size is indicated in the configuration file), which will cause a hang.
PHP and HTTP: headers
PHP, being the language of web programming, supports the implementation of the mechanism for sending HTTP headers.
First, let's say a few words about the HTTP headers themselves.
In accordance with the HTTP specification, this protocol supports the transfer of service information from the server to the browser, designed in the form of special headers.
Thus, HTTP headers is a means of communication between a server and a remote client. Each heading usually consists of a single line of ASCII text with a name and value. The headers themselves are not displayed in any way in the browser window, but they can often greatly change the display of the accompanying document.
The mechanism for sending HTTP headers in PHP.
The mechanism for sending headers in PHP is represented by the function header (). The peculiarity of the HTTP protocol is that the header should be sent before sending other data, so the function should be called at the very beginning of the document and should look like this:
The optional replace parameter can take values of the bool type (true or false) and indicates whether the previous header of this type should be replaced, or add this header to the existing one.
Regarding the header () function, the headers_sent () function is often used, which returns true as a result if the header was successfully sent and false otherwise.
Consider the most commonly used HTTP headers.
The header of the page caching control. In general, this feature is one of the most common headers to use.
This header can be used with the following values:
* no-cashe - Disable caching. Used in frequently updated pages and pages with dynamic content. Its action is similar to the META tag "Pragma: no-cache".
* public - Allow page caching by both local client and proxy server.
* private - Allow caching only by the local client.
* max-age - Allowing a cached document to be used for a specified time in seconds.
Sets the date and time after which the document is considered obsolete. The date should be in the following format (in English):
Day of the week (abbr.) Number (2 digits) Month (abbr.) Year hours: minutes: seconds GMT
For example, Fri, 09 Jan 2002 12:00:00 GMT
The current time in this format is returned by the gmdate () function as follows:
It is possible to use this HTTP header to disable caching. To do this, you must specify the past date.
Indicates the date the document was last modified. The date must be in the same format as the Expires header. This header can be not used for dynamic pages, since many servers (for example, Apache) set the modification date for such pages themselves.
It is possible to make the page always updated:
"Location:" absolute URL
A useful header that redirects the browser to the specified address. Its effect is comparable to META Refresh tag:
For example, this header can be used like this:
PHP and HTTP: cookie.
In the previous lesson we explored the relationship between the HTTP protocol and the PHP language at the level of HTTP headers. In this lesson, we will introduce another specific HTTP header - cookie.
What are cookies?
The fact is that in the process of developing www-technologies and introducing programming languages to the Internet, a very serious problem arose for software developers - how to save the results of the algorithm for each particular user for a long time? The HTTP protocol itself does not have the ability to capture the results of software processes. The use of sessions is also not a solution to the problem, since their action ceases immediately after the connection with the server is disconnected.
The problem was resolved with the introduction of the cookies mechanism (that is, in English, “cookies”). Cookies have a remarkable property - they are stored on the user's hard drive and can be stored there for almost unlimited time.
At their core, cookies are plain text files stored in a special directory used by the browser (usually this folder is called Temporary Internet Files), and you can see them by going to this directory (IE allows quick access to it through the Tools menu). -> Internet Options -> Temporary Internet Files -> Settings -> View Files).
The implementation of cookies in PHP.
The implementation of the cookies mechanism is represented by a single setcookie () function. As in the case of HTTP headers, this function must be called before sending any data to the remote client, even "empty" characters are not allowed, that is, a space, newline characters, and so on.
The function has the following syntax:
All parameters, except the name of the cookie, are optional. If a cookie is sent only with this parameter, then it is immediately destroyed by the remote client, so by itself this parameter does not carry any information load. A full-featured cookie is made by the following two parameters: the value set in the cookie and the time until which this cookie can be used.
The value that carries the cookie can be any string of ASCII characters. For example, you can set a cookie with the first and last name of the visitor, which he previously entered in the form field.
Note that the data sent should be formatted as a string, trying to read the array of values sent earlier will not lead to anything.
The cookie set in the above example will be destroyed immediately after the browser is closed by the user, since the default cookie lifetime is set to zero. To change this order, you must specify the third parameter expire. This parameter can be determined in two ways:
* Set the expiration date using the time () function to which the time is added in seconds to store the cookie. For example, to define a cookie for two hours you need to write:
* The second method is setting the absolute expiration date of the cookie. It is set using the mktime () function, which returns a specific date for deleting cookies. If you need to set a cookie's lifetime until midnight on September 1, 2003, you should define a cookie like this:
An optional path parameter limits the scope of cookies within certain directories. Moreover, this area includes all paths starting with the value in this parameter. For example:
We set the cookie, skipping the value and time parameters and defining the scope in all ways starting with the string "/ mus", that is, this includes the directory "/ music /" and "/ museums /". To uniquely identify the path, you must complete the path with a slash. That is, to limit the cookie to the "/ mus" directory, it was necessary to write in the "/ mus /" parameter.
The next optional parameter is the option to define a cookie action within the specified domain. Moreover, the value of this parameter "someserver.com" corresponds only to the site with the address http://someserver.com , and the value of ".someserver.com" already corresponds to both http://someserver.com and http: //mail.someserver. com , and http://my-someserver.com , that is, all domains ending in a given string.
The last parameter of the setcookie () function indicates that this cookie should be sent over a secure connection (HTTPS). This parameter is required when setting a cookie with confidential data.
Reading a cookie.
Appeal to the set cookie goes through its name. For example, continuing the example above, you can read the cookie as follows:
Accessing data stored in a cookie can also occur via the $ HTTP_COOKIE_VARS array. It is similar to other similar arrays, such as $ HTTP_POST_VARS and others, and contains all the values read from the cookie.
A cookie is deleted by sending a new cookie with the name to be deleted without any additional parameters.
This lesson does not fit into the logical chain of our classes, but was created "under public pressure", that is, at the request of readers, and will be devoted to regular expressions and functions of working with them. Probably, my calculations that the article by Alexander Grimalovsky "Regular expressions" would be enough to understand this topic turned out to be incorrect.
So, hoping that you have already read the above article, we begin today's lesson.
Regular expressions themselves are not new to PHP. In one form or another, they are used for quite a long time and are a very powerful mechanism for working with string data.
A regular expression is a pattern that is used for various actions depending on the function that uses this regular expression. Special characters are used to set the pattern.
Functions for working with regular expressions.
It is necessary to say that PHP has its own regular expression engine (POSIX), and it is borrowed from another Perl server programming language. Outwardly, they are easy to distinguish by function name: functions of the first type begin with the characters "ereg", and the second - "preg".
But function names are not their only difference. First of all, they contain some differences in the regular expression syntax. So, Perl-like functions require delimiters:
As you can see, we use the function of replacing part of a string using regular expressions. Notice the preg_replace function template: the slashes appear here as the separator, with the modifier i following the closing separator, indicating that the template is case-insensitive. The same effect is achieved when using the POSIX function with the i (eregi_replace) suffix.
The preg_replace function in our example showed the so-called "greed", and covered the entire line that begins with the letter "p" and ends with "e". Making the function not "greedy" helps modifier U.
The function found the minimum distance between the letters "p" and "e" and replaced it with the specified string.
The eregi_replace function also showed "greed", but this order can no longer be changed, since POSIX functions do not provide for the use of modifiers.
Regular expressions examples.
Time conversion to standard Unix time.
Suppose we have a date in the database or in another source in the following format:
hours: minutes: seconds - day.month.year
But for some reason (for example, the site was redesigned), we needed to display the date as follows:
day.month.year hours: minutes
As you understand, manually doing this is crazy, so we’ll write a script that in the first stage will bring the date into hours: minutes: seconds month / day / year, and then use the strtotime () function to convert this entry to standard UNIX time which we can display as we like.
The most interesting is the first stage. He is interested in the use of regular expressions.
With the help of a regular expression, we change the format of the day, month and year, with each element separated by brackets. In the second parameter of the function, we refer to the matches in parentheses. Here’s how it happens:
\\ 1 - contains characters that correspond only to the first element enclosed in brackets (i.e. "10").
\\ 2 - contains characters that correspond only to the second element enclosed in brackets (i.e. "03").
and so on.
At this stage we will get the date "12:57:43 - 03/10/02". Now we bring it to the end.
Now you can use the $ time variable as you like.