Viewing 15 replies — 1 through 15 (of 17 total)
WordPress itself supports PHP 7.2 (at least I assume you are using a fairly recent version of WP). Make sure your environment has either MySQL 5.6+ or MariaDB 10+.
Please check your wp-config.php file for the following line:
define('WP_USE_EXT_MYSQL', true);
If you find it, delete the line. Your problem should be fixed.
If you still have the problem, then you incorrectly installed PHP 7.2.x. The error you reported is not possible if you are using PHP 7.2.x and the above line isn’t in wp-config.php.
Installing Mariadb 10.3 fixed this.
I can now view my webpage in localhost and access it from other computers on my domain, but the graphics don’t disply on the other computers. The problem is my path is pointed to localhost. So, I’m currently trying to login to the wordpress dashboard, but it doesn’t give me that option. Any ideas?
-
This reply was modified 4 years, 6 months ago by
sbsmain.
I’ll mark this one resolved and post the new issue.
For what is worth, I encountered the same error and the issue was solved by enabling the nd_mysqli
extension in the PHP 7 configuration, and disabling the mysqli
one.
Thanks Francesco! I did as you said and the error was solved (enabled nd_mysqli, the mysqli was already disabled).
I was using PHP 7 since months, so I don’t know why the error happened (today) in the first place?
Glad it helped!
I encountered the error when I upgraded to PHP 7 while having the W3 Total Cache “Database cache” enabled.
Maybe you’ve played around with W3TC today?
See for reference: https://wordpress.org/support/topic/database-cache-causing-503-errors-when-upgrading-to-php-7/
Thanks Francesco! This fixed the issue for me as well. I had a caching plugin installed when updating WP.
Hi
I’m creating my first site and came upon the error below.
i had created a first page on my domain and i was stuck somewhere unable to edit it, so i deleted all my files on that and started a new website on the same domain.
The problem is, the new website is not accessible.
i have not downloaded anything else apart from wordpress so i dont think the error i have is related to the php download described above
I’m seeing lots of delete.wpm…stuff in here and i’m not sure how to proceed
The error is:
PHP Fatal error: Uncaught Error: Call to undefined function get_transient() in /home/upku9mvvkvf0/public_html/deleteme.wpmfgw.php:16
Stack trace:
#0 {main}
thrown in /home/upku9mvvkvf0/public_html/deleteme.wpmfgw.php on line 16
[14-Apr-2019 04:29:43 UTC] PHP Fatal error: Uncaught Error: Call to undefined function get_transient() in /home/upku9mvvkvf0/public_html/deleteme.wpkq1x.php:16
Stack trace:
#0 {main}
thrown in /home/upku9mvvkvf0/public_html/deleteme.wpkq1x.php on line 16
[14-Apr-2019 04:29:43 UTC] PHP Fatal error: Uncaught Error: Call to undefined function get_transient() in /home/upku9mvvkvf0/public_html/deleteme.wppsmo.php:16
Stack trace:
#0 {main}
thrown in /home/upku9mvvkvf0/public_html/deleteme.wppsmo.php on line 16
please assist me to solve this.
Kind Regards
UPDATE
i just realized that i signed up to linux hosting with cpanel (on godaddy)….while my pc is on windows
oh well!!!!
let me now try to resolve the new problem :/
Francesco’s trick worked form me. I am now running WP 5.2.3 on PHP 7.3 on cPanel.
I am throwing this error. Where exactly can I toggle this setting to change mysqli to nd_mysqli?
I face a similar problem. And I was able to solve it by following Francesco‘s instruction.
Currently, I using PHP 7.3 version and WordPress latest version. Just enabled the extension nd_mysqli
.
I instantly solved the problem and My WordPress site now working good.
Thanks Francesco‘s and other for help.
Can you tell me how can I enable the nd_mysqli
extension please?
Thank you.
If anyone else is having this problem while doing an initial install of wordpress 5.4 on a php 7.x on windows no less, try uncommenting the extension=mysqli line in your php.ini file. That eventually got me there.
Please help with this same issue, I have a Apache and PHP 7.4.5 running on a Windows 10 machine. I was still trying to install wordpress when I encountered an error
There has been a critical error on your website.
Learn more about debugging in WordPress.
I enabled debugging and entered the db details on the wp-config files manually but then I started getting this error.
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:Apache24htdocsclickmediawp-includeswp-db.php:1658 Stack trace: #0 C:Apache24htdocsclickmediawp-includeswp-db.php(631): wpdb->db_connect() #1 C:Apache24htdocsclickmediawp-includesload.php(426): wpdb->__construct(‘admin’, ‘081447Addax’, ‘clickmedia’, ‘127.0.0.1’) #2 C:Apache24htdocsclickmediawp-settings.php(126): require_wp_db() #3 C:Apache24htdocsclickmediawp-config.php(90): require_once(‘C:\Apache24\htd…’) #4 C:Apache24htdocsclickmediawp-load.php(37): require_once(‘C:\Apache24\htd…’) #5 C:Apache24htdocsclickmediawp-blog-header.php(13): require_once(‘C:\Apache24\htd…’) #6 C:Apache24htdocsclickmediaindex.php(17): require(‘C:\Apache24\htd…’) #7 {main} thrown in C:Apache24htdocsclickmediawp-includeswp-db.php on line 1658
I have tried to follow @fcolombo’s suggestion but
1. I dont have the PHP configuration utility you refer to. So I edited the PHP.ini file
2. I can’t find nd_mysql as stated
I only found this line which I uncommented.
extension=mysqli
there is also a this line
[mysqlnd]
with other configurations for mysqlnd, could this be the same as nd_mysql?
Your help would be much appreciated. Stuck trying to to sort this out for hours
Viewing 15 replies — 1 through 15 (of 17 total)
Are you getting Call to undefined function error while accessing? Do you need help? If yes, then you should read this blog. In this, we have discussed every detail that you need to know before fixing this error and steps to fix them.
Let us get started!
It is a fatal error which increases day by day that target themes directly. They receive a URL to your theme directory. Well, there are a numbers of ways to get this information. Let me explain you with an example. Most themes include JavaScript files, CSS, and link of URL.
The bad bots send a request to a popular theme file as index.php or header.php. With this, requesting files outsource security susceptibilities, which is a major attack. This also triggers Call to Undefined function error. The best part is you can fix it easily.
In other words, you can say when a user request to header.php file, any important function as exc_url () are not available, because it is outside the WordPress. Or this is happening because WordPress core is not loaded, loading the template files.
This may happen because of bad bots and depending on your theme, how it is coded. This may be because of bad actions or executing the code out of context.
Does Your Site Under Attack?
First, you will need to check whether your site is targeted or not. To check this error see error logs. For example: Got error”PHP message: PHP Fatal Error: uncaught error: Call to undefined function
get_header() htttps://sktthemes.org/wp-content/themes/digwp/index.php: 1’ Stack trace: #0 {main} thrown in htttps://sktthemes.org/wp-content/digwp/index.php on line 1’
If your site is getting this type of error, this means your site is targeted or attacked by bad bots. You can see many types of these errors. In the example, you can see index.php, 404.php, and header.php. After research and getting reviews from sources, lots of people see this kind of error in WordPress files instead of example.
See this: /archive.php
/Wp-includes/rss-functions.php
..Various theme template files
..Various files in the WP media library
Fundamentally, the direct access from WordPress core, plugin or a file triggers an error. To solve this query we have shared the methods to solve call to undefined function error to the better overall security of your theme.
What’s The Issue?
– If you are trying to log-in to your WordPress account.
– If you have updated the WordPress.
– If you are getting this message; is_network_admin() error message or “Fatal error undefined function is_network_admin()”
How To Fix Call To Undefined Function Fatal Error
To fix this issue you have multiple ways. Here we will talk about the best techniques that may help you without trouble.
One of the beats and easiest ways to overcome this type of error is, exit the script if WordPress is not available. It is an efficient and well-known technique to fix the issue.
In other words, if ABSPATH constant is not definite, exit the script. The ABSPATH works when WordPress is loaded. When bad bots come and request a theme template, it gives a blank page.
For example: <? Php if (! defined (‘ABSPATH’) exit ;?>
You have seen such code during WordPress sessions. It is vital to protect direct script access to PHP security. After all, you do not need bots/attackers on site.
So, to exit from the script you will need to follow the given way.
First open any theme file, which is targeted. Now, include the given line at the top of the file.
When you get no access or exit from the script you will see the given code:
<? Php if (! defined (‘ABSPATH’) exit ; get_header(); ?>
If you want to format the code, it is normal.
Advantage
To move on further, you can protect vital files by restricting the directory views. Let us consider an example: when you visit the parent directory via browser, you will directory views are enabled. If it is, you will get a linked list of files, which is not good.
Either you see a blank screen or maybe some other messages. You will need to keep your file secure and safe.
To restrict the directory views, you will need to create the first empty file index.php file, whichever you want to disable.
To disallow the code do this:
<!–?php // Silence is golden.</p>
<p>WordPress uses this technique for a long time to prevent hackers/boaters. You should try this if any trouble you are getting while accessing WordPress.</p>
The Final Verdict
As you can see, we have shared a simple yet effective way to prevent pages from attackers/hackers. In this technique you will not need an expert, if you are not able to do so then add a suitable plugin for better security. With this, you will get better performance, protect plugin files, and direct access. Good Luck!
Related Post: How to Fix the Syntax Error in WordPress website
Shri shares exciting WordPress themes, plugins and other WordPress related news for our viewers. He also posts selected WordPress developers interviews from time to time.
View all posts by Shri Posts | Website
Webmasters and website owners often upgrade PHP to the latest version to avoid security vulnerabilities. This sometimes causes compatibility errors, and one such error is “PHP fatal error call to undefined function mysql_connect()”.
As a part of our Server Management Services, we help our customers to fix such PHP errors.
Here, let’s discuss how to fix the PHP fatal error call to undefined function mysql_connect()
What is a PHP fatal error?
Using older versions of PHP may expose the website to security vulnerabilities and more importantly, bugs that are fixed in the recent versions.
So it is a better idea to upgrade the PHP version to the latest one. However, it is also important to prevent PHP fatal errors on your website.
PHP Fatal Errors also known as Critical Errors can occur after the PHP upgrade. This error stops/terminates the execution of scripts.
The mysql_connect() PHP fatal error may often occur after upgrading your app to PHP 7+. It will try to use “mysql_connect()” functions of php5 in php7. However, mysql_* functions are completely removed from PHP 7+
Also, Fatal error: Uncaught Error: Call to undefined function mysql_connect() error on WordPress site or dashboard looks like,
How to fix the PHP fatal error call to undefined function mysql_connect() error
After upgrading your PHP version to PHP 7+, there is a chance that you will have the following error:
Fatal error: Uncaught Error: Call to undefined function mysql_connect()
This is due to the removal of the mysql_connect function from PHP 7+ versions.
Let’s see how our Support Engineers fixed the PHP fatal errors
1. Upgrade custom code and WordPress plugins or theme
Initially, we’ll identify whether the site is WordPress or using custom code.
If it is WordPress, the main reason could be compatibility issues. The WordPress theme or plugin may not be compatible with higher PHP versions.
So, we will enable the debug option in wp-config.php and find which WordPress plugin or theme is not compatible with PHP 7+. Then, we will recommend them to upgrade/replace the plugin and theme.
If the site is using custom code, then our developer team will help the customers to make the code compatible with the new PHP version.
This solved the issue.
2. Use MySQLi or PDO
Fatal error: Uncaught Error: Call to undefined function mysql_connect() error can be fixed by the use of MySQLi or PDO.
Many customers are using PHP 7.3 version and WordPress latest version. However, they will get the same error after upgrading.
So, we solved the error by enabling the nd_mysqli extension in the PHP configuration and disabling the mysqli one.
How we fix PHP Fatal error: require_once()
Another issue that we commanly dealing with is PHP Fatal error: require_once(): Failed opening required ‘Mail.php’ (include_path=’.:/usr/share/pear:/usr/share/php’)
Recently, one customer had an issue while sending an email by using PHP mail function with SMTP after upgrading PHP from PHP 5.6 to PHP 7+.
On checking, we have found that the error happened due to an incorrect path to Mail.php. He has created the file mail.php instead of Mail.php and specified as require_once(‘Mail.php’)
So we have renamed the file name to Mail.php and solved the error
[Need assistance to fix PHP Fatal errors? – our Support Engineers will help you.]
Conclusion
In short, php fatal error call to undefined function mysql_connect() error occurs after PHP version upgrade. This is due to the removal of the mysql_connect function from PHP 7+ versions. Today, we saw how our Support Engineers fixed the PHP fatal errors.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
I’m seeing a big increase in bot attacks targeting theme files directly. First they get the URL to your theme directory. There are numerous ways for a bot to get this information. For example most themes include assets like CSS and JavaScript files, and the link includes the full URL. So then once they have the theme URL, bad bots will make direct requests for well-known theme template files, like
index.php
and header.php
. Requesting template files directly may reveal possible security vulnerabilities, which apparently is an increasingly popular attack vector. It also triggers the “Call to undefined function get_header()” (and similar) errors. Fortunately there is an easy fix.
Is your site targeted?
To find out if your site is getting hit with direct requests for theme files, you can check your site’s access/error logs. Here are some examples from my own logs that should help show what to look for:
Note: In the following log entries, all file paths are changed to example URLs to prevent Google from crawling and reporting errors. In the actual log files, errors contain file paths, not URLs. P.S., it is most ridiculous that Googlebot crawls plain-text path information, inside of <pre>
tags no less.
2018-12-30 17:54:07 Error
AH01071: Got error 'PHP message: PHP Fatal error:
Uncaught Error: Call to undefined function get_header() in https://example.com/wp-content/themes/digwp/index.php:1
Stack trace: #0 {main} thrown in https://example.com/wp-content/themes/digwp/index.php on line 1'
2018-12-30 12:53:55 Error
AH01071: Got error 'PHP message: PHP Fatal error:
Uncaught Error: Call to undefined function get_header() in https://example.com/wp-content/themes/digwp/404.php:1
Stack trace: #0 {main} thrown in https://example.com/wp-content/themes/digwp/404.php on line 1'
2018-12-30 12:53:55 Error
AH01071: Got error 'PHP message: PHP Fatal error:
Uncaught Error: Call to undefined function esc_url() in https://example.com/wp-content/themes/digwp/header.php:8
Stack trace: #0 {main} thrown in https://example.com/wp-content/themes/digwp/header.php on line 8'
So if your site is targeted with direct-template attacks, you’ll see LOTS of these types of errors. In these examples, the requests are for index.php
, 404.php
, and header.php
. From my analyses, most of the template requests are for these three files, but you may also find them scanning for other well-known WordPress files, such as:
/archive.php
/wp-includes/rss-functions.php
..various theme template files
..various files in the WP Media Library
Basically, any direct request for a WordPress core, theme, or plugin file most likely will trigger an error, unless proper measures are taken beforehand. For example, later we’ll look at an easy way to stop the “undefined function” error, which in turn will help conserve precious server resources and improve overall site security.
Understanding the error
So what’s with the “call to undefined function” fatal errors? They happen because WordPress core is not loaded for directly loaded template files.
For example, if you request header.php
directly, any core functions such as esc_url()
are not available because the file is requested outside of WordPress.
What happens if you do nothing? Well, your theme may already have implemented a similar technique, or maybe not. What’s the risk? Depending on how your theme is coded, it may be possible for bad actors to execute code out of context, which may expose potential attack vectors.
How to fix
The easiest way to prevent this type of error is to simply exit the script if WordPress is not available. This is an ancient yet effective PHP technique used to prevent direct file access:
<?php if (!defined('ABSPATH')) exit; ?>
It simply says: If the ABSPATH
constant is not defined, then exit the script. This works because ABSPATH
is only defined when WordPress is loaded. So when a bad bot comes along and starts requesting your theme templates, it will simply get a blank page (empty response) from the server.
You may have seen similar code during your WordPress travels. Preventing direct script access is an important part of PHP security. You don’t want attackers/bots running scripts out of context, when not authorized, and so forth.
Example
To implement this technique, open any theme files that are targeted, and include the line at the top of the file. For example, many theme templates include the header before any other code, looks like this:
<?php get_header(); ?>
After adding the “no direct access” snippet, you’ll have something like:
<?php
if (!defined('ABSPATH')) exit;
get_header();
?>
However you decide to format the code is fine, the point is to include the ABSPATH line before any other functions are called.
Pro Tip: Want to stop more bad bots? Check out my free WordPress plugin, Blackhole for Bad Bots, available at the WP Plugin Directory.
Bonus
To go further, you can protect sensitive file information by disabling directory views. For example, if you visit your theme parent directory in a browser, what do you see? If directory views are enabled, you’ll get a linked list of all the files. Not good. What you should see is either a blank white screen or some other server response. You know, to help keep your file information safe and secure.
There are numerous ways to disable directory views. The WordPress way is to create a new (empty) index.php
file in whichever directory you want to protect.
Important! Only create a new index.php
file if one does NOT already exist in the directory. That is, don’t overwrite any existing index files.
Then in index.php
, add the following code:
<?php
// Silence is golden.
WordPress core uses this technique in various directories. By disabling open directory views, we prevent attackers from obtaining information about which files exist on the server. So it benefits security and is recommended practice for all public directories, unless you’ve got it covered with .htaccess, or maybe have reason to do otherwise and leave views enabled for a specific directory.
Closing thoughts
The simple techniques described in this article are proven security measures that will prevent unsafe code execution and stop errors from filling up your logs. That means better performance and security for your site. Even if you’re not experiencing the type of errors described in this article, protecting your theme and plugin files from direct access is good for security.
About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
I’ve installed WordPress under ArchLinux on my VPS, configured the SQL backend and edited /usr/share/webapps/wordpress/wp-config.php. Unfortunately on trying to access pages I’m getting…
2019/06/14 06:44:12 [error] 20812#20812: *394 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /usr/share/webapps/wordpress/wp-includes/wp-db.php:1645
Stack trace:
#0 /usr/share/webapps/wordpress/wp-includes/wp-db.php(639): wpdb->db_connect()
#1 /usr/share/webapps/wordpress/wp-includes/load.php(427): wpdb->__construct('wp-user', 'pc&0wC<k%:o<AuI...', 'wordpress', 'localhost')
#2 /usr/share/webapps/wordpress/wp-settings.php(120): require_wp_db()
#3 /usr/share/webapps/wordpress/wp-config.php(90): require_once('/usr/share/weba...')
#4 /usr/share/webapps/wordpress/wp-load.php(37): require_once('/usr/share/weba...')
#5 /usr/share/webapps/wordpress/wp-blog-header.php(13): require_once('/usr/share/weba...')
#6 /usr/share/webapps/wordpress/index.php(17): require('/usr/share/weba...')
#7 {main}
thrown in /usr/share/webapps/wordpress/wp-includes/wp-db.php on line 1645" while reading response header from upstream, client:...
Searching around this appears to happen under PHP when its attempting to use the mysql module rather than mysqli (found threads here and here).
I’ve enabled mysqli in /etc/php/php.ini
extension=mysqli
…and the module is loaded…
php -m
[PHP Modules]
Core
ctype
curl
date
dom
fileinfo
filter
hash
json
libxml
mbstring
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
Phar
posix
readline
Reflection
session
SimpleXML
SPL
standard
tokenizer
xml
xmlreader
xmlwriter
zip
zlib
[Zend Modules]
Reading through /usr/share/webapps/wordpress/wp-includes/wp-db.php around the offending line (1645) it looks to me as though there are a series of if{} else{} statements starting on line 1589 which checks to see if use_mysqli is being used,this fails and as there is no mysql module in they was removed in PHP7 and mysqli should instead be used.
grep '$this->use_mysqli' /usr/share/webapps/wordpress/wp-includes/wp-db.php -A100 -n | grep 1589 -A100
1589: if ( $this->use_mysqli ) {
1590- $this->dbh = mysqli_init();
1591-
1592- $host = $this->dbhost;
1593- $port = null;
1594- $socket = null;
1595- $is_ipv6 = false;
1596-
1597- if ( $host_data = $this->parse_db_host( $this->dbhost ) ) {
1598- list( $host, $port, $socket, $is_ipv6 ) = $host_data;
1599- }
1600-
1601- /*
1602- * If using the `mysqlnd` library, the IPv6 address needs to be
1603- * enclosed in square brackets, whereas it doesn't while using the
1604- * `libmysqlclient` library.
1605- * @see https://bugs.php.net/bug.php?id=67563
1606- */
1607- if ( $is_ipv6 && extension_loaded( 'mysqlnd' ) ) {
1608- $host = "[$host]";
1609- }
1610-
1611- if ( WP_DEBUG ) {
1612- mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1613- } else {
1614- @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1615- }
1616-
1617- if ( $this->dbh->connect_errno ) {
1618- $this->dbh = null;
1619-
1620- /*
1621- * It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1622- * - We haven't previously connected, and
1623- * - WP_USE_EXT_MYSQL isn't set to false, and
1624- * - ext/mysql is loaded.
1625- */
1626- $attempt_fallback = true;
1627-
1628- if ( $this->has_connected ) {
1629- $attempt_fallback = false;
1630- } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1631- $attempt_fallback = false;
1632- } elseif ( ! function_exists( 'mysql_connect' ) ) {
1633- $attempt_fallback = false;
1634- }
1635-
1636- if ( $attempt_fallback ) {
1637: $this->use_mysqli = false;
1638- return $this->db_connect( $allow_bail );
1639- }
1640- }
1641- } else {
1642- if ( WP_DEBUG ) {
1643- $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1644- } else {
1645- $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1646- }
1647- }
This fails because, looking further back through /usr/share/webapps/wordpress/wp-includes/wp-db.php I can see $is_mysql is set to null on line 564 and $use_mysqli is set to false which explains why the test to see if use_mysqli is being used fails and instead connect_mysql() is being attempted…
grep 'public $is_mysql = null' /usr/share/webapps/wordpress/wp-includes/wp-db.php -A30 -n
564: public $is_mysql = null;
565-
566- /**
567- * A list of incompatible SQL modes.
568- *
569- * @since 3.9.0
570- * @var array
571- */
572- protected $incompatible_modes = array(
573- 'NO_ZERO_DATE',
574- 'ONLY_FULL_GROUP_BY',
575- 'STRICT_TRANS_TABLES',
576- 'STRICT_ALL_TABLES',
577- 'TRADITIONAL',
578- );
579-
580- /**
581- * Whether to use mysqli over mysql.
582- *
583- * @since 3.9.0
584- * @var bool
585- */
586- private $use_mysqli = false;
Given mysql has been removed since PHP7 and is not a listed possible module in /etc/php/php.ini I’m surprised $use_mysqli = false on a fresh install. I’ve tried setting it to true and after restarting php-fpm.service now get another error and enter the if ( $this->$use_mysqli){…} section only to fail on the first call to $this->dbh = mysqli_init()…
2019/06/14 07:10:25 [error] 1439#1439: *1 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught Error: Call to undefined function mysqli_init() in /usr/share/webapps/wordpress/wp-includes/wp-db.php:1591
Stack trace:
#0 /usr/share/webapps/wordpress/wp-includes/wp-db.php(640): wpdb->db_connect()
#1 /usr/share/webapps/wordpress/wp-includes/load.php(427): wpdb->__construct('wp-user', 'pc&0wC<k%:o<AuI...', 'wordpress', 'localhost')
#2 /usr/share/webapps/wordpress/wp-settings.php(120): require_wp_db()
#3 /usr/share/webapps/wordpress/wp-config.php(90): require_once('/usr/share/weba...')
#4 /usr/share/webapps/wordpress/wp-load.php(37): require_once('/usr/share/weba...')
#5 /usr/share/webapps/wordpress/wp-blog-header.php(13): require_once('/usr/share/weba...')
#6 /usr/share/webapps/wordpress/index.php(17): require('/usr/share/weba...')
#7 {main}
thrown in /usr/share/webapps/wordpress/wp-includes/wp-db.php on line 1591" while reading response header from upstream, client:
I’m not adverse to modifying configuration but the impression I had from Arch Wiki : WordPress article is that this level of tinkering is not required. Can anyone advise on where I might have gone wrong.
EDIT
mysqli section from phpinfo()
mysqli
MysqlI Support enabled
Client API library version mysqlnd 5.0.12-dev - 20150407 - $Id: 7cc7cc96e675f6d72e5cf0f267f48e167c2abb23 $
Active Persistent Links 0
Inactive Persistent Links 0
Active Links 0
Directive Local Value Master Value
mysqli.allow_local_infile Off Off
mysqli.allow_persistent On On
mysqli.default_host no value no value
mysqli.default_port 3306 3306
mysqli.default_pw no value no value
mysqli.default_socket /run/mysqld/mysqld.sock /run/mysqld/mysqld.sock
mysqli.default_user no value no value
mysqli.max_links Unlimited Unlimited
mysqli.max_persistent Unlimited Unlimited
mysqli.reconnect Off Off
mysqli.rollback_on_cached_plink Off Off
EDIT2 : Its suggested that php-fpm
wasn’t loading the mysqli
module, I’ve now checked and it appears to…
$ php-fpm -m
[PHP Modules]
cgi-fcgi
Core
ctype
curl
date
dom
fileinfo
filter
hash
json
libxml
mbstring
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
pdo_mysql
Phar
posix
readline
Reflection
session
SimpleXML
SPL
standard
tokenizer
xml
xmlreader
xmlwriter
zip
zlib
[Zend Modules]
If you see something like this error, «undefined function mysql_connect()», in your logs it means your WordPress site is calling a function to a deprecated extension called mysql_Connect:
PHP Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /wp-includes/wp-db.php:1645
As its name implies, it’s used to call connections to the database in older versions of PHP.
According to the PHP Manual:
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Alternatives to this function include:
mysqli_connect()
PDO::__construct()PHP Manual | www.php.net
Here’s the example usage:
mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = FALSE [, int $client_flags = 0 ]]]]] ) : resource
This error will most likely crop up if you upgrade your server’s PHP version from 5.X to 7.X (or migrate to new hardware). This function actually works just fine on PHP 5.6, but not on 7.0 and above. The side-effects to your site will range from just being an error in the logs all the way to bringing the site down:
The most common reason for the presence of «undefined function mysql_connect()» in your error logs or debug output is this one line in wp-config.php
:
define('WP_USE_EXT_MYSQL', true);
Removing that line should fix the issue. If it doesn’t, hop into your terminal and seach for WP_USE_EXT_MYSQL
through your file system (with something like ack wp_use_ext_mysql -l
) to hunt it down in your plugin and theme files.
Though it’s worth consulting your developer, or the developer of the related theme or plugin, to see why it was there in the first place. They may need to update the code to use something like mysqli_connect()
instead.
That WP_USE_EXT_MYSQL
define is most commonly used to add support for older plugins (like some versions of Shopp and Social Streams for example) so it’s a good idea to at least run through your site to test for broken functionality after removing that line.
And that’s that.
Интересный баг обнаружил при работе дополнения на мультисайте WordPress. Здесь расскажу о нем, его не очевидном выявлении и это поможет вам избежать подобных промашек.
Предыстория:
Вначале один пользователь сообщил мне что активировав мое дополнение для WordPress плагина WP-Recall он не может перейти в консоль управления мультисайтом (Управление сетью->Консоль)
Вот сюда:
Ок,
«Какую ошибку выдает на момент перехода? Что в Error.log сервера?»
— ответ был такой:
PHP Fatal error: Uncaught Error: Call to undefined function wp_get_current_user() in our-site.ru/wp-includes/capabilities.php:598
Самая засада в том, что мое дополнение не использует функцию wp_get_current_user. Больше никаких подробностей не сообщалось.
Я свои дополнения не тестировал в работе режима мультисайта и не заявляю о его поддержке (потому что малый процент использование его только лишь добавит мне проблем и траты времени на его тестирование и отладку). Поэтому не придал проблеме должного внимания. Но интересное пошло потом — еще один пользователь сообщил мне о проблеме с 2-мя моими дополнениями. Это было накануне новогодних праздников. Так вот после них я и решил глянуть — в чем проблема. Один репорт — случайность, два — закономерность, а три — это уже проблема. Проблемы должны решаться. Что я и сделал вчера.
Поиск виновного:
Установил на поддомене чистый вордпресс, активировал на нем режим мультисайта, взяв дефолтные настройки сети (каждый новый сайт в подкаталоге).
Активировал проблемный доп и перешел по скрину выше в управление мультисайтом. Белый экран.
Полез в логи и вот что увидел:
PHP Fatal error: Uncaught Error: Call to undefined function wp_get_current_user() in .otshelnik-fm.ru/wp-includes/capabilities.php:598
Stack trace:
# 0 .otshelnik-fm.ru/wp-admin/network/settings.php(16): current_user_can(‘manage_network_…’)
# 1 .otshelnik-fm.ru/wp-content/wp-recall/add-on/hello-private-message/index.php(3): require_once(‘…’)
# 2 .otshelnik-fm.ru/wp-content/plugins/wp-recall/functions/addons.php(96): include_once(‘…’)
# 3 .otshelnik-fm.ru/wp-content/plugins/wp-recall/wp-recall.php(400): rcl_include_addon(‘…’, ‘hello-private-m…’)
# 4 .otshelnik-fm.ru/wp-content/plugins/wp-recall/wp-recall.php(354): WP_Recall->include_addon(‘hello-private-m…’
# 5 .otshelnik-fm.ru/wp-content/plugins/wp-recall/wp-recall.php(181): WP_Recall->include_addons()
# 6 .otshelnik-fm.ru/wp-includes/capabilities.php on line 598
wp_get_current_user — эту функцию мой доп не использует, но по стеку видно что add-on/hello-private-message/index.php(3)
— в 3-й строке доп подключает файл. Но php скрипт не обрывается, а выполняется дальше. Стек трейс мой доп упомянул — значит косвенно он участвует в падении.
Смотрим, что в 3-й строке:
require_once('settings.php');
— и всё!
WTF? Почему подключая файл settings.php, который лежит в корне дополнения, я получаю белый экран? Я закомментировал эту строчку и смог войти в панель управления мультисайтом.
Вернул как было.
Я еще был далек от понимания. В файле settings.php — настройки для админки, но там нет вызова этой функции. Стер весь файл settings.php — он пустой. И снова получаю белый экран с этой же ошибкой.
Тут я понимаю что стек трейс я читаю неверно. Что после подключения settings.php файла я оказываюсь выше по стеку:
/wp-admin/network/settings.php(16): current_user_can('manage_network_...')
а урл, который в админке с белым экраном, такой:
.otshelnik-fm.ru/wp-admin/network/
— и тут пришло озарение: что путь подключения, функция require_once, берет не от корня моего дополнения, а от урл моего нахождения /wp-admin/network/settings.php(16)
— вот он settings.php и подключается. Только с другого пути. Перечитал описание функций require_once и require и include и башка вскипела.
Константы __DIR__ и __FILE__ выдают мне пути до моего дополнения.
Я переименовал файл в корне моего дополнения на sssettings.php и исправил в 3й строке подключение к нему на новое имя. Белый экран пропал. Я попал в консоль управления мультисайтом.
Решение проблемы:
Решений несколько:
1. Как вариант — не иметь в корне дополнения (или вашего плагина) файла settings.php и вообще таких имен:
2. Или перенести в подпапку inc свой файл settings.php (подозреваю что имя подпапки не должно совпадать с именем подпапки по вышеуказанному пути — не дай боже второй раз совпадение будет)
3. Подключать файл указав полный путь до дополнения:
require_once rcl_addon_path(__FILE__).'settings.php';
— функция wp-recall — содержит полный путь до вашего дополнения на сервере. Можете и ВП аналогичные функции использовать
4. Вводить проверку:
if( is_admin() && !is_network_admin() ){
require_once 'settings.php';
}
— мы проверяем что мы в админке, но не на странице управления мультисайтом.
Выводы:
Не все очевидно с багами которые нам встречаются. Мультисайтовая сборка доставляет нам еще один опыт. Виновен ли php — или сам мультисайт? У меня прозрение не наступило — сказать не могу. Но мы получили такой опыт.
Гугл не давал мне результатов кроме одного. Теперь стоит запомнить эту ошибку и внимательнее смотреть к репортам пользователей. Возможно одного пользователя я потерял. Но второй меня заставил все таки пошевелиться и отнестись внимательнее к проблеме. Входных данных конечно было мало и это возможно остановило меня при первом репорте.
Дополнения я свои исправлю. Но не буду утверждать что я поддерживаю работу в режиме мультисайта — тестировать еще одну сущность, да крайне редкую не буду. Только по факту обращения с проблемами.
upd: подобную проблему обнаружил подключая файл из корня: require_once 'setup.php';
— решение такое же, как в заметке выше.