This page has been robot translated, sorry for typos if any. Original content here.

PHP Session (Files, Directories and PHP, Working with Files)



file_exists
Before performing operations on 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, using this function looks like this:
if ( !file_exists("somefile.txt") ) exit("Указанный файл не существует");
Note that the function only works on local files, that is, if you want to check if Yandex has acquired a robot.txt file, then your efforts will be in vain. But then it is possible to check any file lying on the local server regardless of its location directory.

filesize

As the name implies, the function determines the size of the file and returns it in bytes. It is useful if you want to check the file for information in it (as you know, an empty file contains 0 bytes), and it is also possible to check the file size for exceeding a certain limit.


file

This function already works directly with the file. It returns the contents of the specified file, and it does this in the form of an array, where each of its elements is a line in the file. This function is useful when you need to save several different values ​​in a single file 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 specified variable is accessed 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 a single variable. This is done using the implode array function. $text_file = implode("", file("somefile"));
echo $text_file;



readfile

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 equal to 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, only the number of characters read will be assigned to the variable. $bytes = readfile ("somefile");
echo "Итого - ".$bytes." символов";



fopen

If the previous function is self-sufficient and in general is not connected with other functions, then the subsequent functions of working with files work in conjunction with fopen. This function opens the specified file and returns the identifier of the connection to the file, which is used for official purposes. This function is not associated with the contents of the file in any way.

The fopen function has several modes of working with a file. They are indicated after the file name and are the following notation:
    "r" The file is opened only for reading its contents.
    "r +" Open the file for both reading and writing.
    "w" The file is opened for recording.
    "w +" Open the file for reading and writing.
    "a" The file is opened for writing to the end of the file (rewriting).
    "a +" Opens for recording and reading.


fgets

The read function of a file opened by the fopen function. But unlike file, this function returns only one file line at a time, while it moves the internal file pointer to the next line, which it will read the next time the function is called. Therefore, if you need to read the entire file, you must use this function in a loop.

Note that the fgets function uses the optional length parameter, which specifies the maximum length of the file line to read. If the line volume exceeds this number, the function will return it in a "truncated" form with a volume of length bytes. By default, this parameter is set to 1024 bytes, or one kilobyte. Moreover, pay attention to this parameter if you use large files, since when reading such files the PHP runtime buffer may overflow (its size is indicated in the configuration file), which will lead to a hang.



PHP and HTTP: headers



PHP, being a web programming language, 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 are 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 often can 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 header () function. The peculiarity of the HTTP protocol is that the header must be sent before sending other data, so the function should be called at the very beginning of the document and should look like this:
header("HTTP заголовок", необязательный параметр replace);

The optional replace parameter can take values ​​of type bool (true or false) and indicates whether the previous header of a similar type should be replaced, or add this header to an existing one.

For the header () function, the headers_sent () function is often used, which returns true if the header was sent successfully and false otherwise.

Consider the most used HTTP headers.

Cache control

"Cache-control:" value

The page caching control header. In general, this function 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 operation is similar to the META tag "Pragma: no-cache".
* public - Enables page caching by both the local client and proxy server.
* private - Allow caching only by the local client.
* max-age - Allow the use of a cached document for a specified time in seconds. header("Cache-control: private, max-age = 3600") /* Кеширование локальными клиентами и использование в течение 1 часа */

Expires

"Expires:" HTTP-date

Sets the date and time after which the document is considered obsolete. The date should be indicated in the following format (in English):

Day of the week (abbr.) Day (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 in the following form:
echo gmdate("D, d MY H:i:s")."GMT";

You can use this HTTP header to disable caching. To do this, specify the past date.

Last-Modified.

"Last-Modified:" HTTP-date

Indicates the date the document was last modified. The date must be in the same format as with the Expires header. This header can not be used for dynamic pages, since many servers (for example, Apache) for these pages themselves set the modification date.

It is possible to make the page always updated:
header("Last-Modified: ".gmdate("D, d MY H:i:s")." GMT");

Location.

"Location:" absolute URL

A useful header that redirects the browser to the specified address. Its action is comparable to the META Refresh tag:
<META HTTP-EQUIV="Refresh" CONTENT="0; URL=someURL">

For example, this header can be used like this:
if ($login != $admin_login) header("Location: http://www.server.com/login.php");
else header("Location: http://www.server.com/admin.php?login=$login");

if (!headers_sent()) exit("Произошла ошибка! Пройдите <a href='http://www.server.com/login.php'>авторизацию</a> заново");



PHP and HTTP: cookie.



In the previous lesson, we examined 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 ​​on the Internet, a very serious problem arose for program 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. Using sessions is also not a solution to the problem, since their action stops immediately after disconnecting from the server.

The problem was resolved with the introduction of the cookie mechanism (that is, in translation from English, “cookies”). Cookies have a wonderful property - they are stored on the user's hard drive and can be stored there for virtually unlimited time.

At its core, cookies are ordinary 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 browser provides quick access to it through the Tools menu items -> Internet Options -> Temporary Internet Files -> Settings -> Browse Files).

Implementation of cookies mechanism in PHP.
The implementation of the cookie 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, space, line feed characters, and so on.

The function has the following syntax:
setcookie(имя куки, значение, срок годности, информация о пути, домен, защищенность)

