Logbook. Should you upgrade to PHP7? What if I can't update


So, you have an old, but very sweet-hearted site, which you decide out of pity (or, perhaps, after re-reading Habr) to translate into PHP7. Expecting a dramatic boost in performance, you dust off the poor site and decisively switch the PHP version in your hosting control panel.

If the site is not young for a long time, then with a high degree of probability a miracle will not happen. At best, all sorts of errors will start to appear, and at worst, you will see a white screen, the Zen of web development. At this moment, you want to quickly switch everything back and forget about your sudden weakness.

But suppose your forte is persistence, and you also have some time to experiment. Let's try to fix everything.

Backups

We make backup copies of the site (as well as databases). After all, who doesn't make backups is his own enemy, right? For all sorts of experiments, it makes sense to add another site on the hosting and copy the files that we will now edit into it.

Error logs

Let's configure PHP error logging to the .htaccess file (if it was not configured earlier):

php_value display_errors 0
php_value log_errors 1
php_value error_log /home/vasya/domains/mysite.ru/logs/error.log

Working with MySQL

Let's say the site uses databases and you see errors like this:

Fatal error: Uncaught Error: Call to undefined function mysql_connect ()

This is because the original MySQL extension is not supported in modern PHP versions (since PHP 5.5.0). The developers recommend using MySQLi or PDO. Let's try to switch to MySQLi, it's simple:

Suppose that the site is written using a procedural approach, which is a classic shit code by many and is now considered a concise and effective solution. In such a case, the following is a deprecated construct for connecting to a database:

$ link = mysql_connect ('localhost', $ user, $ password)
mysql_select_db ($ dbname, $ link)
mysql_query (‘set names cp1251’)

can be replaced with:

$ link = mysqli_connect (‘localhost’, $ user, $ password, $ dbname)
mysqli_query ($ link, ‘set names cp1251’)

for queries:

$ result = mysql_query ($ query, $ cid)

replaced by:

$ result = mysqli_query ($ cid, $ query)

Other popular functions easily change to their ‘i’ counterparts:

mysqli_fetch_array ()
mysqli_fetch_row ()
mysqli_fetch_assoc ()
mysqli_fetch_array ()
mysqli_num_rows ()
mysqli_insert_id ()
mysqli_close ()

As a result of these simple actions, data from the database should be successfully collected and sent.

Encoding

Real old school is a site at CP1251 (at least). Has everything turned into diamonds or other scabies?

Most likely, it will be enough to specify the encoding in .htaccess like this:

php_value default_charset "cp1251"

Regular Expressions

You can also observe errors of the following kind:

Warning: preg_replace (): The / e modifier is no longer supported, use preg_replace_callback instead

This means that the / e modifier, which allowed passing the result of a regular expression to an arbitrary function, is no longer supported. In such cases, it is recommended to use the preg_replace_callback function

Let's say we have a regular expression like this:

$ string = preg_replace ("/: ((1,10)): / e", "print_smile ('\\ 1' ')", $ string)

replaced with preg_replace_callback, it should look like this:

$ string = preg_replace_callback ("/: ((1,10)): /", create_function (‘$ matches’, ‘return print_smile ($ matches)’), $ string)

everything is simple here, the regular expression is now specified as the first argument (without the / e modifier, of course), and the second argument is an anonymous function (which will be executed after the regular expression is applied) with two arguments: the $ matches array, where the data will be saved matching regular expression and calling an external function with arguments. In this example, the external function is called print_smile and is passed as an argument to the first occurrence it finds. What preg_replace was \\ 1 (the first match it found) would become $ matches (if there were more arguments, it would be $ matches, $ matches, and so on).

Here's another more complicated example:

It was like this:

$ out = preg_replace ("/<(=[\’\»]{0,1}|)(.*?)([\’\»]{0,1})>(.*?)<\/>/ es "," feed_out_sub_rm ('\\ 2', '$ base_prefix', '$ nick', '$ id_entry') ", $ out)

It became like this:

