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

PHP Session (Files, directories and PHP, Working with files)

Before you perform operations on a file, you often need to make sure that the specified file exists at all. This is the function of file_exists. 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:
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 got a robot.txt file, then your efforts will be useless. But it is possible to check any file on the local server, regardless of the directory of its location.


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


This function already works directly with the file. It returns the contents of the specified file, and it does this as an array, where each of its elements is the file's string. The function is useful when you need to store several different values ​​in one file, which should not overlap. Then each value is stored on a separate line and read by the function file, which returns an array, so that the reference to 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 one variable. This is done using the function of working with implode arrays. $text_file = implode("", file("somefile"));
echo $text_file;


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 that anyone likes, since one character is equal to one byte). But keep in mind that unlike file, this function does not provide for assigning the read contents of a variable file. If you try to do this, only the number of characters read will be assigned to the variable. $bytes = readfile ("somefile");
echo "Итого - ".$bytes." символов";


If the previous function is self-contained and generally unrelated to other functions, the subsequent functions of working with files work in conjunction with fopen. This function opens the specified file and returns the connection id of the file that is used for business purposes. With the contents of the file, this function is not linked in any way.

The fopen function has several modes of working with the file. They are specified after the file name and represent 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 writing.
    "w +" Open the file for reading and writing.
    "a" The file is opened for writing to the end of the file (additional recording).
    "a +" Opens for dubbing and reading.


Function of reading a file opened by the function fopen. But unlike file, this function returns only one line of the file for each time it executes, and it moves the internal file pointer to the next line, which it will read the next time it accesses the function. Therefore, if you need to read the entire file, you need to use this function in the loop.

Note that the fgets function uses the optional length parameter, which specifies the maximum length of the line of the file to read. If the volume of the string exceeds this number, then the function returns it in the "truncated" form by the volume in the number of length bytes. By default, this parameter is set to 1024 bytes, or one kilobyte. Especially pay attention to this parameter if you use large files, because when reading such files the PHP execution buffer may overflow (its volume is specified in the configuration file), which will lead to a hangup.

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 as special headers.

Thus, HTTP headers is a means of communicating a server with a remote client. Each header usually consists of a single ASCII line of text with a name and value. The headers themselves are not displayed in the browser window, but they can often greatly alter the display of the accompanying document.

The mechanism of 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 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:
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.

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

Consider the most used HTTP headers.


"Cache-control:" value

Header of caching pages. In general, this function is one of the most common in use headers.

This header can be used with the following values:

* no-cashe - Prohibition of caching. Used in frequently updated pages and pages with dynamic content. Its operation is similar to the META tag "Pragma: no-cache".
* public - Allows caching of the page by both the local client and the proxy server.
* private - Enable caching only by local client.
* max-age - Enables the use of a cached document within a specified time in seconds. header("Cache-control: private, max-age = 3600") /* Кеширование локальными клиентами и использование в течение 1 часа */


"Expires:" HTTP-date

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

Day of the Week (abbr.) Number (2 digits) Month (abbreviated) 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 function gmdate () in the following form:
echo gmdate("D, d MY H:i:s")."GMT";

It is possible to use this HTTP header to disable caching. To do this, you need to specify the past date.


"Last-Modified:" HTTP-date

Indicates the date the document was last modified. Date must be specified in the same format as in the case of the header Expires. This header can not be used for dynamic pages, since many servers (for example, Apache) for such pages themselves expose the modification date.

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


"Location:" absolute URL

A useful title that redirects the browser to the specified address. Its action is comparable to the META tag Refresh:

For example, this header can be used like this:
if ($login != $admin_login) header("Location:");
else header("Location:$login");

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

PHP and HTTP: cookie.

In the previous lesson, we disassembled the relationship between the HTTP protocol and the PHP language at the level of HTTP headers. In this lesson we will get acquainted with one more specific HTTP header - cookie.

What are cookies?
The point is that in the process of development of www-technologies and introduction of programming languages ​​on the Internet, software developers faced a very serious problem - how to save the results of the algorithm for each particular user for a long time? By itself, the HTTP protocol does not have the ability to capture the results of software processes. The use of sessions is also not a solution, since their action is terminated immediately after the connection to the server is disconnected.