All parameters except the cookie name are optional. If a cookie is sent only with this parameter, then it is immediately destroyed by the remote client, so this parameter in itself does not carry an information load. The following two parameters make a fully functional cookie: the value embedded in the cookie, and the time until which this cookie can be used.

The value that the cookie carries can be any string of ASCII characters. For example, you can set a cookie with the first and last name of the visitor that he previously entered in the form field.
$data = $name."||".$surname;
setcookie("username", $data);


Note that the data sent must be in the form of a string, an attempt 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 user closes the browser, since by default the cookie lifetime is set to zero. To change this order, you need to specify the third parameter expire. The definition of this parameter can be done in two ways:

* Set the relative validity period using the time () function, to which the time in seconds is added to store the cookie. For example, to determine a cookie for two hours, you need to write: setcookie("test 1", "это тестовая куки", time() + 3600 * 2); // 3600 - количество секунд в часе setcookie("test 1", "это тестовая куки", time() + 3600 * 2); // 3600 - количество секунд в часе

* The second way is to set the absolute expiration date of the cookie. It is set using the mktime () function, which returns the specific date the cookie was deleted. If you want to set the cookie's life time until midnight September 1, 2003, you should define the cookie like this: setcooikie("test 2", "куки с абсолютной датой удаления", mktime(0, 0, 0, 9, 1, 2003);

An optional path parameter limits the scope of the cookie within certain directories. Moreover, this path includes all paths starting with a value in this parameter. For example:
setcookie("test 3, "", 0, "/mus");

We set the cookie by skipping the value and time parameters and determining the scope by all the paths starting with the line "/ mus", that is, the directory "/ music /" and "/ museums /" are included. To uniquely identify a path, you must end the path with a slash. That is, to limit the effect of cookies to the directory "/ mus", it was necessary to write in the parameter "/ mus /".

The next optional parameter is the parameter for determining the action of cookies 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 ".someserver.com" corresponds to both http://someserver.com and http: //mail.someserver. com , and http://my-someserver.com , that is, all domains ending with this line.

The last parameter to the setcookie () function indicates that this cookie should be sent over a secure connection (HTTPS). This parameter is necessary when setting a cookie with confidential data.
setcookie("my_cookie", $value, time() + 3600 * 24 * 5, "/", ".myphp.dem.ru", 1);

Reading cookie.
The set cookie is accessed through its name. For example, continuing the example above, you can read the cookie as follows:
echo "У вас сохранены следующие данные:<br>";
echo $my_cookie;


The data stored in the cookie can also be accessed through 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.

Removing a cookie.
Deleting a cookie is done by sending a new cookie with the name of the cookie being deleted without any additional parameters.

For example:
$data = $my_cookie;
setcookie("my_cookie");
echo "Следующие данные были удалены:<br>" . $data;

Regular applications.



This lesson does not fit into the logical chain of our classes, but was created "under pressure from the public," that is, at the request of readers, and will be devoted to regular expressions and the 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 have been used for quite a long time and are a very powerful mechanism for working with string data.

A regular expression is a kind of pattern that is used for various actions depending on the function that uses this regular expression. Special characters are used to set the pattern.

Regular expression functions.
It must be said that PHP has both its own regular expression engine (POSIX) and borrowed from another server programming language Perl. Outwardly, they are easy to distinguish by function names: 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 syntax of regular expressions. So, Perl-like functions require delimiters: $str = "регулярное выражение"; // просто строка
$preg = preg_replace("/р.+е/i", "<i>[вырезано]</i>", $str);
$ereg = eregi_replace("р.+е", "<i>[вырезано]</i>", $str);
echo $preg."<br>".$ereg;
$str = "регулярное выражение"; // просто строка
$preg = preg_replace("/р.+е/i", "<i>[вырезано]</i>", $str);
$ereg = eregi_replace("р.+е", "<i>[вырезано]</i>", $str);
echo $preg."<br>".$ereg;

As you can see, we use the function to replace part of a string with regular expressions. Pay attention to the preg_replace function template: slashes act here as a separator, and after the closing separator there is a modifier i indicating that the template is case-insensitive. The same effect is achieved when using the POSIX function with the suffix i (eregi_replace).

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". U modifier helps to make the function not “greedy”.

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 cannot be changed anymore, since modifiers are not provided for in POSIX functions.

Examples of regular expressions.

Converting time 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 in the following form:
day.month.year hours: minutes

As you know, manually doing this is crazy, so we’ll write a script that will first bring the date to the form hours: minutes: seconds month / day / year, and then use the strtotime () function to translate this record to UNIX standard time which we can display as we want.

The most interesting is the first stage. He is what interests us in terms of using regular expressions. $str = "12:57:43 - 10.03.02"; // $str содержит некоторую дату
$str = preg_replace("!(\d{2})\.(\d{2})\.(\d{2})!", "\\2/\\1/\\3", $str);

Using a regular expression, we change the recording format of the day, month, and year, and each element is separated by brackets. In the second parameter of the function, we refer to the matches found in parentheses. Here's how it goes:

    \\ 0 - contains a string that matches the entire pattern (in our example, "10.03.02").
    \\ 1 - contains characters that correspond only to the first element enclosed in brackets (that is, "10").
    \\ 2 - contains characters that correspond only to the second element enclosed in brackets (that is, "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.
$str = str_replace("-", "", $str); // вырезаем знак "-"
$time = strtotime($str);


Now you can use the $ time variable as you like.