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 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:
if ( !file_exists("somefile.txt") ) exit("Указанный файл не существует");
Note that the function acts only on local files, that is, if you want to check whether 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.

filesize

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.


file

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



fopen

If the previous function is self-sufficient and in general is not related to other functions, then the subsequent functions of working with files work in conjunction with fopen. This function opens the specified file and returns the connection ID to the file that is used for service purposes. With the contents of the file, this function is not associated 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 for reading its contents only.
    "r +" Open 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.


fgets

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 such 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:
header("HTTP заголовок", необязательный параметр replace);

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

With respect to the header () function, the headers_sent () function is often used, which returns true as a result if the header is successfully sent and false otherwise.

Consider the most commonly used HTTP headers.

Cache-control.

"Cache-control:" value

Heading control caching pages. 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. 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 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:
echo gmdate("D, d MY H:i:s")."GMT";

It is possible to use this HTTP header to disable caching. To do this, you must 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 the Expires header. This title may not be 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:
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 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 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 development of www-technologies and the 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? 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 almost indefinitely.

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, i.e., space, newline characters, etc. are not allowed.

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 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 name and surname of the visitor, which he previously entered in the form field.
$data = $name."||".$surname;
setcookie("username", $data);


Note that the data sent must be formatted as a string, trying to read the previously sent array of values ​​will lead to nothing.

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 in seconds is added to store the cookie. For example, to define 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 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: setcooikie("test 2", "куки с абсолютной датой удаления", mktime(0, 0, 0, 9, 1, 2003);

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:
setcookie("test 3, "", 0, "/mus");

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 correspond 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.
setcookie("my_cookie", $value, time() + 3600 * 24 * 5, "/", ".myphp.dem.ru", 1);

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:
echo "У вас сохранены следующие данные:<br>";
echo $my_cookie;


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.

Delete cookie.
A cookie is deleted by sending a new cookie with the name to be 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 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 Alexander Grimalovsky’s article 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 must be said that PHP has both its own regular expression engine (POSIX) and 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 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 functions of replacing a 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 suffix (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". 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 at 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. $str = "12:57:43 - 10.03.02"; // $str содержит некоторую дату
$str = preg_replace("!(\d{2})\.(\d{2})\.(\d{2})!", "\\2/\\1/\\3", $str);

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:

    \\ 0 - contains the string corresponding to the entire pattern (in our example, "03.10.02").
    \\ 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.
$str = str_replace("-", "", $str); // вырезаем знак "-"
$time = strtotime($str);


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