The problem was resolved with the introduction of the mechanism of cookies (that is, in translation from 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.

In essence, 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 into this directory (quick access to it for IE browser is done through the menu items Service -> Internet Options -> Temporary Internet Files -> Settings -> View Files).

Implementation of the mechanism of cookies in PHP.
The implementation of the cookies mechanism is represented by the only function setcookie (). As with HTTP headers, this function must be called before sending any data to the remote client, even "empty" characters, that is, a space, newlines, and so on, are not allowed.

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

All parameters, except the name of the cookie, are optional. If a cookie is sent only with this parameter, it is immediately destroyed by the remote client, so this parameter alone does not carry the information load. A fully-functional cookie makes the following two parameters: the value stored in the cookie, and the time to which this cookie can be used.

The value that the cookie carries is any string of ASCII characters. For example, you can set a cookie with the name and surname of the visitor, which he previously entered into 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 previously sent out array of values ​​will lead to nothing.

The cookie set in the above example will be destroyed immediately after the user closes the browser, because by default the cookie's lifetime is set to zero. To change this order, you must specify the third expire parameter. The definition of this parameter can be made in two ways:

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

* The second way is to set the absolute expiry date for the cookie. It is set using the mktime () function, which returns a specific date to delete the cookie. If you want to set the cookie lifetime before midnight on September 1, 2003, you should define the cookie as follows: setcooikie("test 2", "куки с абсолютной датой удаления", mktime(0, 0, 0, 9, 1, 2003);

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

We set the cookie by omitting the value and time parameters and defining the scope of all paths starting with the line "/ mus", that is, the directory "/ music /" and "/ museums /". To uniquely determine the path, you must complete the path with a slash. That is, to limit the effect of the cookie to the "/ mus" directory, you would write in the "/ mus /" parameter.

The next optional parameter is the parameter for determining the action of the cookie within the specified domain. And the value of this parameter "" corresponds only to the site with the address , and the value "" matches already and , and http: //mail.someserver. com , and , that is, all domains ending with this line.

The last parameter of the setcookie () function indicates that the cookie must be sent over a secure connection (HTTPS). This parameter is required when installing a cookie with confidential data.
setcookie("my_cookie", $value, time() + 3600 * 24 * 5, "/", "", 1);

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

Access to data stored in the cookie can also occur 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.

Delete the cookie.
The cookie is deleted by sending a new cookie with the name of the cookie to be deleted without any additional parameters.

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

Regular applications.

This lesson does not fit into the logical chain of our studies, but was created "under the pressure of the public", that is, at the request of the readers, and will be devoted to the regular expressions and functions of working with them. Probably, my calculations that the articles of Alexander Grimalovsky "Regular Expressions" will be enough to understand this topic turned out to be wrong.

So, hoping that you have already read the above article, we begin today's lesson.

The regular expressions themselves are not a novelty, introduced by 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 template that is used for various actions, depending on the function that uses this regular expression. Special characters are used to specify a template.

Functions of working with regular expressions.
It must be said that PHP has both its own mechanism for working with regular expressions (POSIX), and borrowed from another server programming language Perl. Externally, they can easily be distinguished by the names of functions: functions of the first type begin with the characters "ereg", and the second - "preg".

But the names of functions 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 of replacing part of a string with regular expressions. Note the pattern of the preg_replace function: the slashes here are the slashes, with the i modifier following the closing delimiter indicating that the pattern is case insensitive. The same effect is achieved when using the POSIX function with the suffix i (eregi_replace).

The function preg_replace in our example showed the so-called "greed", and covered the entire line, which begins with the letter "p" and ends with "e". Make 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 function eregi_replace also showed "greed", but this order can no longer be changed, since POSIX-functions do not use modifiers.

Examples of regular expressions.

Time conversion in standard Unix time.

Suppose we have a date in the database or another source in the following format:
hours: minutes: seconds - day.month.year
But for some reason (for example, redesigning the site), we needed to display the date in the following form:
day.month.year hours: minutes

As you know, it's crazy to do it manually, so write a script that will bring the date to the form: hours: minutes: seconds a month / day / year, and then use strtotime () to translate this entry at standard UNIX time , which we can display as you want.

The most interesting is the first stage. It's something that 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 the regular expression, we change the format of the day, month, and year records, and each element is separated by brackets. In the second parameter of the function, we refer to the matches found in brackets. Here's how it happens:

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

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