$ out = preg_replace_callback (‘/<(=[\’\»]{0,1}|)(.*?)([\’\»]{0,1})>(.*?)<\/>/ s ', create_function (' $ matches ',' return feed_out_sub_rm ($ matches, "'. $ base_prefix." ","'. $ nick. "", "'. $ id_entry." ")'), $ out )

it is easy to get confused in quotes here, be careful.

Digging into regular expressions, you can recall two more functions that are deprecated (and are not supported) since PHP 5.3.0. The symptoms are as follows:

Fatal error: Uncaught Error: Call to undefined function ereg_replace ()

If the regex in ereg_replace is simple, then you can get away with just setting the boundary characters, like here:

$ str = ereg_replace ("[\ r \ t \ n]", "", $ str)
$ str = preg_replace ("/ [\ r \ t \ n] /", "", $ str)

A similar symptom:

Fatal error: Uncaught Error: Call to undefined function split ()

$ var_pair = split ("=", $ tmp)

$ var_pair = explode ("=", $ tmp)

If the regular expression is more complex, then we try to convert it to preg_split.

If something does not work out, or your case is not at all similar to our examples - write comments, we will try to figure it out together.

In order to leave comments on a post, log in using your account on social networks VKontakte / FaceBook, or your account on Google / Yandex.

Good afternoon, dear readers and subscribers, for sure many of you have heard the information that the Google search engine is making great efforts to transfer all sites on the Internet to a secure https connection, by installing encryption certificates for websites, inviting webmasters to get bonuses in search results, all other things being equal. So I seriously thought about this task, planning to move the site in the summer, but before doing this I have to prepare everything and I set one of the preparation steps for myself, the transition from php 5 to php 7, on my hosting mchost.ru

Why should I switch from php 5 to php 7

I was prompted by two things:

  • I am getting more functionality from php 7
  • I reduce the load on my resources and reduce the number of requests, thereby increasing the speed of loading the site, it is very important now for mobile search results, the percentage of which has already exceeded 50 percent.

I have already described to you in the article how my site was bent from the load of parsing not by him, and the technical support, after solving the problems, also recommended, with the support of the php 7 site, to switch to it. Comparison tests of php 5 and php 7 performance, see the link.

Php version change

Since I have VPS hosting on mchost, it is very easy to do. We go to your personal account at https://cp.mchost.ru/login.php. Next, like any normal person, you should make a backup copy of the site. We go to the item backups, select a site and create.

The next step, you select the item sites. Find the right one among them and click php settings.

In the php paragraph for the domain, you will see a list of possible versions, currently the latest is FastCGI PHP 7.1

The process of transition from php 5 to php 7 will begin, on the right you will have a progress bar.

as you can see, before the version change, I have it 5.4.45

We are now watching 7.1

I want to note that the translation itself between versions can take up to 15 minutes, so it is better to postpone this action until the evening

If by the way you want to get 3 months of freebies from this hosting, then click on the banner below and enter promo code 48C4-D018-AC60-50C6

After you have transferred the site to a fresh version, check all the functionality of your resource, whether everything is working and displayed correctly, if you don’t have two options, 1 is to roll back, the second is to modify the site.

Possible problems

There are times when you get an error: Error establishing database connection

It can be solved simply, you need to update the password for the database in your personal account. Select the Databases item and click on the desired (edit)

We set the password again.

If, for example, you do not remember the password from it and you have a site engine, like mine is WordPress, then you can connect to the ftp server and find the wp-config.php file in the root of the site

Open it and find the (MySQL database password) field

If you have any other problems, then write about them in the comments and we will try to solve them together. So, do not be too lazy to complete this task, it is important to use all the features of the latest software, especially since you also get a bonus with less load on hosting and higher speed of your resource.

I decided to write about migrating to PHP 7, since he himself is now busy translating the code of one engine in PHP 7. And so to begin with, we turn on the debug or debugger in the admin panel of the site, if you don't have this, then you can do it as it is written in the subject: now on the monitor screen, we we can see error messages like this:

Warning: preg_replace (): The / e modifier is no longer supported, use preg_replace_callback instead - dir / file.php (line number)


This message says that the e modifier does not exist in PHP 7, you should get rid of it, but if you just remove this modifier, the script may not be executed correctly, it is not easy to write it there. I will show with an example of the code from PHPFOX 3(as I rewrote the code :), we do it like this:
For example, our error message points to the following line:

$ sStr = preg_replace ("/\.+?\ [\/ x \] / ise", "" ".stripslashes (\ $ this -> _ parseUserTagged (" $ 1 "))." "", $ sStr);


It should be changed like this:

$ sStr = preg_replace_callback ("/\.+?\ [\/ x \] / is", function ($ match) (return stripslashes ($ this -> _ parseUserTagged ($ match));), $ sStr);


Here we have replaced the function preg_replace (), on the preg_replace_callback (), removed the e modifier in the first argument, which is a regular expression. The second argument has been replaced with an anonymous function that will be executed after the regular expression is applied. The anonymous function contains an array $ match, the elements of the array replace matches, for example, it was: $ 1, now it is: $ match; was: $ 2, now: $ match, and so on. Removed the quotes and the escape character (backslash \).

In conclusion about the error of the non-existent modifier e, I will show a couple more examples of code replacement. The line:

$ aRow ["value_actual"] = preg_replace ("/ s: (. *): \" (. *?) \ "; / ies", "" s: ". strlen (" $ 2 ").": \ " $ 2 \ ";" ", $ aRow [" value_actual "]);


Change like this:

$ aRow ["value_actual"] = preg_replace_callback ("/ s: (. *): \" (. *?) \ "; / is", function ($ match) (return "s:". strlen ($ match) . ":" ". $ match." ";";), $ aRow ["value_actual"]);


And an example with a variable in a regular expression, the line:

$ sTxt = preg_replace ("/ \ [". $ sBbcode. "= (. *?) \] / ise", "" ". \ $ this -> _ replaceBbCode (" ". \ $ sBbcode." "," prefix ", true," $ 1 ")." "", $ sTxt);


Replaced like this:

$ sTxt = preg_replace_callback ("/ \ [". $ sBbcode. "= (. *?) \] / is", function ($ match) use ($ sBbcode) (return $ this -> _ replaceBbCode ($ sBbcode, "prefix ", true, $ match);), $ sTxt);


Here we added the use () function, into which we placed the variable from the regular expression, thereby passing the variable to the anonymous function. If there are more than one variables in the regular expression, then we simply list them separated by commas, for example:

function ($ match) use ($ a, $ b, $ c)

Deprecated ereg_replace () function
As the official PHP site reported: http://php.net/:

This function is DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.


And already in PHP 7 they completely forgot about it ... You can get the following error message:

Fatal error: Uncaught Error: Call to undefined function ereg_replace ()


This function should be replaced with preg_replace () by following the example below. Let's say we have the following line of code:

$ str = ereg_replace ("[^ -<>-)] "," ", str_replace (" \ x00 "," ", $ originalcommentname));


Let's change the code like this:

Should you upgrade to PHP 7.0? - Definitely worth it, don't even think - go!

There are a lot of innovations in the seventh version. The main ones are:

  1. PHP 7 is based on PHPNG. The new core gives a performance boost to sites from 40%;
  2. type Hints and return values. Now, when declaring a function, for each variable you can specify its own type, as well as the data type that the function will return. The available types are int, float, string, and bool;
  3. combined comparison operator and more.

The extensions have been removed in PHP 7:

  • mysql

Removed extensions have long been in the "deprecated" status, their use led to the display of a warning. Instead of "mysql" you should use "mysqli" or "pdo_mysql", and instead of "ereg" => "preg_ *".

More details about the new PHP 7 can be found on the official page.

Should you upgrade to PHP 7?

At the moment, the easiest thing you can do to improve your site's performance is to upgrade to PHP 7.0.x. The speed boost also depends on how your project is written. If you are still in doubt, here are some comparisons:

PHP 5.6 vs PHP 7 benchmarks for some frameworks and CMS (Zend framework, Magento, Drupal, Mediawiki, WordPress, Laravel, SugarCRM, etc.):

For all frameworks, the performance gains are significant. Let's see how things stand with kernel functions and constructs:

If the charts have convinced you, you can try to migrate your site to the new PHP version and feel the gain on a real project.

When creating a node, select "Blue" in the server list so that the node will be created on a server with PHP 7.

This is how 1c bitrix on the basis of an SSD disk and PHP 7.0 shows itself

Should you upgrade to PHP 7.0? - Definitely worth it, don't even think - go!

There are a lot of innovations in the seventh version. The main ones are:

  • PHP 7 core is based on PHPNG... The new core gives a performance boost to sites from 40%;
  • type Hints and return values... Now, when declaring a function, for each variable you can specify its own type, as well as the data type that the function will return. The available types are int, float, string, and bool;
  • combined comparison operator and much more.

Some extensions have been removed in PHP 7:

  • mysql

As of PHP 5.6.x, the use of these extensions was deprecated. Instead of "mysql" you should use "PDO" and instead of ereg → preg.

More details about the new PHP 7 can be found on the official page

Should you upgrade to PHP 7?

At the moment, the easiest thing you can do to improve your site's performance is to upgrade to PHP 7.0.x. The speed boost also depends on how your project is written. If you are still in doubt, here are some comparisons:

Benchmarks PHP 5.6 vs PHP 7 for some frameworks (Zend framework, Magento, Drupal, Mediawiki, WordPress, Laravel, SugarCRM, etc.):

For all frameworks, the performance gains are significant. Let's see how things stand with kernel functions and constructs:

Benchmarks PHP 5.6 vs PHP 7 for kernel functions and constructs:

If the charts have convinced you, you can try to migrate your site to the new PHP version and feel the gain on a real project.

Colleagues from Elasticweb said that before launching a new server with PHP 7, they launched a large state project on it, running on Laravel 5. It was a kind of performance test of the new version of PHP and the server as a whole. This project was previously on a server running PHP 5.6. After the site was moved, the pages began to open much faster, while the use of resources was cut in half.

They used PHP 7 Migration Assistant Report (MAR) to prepare for the move to PHP 7. Most of the popular CMS / Framework already have PHP 7 compatibility, so the main task was to test custom plugins.

WordPress 4, Drupal 8/7 and the latest Joomla are PHP 7 Ready!







2021 gtavrl.ru.