I have two sites on a LAMP stack. One (Site1) uses WordPress with Wordfence, and it works perfectly fine. The second website (Site2) only runs a simple index.php file on it:
<?php
echo "Testing";
?>
However, it shows HTTP ERROR 500 with the error log as below.
[Thu Dec 22 16:23:44.774993 2016] [:error] [pid 56607] [client xxx:27253] PHP Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0
[Thu Dec 22 16:23:44.775042 2016] [:error] [pid 56607] [client xxx:27253] PHP Fatal error: Unknown: Failed opening required '/var/www/site1/public_html/public/wordfence-waf.php' (include_path='.:/usr/share/php') in Unknown on line 0
Site1 and Site2 have nothing to do with each other, and they are located in separate folders. I am not sure what’s happening. Please advise.
.htaccess file on Site1
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
# Wordfence WAF
<IfModule mod_php7.c>
php_value auto_prepend_file '/var/www/site1/public_html/public/wordfence-waf.php'
</IfModule>
<Files ".user.ini">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
# END Wordfence WAF
elixenide
43.8k16 gold badges75 silver badges99 bronze badges
asked Dec 22, 2016 at 17:52
8
Thanks for @EdCottrell. I finally found an answer for that.
First, I debug to find where the php.ini locates by create a info.php on the working site.
<? php phpinfo(); ?>
Then, I find if there is any value on auto_prepend_file =. If yes, delete it.
Then I open the site1.conf file and add the auto_prepend_file line instead of the one from .htaccess
<Directory "/path/to/folder">
php_value auto_prepend_file /absolute/path/to/apache-prepend.php
</Directory>
After restarting the Apache server, everything works again!
sudo systemctl restart apache2
answered Dec 22, 2016 at 19:59
Dale NguyenDale Nguyen
1,8403 gold badges23 silver badges37 bronze badges
I had the same problem, I tried to run
docker run --t -v .:/project php
when I tried to do
/project:$ php file.php
I got this error.
Apparently, you can’t use bound volumes from docker that easily. So I copied the volume inside the container, and used a copy.
docker run --t -v .:/project php
/project:$ cd ..
/:$ cp -r /project /project2
/:$ cd /project2
/project2: $ php file.php
and it worked.
answered Aug 18, 2021 at 18:26
DanonDanon
2,56425 silver badges37 bronze badges
Are you seeing the ‘failed to open stream’ error in WordPress? This error usually points out the location of the scripts where the error has occurred. However, it is quite difficult for beginner users to understand it. In this article, we will show you how to easily fix the WordPress failed to open stream error.
Why Failed to Open Stream Error Occurs?
Before we try to fix the error, it would be helpful to understand what causes the ‘Failed to open stream’ error in WordPress.
This error occurs when WordPress is unable to load the file mentioned in website code. When this error occurs, sometimes WordPress will continue loading the site and only show a warning message, while other times WordPress will show a fatal error and will not load anything else.
The message phrasing will be different depending on where the error occurs in the code and the reason for failure. It will also give you clues about what needs to be fixed.
Typically, this message would look something like this:
Warning: require(/home/website/wp-includes/load.php): failed to open stream: No such file or directory in /home/website/wp-settings.php on line 19 Fatal error: require(): Failed opening required ‘/home/website/wp-includes/load.php’ (include_path=’.:/usr/share/php/:/usr/share/php5/’) in /home/website/wp-settings.php on line 19
Here is another example:
Last Error: 2018-04-04 14:52:13: (2) HTTP Error: Unable to connect: ‘fopen(compress.zlib://https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?start-index=1): failed to open stream: operation failed’
Having said that, let’s take a look at how to troubleshoot and fix ‘failed to open stream’ error in WordPress.
Fixing Failed to Open Stream Error in WordPress
As we mentioned earlier, the error can be caused by a variety of reasons and the error message will be different depending on the cause and location of the file that’s causing the error.
In each instance, failed to open stream phrase would be followed by a reason. For example, permission denied, no such file or directory, operation failed, and more.
Now if your error message contains ‘no such file or directory’, then you need to look in the code to figure out which file is mentioned at that particular line.
If it is a plugin or theme file, then this means that the plugin or theme files were either deleted or not installed correctly. Simply deactivate and reinstall the theme / plugin in question to fix the error.
However, it is also possible that WordPress is unable to locate the files because of a missing .htaccess file in your root folder. In that case, you need to go to Settings » Permalinks page in your WordPress admin and just click on the ‘Save changes’ button to regenerate the .htaccess file.
If the error message is followed by ‘Permission denied’, then this means that WordPress does not have the right permission to access the file or directory referenced in the code.
To fix this, you need to check WordPress files and directory permissions and correct them if needed.
Lastly, some WordPress plugins load scripts from third-party sources like Google Analytics, Facebook APIs, Google Maps, and other third-party APIs.
Some of these APIs may require authentication or may have changed the way developers can access them. A failure to authenticate or incorrect access method will result in WordPress failing to open the required files.
To fix this, you will need to contact the plugin author for support. They will be able to help you fix the error.
If none of these tips help you resolve the issue, then follow the steps mentioned in our WordPress troubleshooting guide. This step by step guide will help you pinpoint the issue, so you can easily find the solution.
We hope this article helped you fix the WordPress ‘failed to open stream’ error. You may also want to bookmark our list of the most common WordPress errors and how to fix them.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.
Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.
Содержание
- PHP Fatal error: Unknown: Failed opening required
- 8 responses to “ PHP Fatal error: Unknown: Failed opening required ”
- Fatal error: require(): Failed opening required ‘../vendor/codeigniter4/framework/system/bootstrap.php’ #3021
- Comments
- How do I solve the error «Fatal error: require(): Failed opening required ‘../vendor/autoload.php’ (include_path=’C:xamppphpPEAR’) ?»
- 2 Answers 2
- Проблема с “open_basedir restriction in effect.”
- modulator
- How do I resolve a PHP error «Failed opening required» in a symlink context?
- 1 Answer 1
PHP Fatal error: Unknown: Failed opening required
На сайте посыпались в большом количестве ошибки
PHP Fatal error: Unknown: Failed opening required ‘тут_путь_к_файлу’ (include_path=’.:/usr/local/lib/php’) in Unknown on line 0
При этом страница открывается через раз после рефреша.
Ошибка возникла после установки PHP 5.3.0 первый вариант решения этой ошибки помог, но ненадолго.
PHP Fatal error: Unknown: Failed opening required появляется когда выполняются три условия:
1. для виртуального домена или в самой конфигурации PHP используется опция open_basedir, препятствующая «выходу» скриптов «за пределы дозволенного».
2. в php-скрипте используется include или require
3. и, собственно, стоит PHP 5.3.0 в конфигурации по умолчанию (для переменной include_path).
В php.ini, по умолчанию, для include_path (аналог переменной окружения PATH) используется значение «.;/path/to/php/pear», где путь «/path/to/php/pear» зависит от операционной системы и параметров компиляции. Для Linux-систем этот путь /usr/local/lib/php
Если внимательно посмотреть в текст ошибки (include_path=’.:/usr/local/lib/php’), то после «точки», стоит «двоеточие» вместо «точки с запятой». По логике вещей, достаточно заменить этот символ, но это, к сожалению, не помогло:
— открываем файл конфигурации php.ini
— ищем ;include_path = «.:/php/includes» (в принципе этот пункт можно пропустить) и после этой строчки
— прописываем include_path = «.;/usr/local/lib/php»
— рестарт Apache.
Как уже говорил, это помогло ненадолго.
В данный момент вариантов действий три:
— поставить 5.3-dev отсюда http://snaps.php.net/ (не пробовал)
— поставить последнюю версию php ветки 5.2.х (что собственно и сделал)
8 responses to “ PHP Fatal error: Unknown: Failed opening required ”
добрый день
у меня та же проблема возникла. Вы не нашли другого решения кроме как переустанавливать php?
Давненько это было. Подобной ошибки больше не возникало, когда использовал 5.3.8 и старше, поэтому не было необходимости искать других решений. Сейчас стоит ветка 5.4.х
Покажите полный текст своей ошибки, возможно там проблема в другом будет.
Fatal error: require_once(): Failed opening required ‘/var/www/clients/client1/web221/web/engine/init.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/clients/client1/web221/web/index.php on line 35
1. engine/init.php на месте?
2. open_basedir используется?
1. engine/init.php Самой папки даже нет(
2. Вроде нет!
Fatal error: Call to undefined function clean_url() in /var/www/clients/client1/web221/web/index.php on line 37
вот такая ошибка как создал engine/init.php
Что делать подскажите? пожалуйста! просто я Только начинаю работать в DLE
Call to undefined function clean_url()
Источник
Fatal error: require(): Failed opening required ‘../vendor/codeigniter4/framework/system/bootstrap.php’ #3021
my error is
PHP Warning: require(D:xampphtdocsmyCIappappConfig/../../vendor/codeignite
r4/framework/system/bootstrap.php): failed to open stream: No such file or direc
tory in D:xampphtdocsmyCIappspark on line 44
Warning: require(D:xampphtdocsmyCIappappConfig/../../vendor/codeigniter4/fr
amework/system/bootstrap.php): failed to open stream: No such file or directory
in D:xampphtdocsmyCIappspark on line 44
PHP Fatal error: require(): Failed opening required ‘D:xampphtdocsmyCIappap
pConfig/../../vendor/codeigniter4/framework/system/bootstrap.php’ (include_path
=’D:xamppphpPEAR’) in D:xampphtdocsmyCIappspark on line 44
Fatal error: require(): Failed opening required ‘D:xampphtdocsmyCIappappCon
fig/../../vendor/codeigniter4/framework/system/bootstrap.php’ (include_path=’D:
xamppphpPEAR’) in D:xampphtdocsmyCIappspark on line 44
The text was updated successfully, but these errors were encountered:
Run composer install
i have another problem :
Your requirements could not be resolved to an installable set of packages.
Problem 1
— codeigniter4/framework v4.0.3 requires ext-intl * -> the requested PHP extension intl is missing from your system.
— codeigniter4/framework v4.0.2 requires ext-intl * -> the requested PHP extension intl is missing from your system.
— codeigniter4/framework v4.0.1 requires ext-intl * -> the requested PHP extension intl is missing from your system.
— codeigniter4/framework 4.0.0 requires ext-intl * -> the requested PHP extension intl is missing from your system.
— Installation request for codeigniter4/framework ^4 -> satisfiable by codeigniter4/framework[4.0.0, v4.0.1, v4.0.2, v4.0.3].
To enable extensions, verify that they are enabled in your .ini files:
— C:xamppphpphp.ini
You can also run php —ini inside terminal to see which files are used by PHP in CLI mode.
Try composer commands;
composer update —ignore-platform-reqs
You need to enable the intl extension in your php.ini, it’s part of server requirements for Codeigniter 4, they state that in the readme page. https://github.com/codeigniter4/CodeIgniter4#server-requirements
Please, use the forum for the support questions.
Источник
How do I solve the error «Fatal error: require(): Failed opening required ‘../vendor/autoload.php’ (include_path=’C:xamppphpPEAR’) ?»
So I am using vlucas/phpdotenv in my php application to store and use environment variables. I have created a db.php file which contains the configuration of my database connection. The folder structure is root/config/db.php.
I have require(‘../vendor/autoload.php’); in the db.php file and then I have used
to access the environment variables since the .env file is in the root of the directory. It all works perfectly fine when i access the db.php file on the server but when I include this file in the register.php file which is in the root I get the error «Fatal error: require(): Failed opening required ‘../vendor/autoload.php’ (include_path=’C:xamppphpPEAR’)».
However when I change the directory of the autoload.php to match the path I then get this error: «Uncaught DotenvExceptionInvalidPathException: Unable to read any of the environment file(s) at [../.env].»
Can someone please help me out here? Thank you.
2 Answers 2
It looks like you’re using a relative path, but expecting it to function like an absolute path.
the ../ notation meant the parent directory, so if you move the file the parent directory changes also.
Instead of working relatively, I prefer to set a base and work upwards.
Use $_SERVER[‘DOCUMENT_ROOT’] , which is the file path to the root of your application.
Then use the same notation in you createImmutable static call. I don’t know where you’re supposed to be pointing that to. If it’s the root, use.
So let’s look at this. Your directory structure seems to be something like this:
There are several problems with this. One of them is: Files that should not be accessible by web browsers are accessible. (try to call your-domain.com/.env If you didn’t protect this by a .htaccess file, then you’ll leak your database information to public)
But coming back to your problem: ../ is a relative path. Relative to the file, that was the entry point for the call. Let’s look at it: If you call config/db.php , then the current working directory will be config and ../ will point to the root path. If you call register.php , then the current working directory will be the root path and ../ will point to the parent directory.
You should go with something like this:
Every file in public should include bootstrap.php , where dotenv will be executed. And instead of something like ‘./env’ , you can use __DIR__/ . ‘.env’ . There are several benefits from this:
- You don’t risk leaking sensible files/data
- You always have the same include path and don’t have to worry, from where to call this file
- You have to configure your server to serve the public folder instead of the root directory.
Источник
Проблема с “open_basedir restriction in effect.”
modulator
Новичок
Проблема с “open_basedir restriction in effect.”
Постоянно получаю ошибку:
PHP Warning: Unknown: open_basedir restriction in effect. File(/Home/ localhost.ru /public_schet/schet.php) is not within the allowed path(s): (/Home/localhost.ru/.includes/;/Home/.includes/) in Unknown on line 0
PHP Warning: Unknown: failed to open stream: Operation not permitted in Unknown on line 0
Причем в “open_basedir” чётко указано:
PHP_Admin_Value open_basedir «/Home/localhost.ru/;/Home/.includes/»
а в
PHP_Admin_Value include_path «/Home/localhost.ru/.includes/;/Home/.includes/»
Почему PHP вдруг начинает путать значения этих параметров, происходит очень часто и со временем Apache вылетает?
Вот настройки одного из хостов в файле: httpd-vhosts.conf
127.0.0.1:80 и localhost.ru — заменены для этого форума, на самом деле там реальный ip и url!
ServerName schet.localhost.ru
ServerAlias www.schet.localhost.ru
ServerAdmin [email protected]
DocumentRoot /Home/localhost.ru/public_schet/
ErrorLog /Home/localhost.ru/logs/schet.localhost.ru_Error.log
CustomLog /Home/localhost.ru/logs/schet.localhost.ru_Access.log common
PHP_Admin_Value error_log «/Home/localhost.ru/logs/PHP_schet_Errors.log»
PHP_Admin_Value open_basedir «/Home/localhost.ru/;/Home/.includes/»
PHP_Admin_Value include_path «/Home/localhost.ru/.includes/;/Home/.includes/»
PHP_Admin_Value doc_root «/Home/localhost.ru/»
PHP_Admin_Value upload_tmp_dir «/Home/localhost.ru/temp/»
PHP_Admin_Value session.save_path «/Home/localhost.ru/temp/»
Где чётко прописаны: “PHP_Admin_Value open_basedir” и ”PHP_Admin_Value include_path” для данного хоста.
Почему вдруг при некоторых вызовах файла “schet.php” расположенного: ”/Home/localhost.ru/public_schet/schet.php” что не противоречит: (PHP_Admin_Value open_basedir «/Home/localhost.ru/;/Home/.includes/») выдается ошибка:
PHP Warning: Unknown: open_basedir restriction in effect. File(/Home/localhost.ru/public_schet/schet.php) is not within the allowed path(s): (/Home/localhost.ru/.includes/;/Home/.includes/) in Unknown on line 0
Где “open_basedir” вдруг начинает брать данные из “PHP_Admin_Value include_path” .
Такая же история творится и с другими хостами.
Кто сталкивался с таким или знает, что конкретно делать просьба помогите…
Источник
How do I resolve a PHP error «Failed opening required» in a symlink context?
I am running Apache/PHP on MacOS X Lion 10.7.4. My directory structure is set up as so:
where epwbst/ is a symlink inside of
If I put test.php inside of the Sites/ directory, Apache serves up the file correctly; it spews out phpinfo() like it is supposed to. If I put the same file under the symlink, I get this error:
Just to be sure that Apache was working, I created a test html file under
/Sites/epwbst/ and Apache served it up as expected.
Why can’t Apache run php under my symlinked directory?
1 Answer 1
Okay, this drove me nuts for hours. It is a permissions issue, but not how one might think. The problem rests with the permissions of the symbolic link itself:
Here’s the rub: chmod won’t normally change the permissions on symbolic links, because (with the apparent exception of php5_module and some other cases beyond the scope of this answer) those permissions are largely irrelevant as they are ignored in nearly all contexts. Here’s the fix:
Note the -h . From the man page:
For some reason, php5_module actually pays attention to the permissions on the symbolic link. If they are too restrictive, php5_module will refuse to see the target, even if the httpd user could otherwise read and run that very same target using /usr/bin/php .
Consider the following:
So far, so good. Now consider:
Hmmm. My httpd runs as user _www , so let’s check to see if that user can read . /foo/info.php :
Yup. Now let’s see if that user can run . /foo/info.php :
Yes?! WTF?! Grrr! Now repair it:
So, yes. It appears that php5_module does something paranoid and nonstandard. This may have gone overlooked as umask often defaults to 022 , which will at least create symbolic links with 755 . Also, many filesystems (not HFS+) impose at the kernel level permissions of 777 during symbolic link creation, irrespective of umask .
You and I appear to be the two people in the solar system running Apache+PHP on HFS+ while setting our umask to something more restrictive than the default. I’ll bet you even use case-sensitive HFS+, too. ;o)
Источник
WordPress is so popular that several WordPress Developers and company have created plugins for all purposes. You can literally achieve anything with WordPress and due to this the most irritating error appears on your WordPress site.
Known as the Fatal Error.
So, how to fix WordPress Fatal Error the easy way.
This is what made WordPress so popular, but with this comes the notorious “WordPress Fatal Error”.
Fatal Error is an error where the WordPress stops working completely due to an error which was caused in a plugin or theme. This error is mostly due to a conflict between a theme or plugin with WordPress.
In WordPress, WooCommerce is also used by several website owners to run an eCommerce website on WordPress.
WooCommerce also depends on plugins for its extra functionality. This sometimes makes the store owner face weird problems like Fatal Error or Maximum Execution Time Error.
If you are facing Maximum Execution Time Exceeded WordPress Error, then we have a detailed post on How To Fix Fatal Error Maximum Execution Time Exceeded WordPress Error.
Disclosure: I may receive affiliate compensation for some of the links below at no cost to you if you decide to purchase a paid plan. You can read our affiliate disclosure in our privacy policy.
The method that we are sharing is easy but you need to have paitence. In 90% cases this method solves the Fatal Error WordPress and Fatal Error WooCommerce problem.
The method doesn’t require you to have any technical knowledge or any programming skills.
So, I hope you have some time to go through the tutorial and fixing the Fatal error problem.
So Lets get started 😃.
How To Fix Fatal Error WordPress?
So, lets get started first with debugging.
Case 1 – The 90% Cases
If you have recently installed or updated any plugin or theme. Then in most of the cases the problem is with that particular plugin or theme.
So let’s assume that the problem was in a plugin called – “Niraj the Blogger“. I know, there’s no plugin by that name and Name is like a Movie.
Case 2 – The Unknown
But what If you don’t know why you are facing the WordPress Fatal Error. Whether its a Plugin or theme.
Then, what can you do?
Solution – Fixing the fatal error
Whether you know why the fatal error has occurred or you don’t have even 1% Idea why it happened.
Here is what you need to do to find the fatal Error.
- Login in to your Hosting Panel / cPanel.
- Then go to File Manager in your Hosting Panel.
- Navigate to the WordPress Folder.
- Find error.log / debug.log file.
- You can find this file in Root Folder / WP-Content Folder.
- Open the error.log file and check for the latest error with date and time given in the error log.
- The error log records the file path where the error was triggered.
- Now you can easily find the theme or plugin that caused this error.
- The error log will contain the file path – “/home/yourusername/public_html/wp-content/plugins/niraj-the-blogger/plugin-file.php“.
- This is the plugin, you just need to deactivate the plugin to get your WordPress back to Normal.
Deactivating the plugin without the admin panel is very easy. Now since you are already logged in to your cPanel and you are currently in your WordPress root directory.
Now you need to navigate to WordPress Root Folder -> WP-Content -> Plugins and rename the particular plugin folder. Like “niraj-the-blogger ” to something like “BACKUP-niraj-the-blogger“.
Now login to your WordPress Admin section and visit the WP_Admin -> Plugins. You will find an error notice that the plugin has been deactivated.
Now, check whether the Fatal Error has been fixed or not. In most cases it has been fixed and you will be able to get access to the wp-admin.
Note: If the particular folder method doesn’t work, then it means the error is in another plugin. To fix it, rename the plugins folder to plugins2. The folder is located in WordPress root -> WP-Contents.
How To Fix Fatal Error WooCommerce?
Fixing WooCommerce Errors are a little different. Although using the WordPress fatal error method you can fix it. But this sometimes don’t work on WooCommerce.
Or what if you just want to fix the WooCommerce error which the rest of your website and blog to work like normal.
Then, this is what you will do to fix the WooCommerce Fatal error.
- Login to cPanel -> File Manager.
- Navigate to WordPress Root Folder -> WP-contents -> PLugins
- Rename the WooCommerce folder to “BACKUP-woocommerce”.
- Check the fatal error. It should have been fixed.
By deactivating the WooCommerce, most of the WooCommerce plugins will stop working. Which will also stop the plugin to work which is causing the Fatal error.
But wait, the fatal error has not been fixed.
Now you need to find the culprit, oh I mean the Plugin that is causing the fatal error.
Here is what you need to do to find the plugin.
- Login to WP-Admin
- Go to WP-Admin -> Plugins -> Installed Plugins.
- Deactivate all the plugins that are related with woocommerce.
- Now go back to your cPanel and rename the “BACKUP-woocommer” plugin to “woocommerce”.
- Activate the woocommerce from your WP-admin.
- Now you need to find the Culprit plugin 🕵️.
- To find it, start activating the plugins related to woocommerce. One-by-one.
- You will find that while doing it one-by-one. You will encounter the Fatal error.
- Now you know the plugin name.
- Go to cPanel -> File Manager -> WordPress Root -> WP-Contents -> Plugins and delete the particular plugin folder.
- Note: Delete the plugin folder that caused the error, not the Plugins folder.
Try logging in back to your WP-Admin. The error has been fixed.
Avoid that plugin as it is resulting a fatal error. If you have purchased this plugin. Then contact the plugin developer and ask them to check for the error.
They may come up with a solution to make that plugin work without throwing a fatal error.
How To Fix Fatal Error using Database Method? 🕵️
Fixing using the database method is totally different when it comes to process it but the way WordPress processes it is totally same like the above methods.
Let me explain How?
When we rename any particular plugin folder to a different name, the WordPress database will treat that plugin as deactivated.
Because all active plugins are saved into database in an array. The array contains the filepath of the plugins. Since now the filepath has been changed, wordpress will not find the plugin in that filepath which is saved in the database.
So, the WordPress system will trigger an error popup that only admin can see.
The Database method is also the same, here we will delete the filepath of the plugin. So that will make the plugin deactivated.
Basically it’s the same method. 2 + 3 = 5 or 3 + 2 = 5. So if you are comfortable with the database method, I have given the complete tutorial below.
Note: Database method is a risky way, since you will be interacting with the WordPress Database directly. If you did any thing wrong, your entire WordPress may stop working.
- Login to your cPanel.
- Search for phpMyAdmin and click on it.
- This will open your database.
- Now Click on your database name on the left.
[image] - select “wp_options”.
[image] - Search for “active_plugins”.
[image] - Click on edit button. This will open a section, copy everything from “option_value” and save it to a notepad.
- Now delete the content inside “option_value” and save it.
- By doing this, it will deactivate the plugins and your WordPress will be back to normal.
- Incase you have a problem in your Theme, then you need to search for “template” and “stylesheet”.
- Now repeat the step 7 and 8. This will deactivate the current theme and switch to the default theme.
So this is how the database method works. You can fix the WordPress fatal error using this method, but you need to be little careful while doing it.
Get Professional Help? 😃
If you are overwhelmed with all this methods and don’t know how to to do it. Then you must visit GloriousThemes.com.
GloriousThemes is a WordPress Product company and the best thing I like is that they also provide WordPress Services.
You can easily hire them for any WordPress bugs and Error Fixing for as low as $30. They provide you 100% Satisfaction or Money return Guarantee. They also have 24/7 WordPress Management Service where you focus on your work, while they maintain your websites.
Visit Gloriousthemes.com/services
Conclusion
I hope this article has helped you to fix fatal Error on your WordPress website. If you have any queries, you can comment below or contact us.
Fatal Errors are the most troublesome Errors in WordPress and WooCommerce. This error is sometimes so notorious that it happens on on front-end. Which means the WP-Admin will keep working while the frontend is dead or sometimes vice-versa.
We love the simple technique of folder renaming that allows you to simply debug the error and fix it easily.
You can also subscribe to our YouTube and Like and Follow us on Facebook, Twitter and Instagram.
If your WordPress site displays an error like:
Warning: require(/home/content/22/7568022/html/partisanissues/wp-includes/load.php): failed to open stream: No such file or directory in /home/content/22/7568022/html/partisanissues/wp-settings.php on line 19
Fatal error: require(): Failed opening required ‘/home/content/22/7568022/html/partisanissues/wp-includes/load.php’ (include_path=’.:/usr/local/php5_6/lib/php’) in /home/content/22/7568022/html/partisanissues/wp-settings.php on line 19
the problem is likely that your WordPress installation is corrupt. I have only seen this occur with failed automatic upgrades.
Fortunately, there is an easy fix.
- Surf to wordpress.org/download and download the version of WordPress you think the system was using. That is most likely the current version as shown on wordpress.org/download
- Unzip the WordPress installation files
- Use FileZilla (or whatever file manager your host provides or any other FTP client) to open an FTP session to your host
- Rename the WP-INCLUDES folder to WP-INCLUDES-DEL-ME
- Use FileZilla (or whateva’) to copy the WP-INCLUDES folder from the fresh WordPress install you just downloaded and unzipped to your site
Check your site. If it is up skip the end of this article, titled REINSTALL WORDPRESS. If it is still down read follow the same procedure as shown above, but this time with the WP-INCLUDES folder.
Check your site. If it is up skip the end of this article, titled REINSTALL WORDPRESS. If it is still down read follow the same procedure as shown above, but this time:
- Consider copying ALL of your site from your host to your PC so you have a backup before following these steps
- It is CRITICAL that you do NOT overwrite your WP-CONFIG.PHP file, so rename or delete the one from the fresh WordPress installation you just downloaded.
- Personally I like to keep things clear by renaming the file to WP-CONFIG-FACTORY.PHP
- Copy the entire freshly downloaded WordPress installation to your site.
- Yes, you should overwrite all of the existing files… that is the point.
REINSTALL WORDPRESS
Once you have your site functional again, WordPress will not likely be too happy and so to avoid problems, have WordPress reinstall itself properly:
- Login to your admin portal www.<YourSite.com>/wp-admin
- On the DASHBOARD you will likely see:
An automated WordPress update has failed to complete – please attempt the update again now
and you should click the please attempt the update again now linkIf you don’t see that message/link, click DASHBOARD > UPDATES - Click the REINSTALL WORDPRESS button
- Wait for it to complete
WordPress
WordPress — простая в использовании система управления контентом. Для нее создано множество плагинов и тем, благодаря которым сайт может выполнять любые задачи. Однако при их установке могут возникнуть различные ошибки, препятствующие корректной работе сайта. Опираясь на рекомендации данной статьи, вы сможете самостоятельно исправить большинство ошибок, которые встретите при работе с сайтом.
Internal Server Error
Сообщение Internal Server Error выводится, когда веб-сервер не смог обработать запрос к сайту из-за ошибок в файле .htaccess. Найдите файл .htaccess в корневой директории сайта, переименуйте его и создайте новый файл с именем .htaccess, в который добавьте стандартные правила WordPress:
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
Вновь перейдите на сайт и убедитесь, что при переходе по его страницам ошибка не возникает.
Некоторые плагины требуют собственных директив в файле .htaccess. Чтобы правила были добавлены автоматически, последовательно перезапустите все плагины в соответствующем разделе административной панели сайта.
На сайте возникли временные проблемы технического характера
Данное уведомление является внутренним сообщением WordPress, свидетельствующим о наличии ошибок в скриптах вашего сайта.
Чтобы узнать причины ошибки, в начало файла .htaccess добавьте директиву:
php_value error_log /home/user/domains/domain.ru/errors.log
где user — ваш логин, domain.ru — адрес вашего сайта.
Затем повторно обратитесь к странице, на которой возникает ошибка. После этого в файле лога появится сообщение о причине возникающей неполадки.
Если после обновления страницы, на которой вы наблюдаете ошибку, файл errors.log не появился, в файле wp-config.php в корневой директории сайта найдите функцию:
define('WP_DEBUG', false);
и измените её значение на ‘true’, чтобы она имела следующий вид:
define('WP_DEBUG', true);
Сохраните изменения в файле и обратитесь к странице повторно: на ней появятся ошибки, которые возникли на сервере при обработке запроса к сайту.
Простейшим способом вернуть сайт к рабочему состоянию будет восстановление его содержимого из резервной копии до состояния, когда он работал корректно.
Если восстановление не даст результата, или по каким-то причинам выполнить его невозможно, следует приступить к диагностике причин ошибки, предварительно создав резервную копию файлов и баз данных.
Подробнее ознакомиться с информацией о возникающих ошибках вы можете в инструкции.
Наиболее популярные ошибки, возникающие при работе с системой WordPress, мы рассмотрим ниже.
Плагины
Причиной ошибки в работе сайта может стать некорректная работа плагинов после их установки или обновления.
Если в выводе информации об ошибке вы видите путь, который ссылается на директорию /home/user/domains/domain.ru/public_html/plugins/plugin/ , например:
PHP Fatal error: Call to a member function format() on a non-object in /home/user/domains/domain.ru/public_html/plugins/quickicon/phpversioncheck/phpversioncheck.php on line 174
С помощью раздела «Файловый менеджер» Панели управления найдите директорию плагина и переименуйте её, после чего проверьте работу сайта.
Если сайт работает корректно, перейдите в административную панель сайта, раздел «Плагины» → «Установленные» и удалите плагин.
Если плагин был важен для работы вашего сайта, попробуйте установить его повторно или использовать плагин с аналогичным функционалом с помощью раздела «Плагины» в административной панели.
Неверная версия PHP
Различные версии WordPress, а также дополнительные плагины работают только на определенной версии PHP. Несоответствие используемой и требуемой версии PHP является одной из наиболее часто встречаемых причин ошибки 500:
Parse error: syntax error, unexpected T_FUNCTION in /home/user/domains/domain.ru/public_html/wp-config.php on line 94
PHP Fatal error: Uncaught Error: Call to undefined function ereg() in /home/user/domains/domain.ru/public_html/wp-content/plugins/whydowork-adsense/whydowork_adsense.php:332
Перейдите в раздел «Сайты» → «Веб-серверы» Панели управления, найдите веб-сервер, на котором размещен интересующий вас сайт, и последовательно изменяйте используемую на нем версию PHP, пока работа сайта не возобновится.
Недостаток оперативной памяти
По умолчанию для выполнения PHP-скриптов сайта доступно 128МБ оперативной памяти.
Для работы многих скриптов и плагинов требуется больший объем оперативной памяти. Если вы столкнулись с ошибкой:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 81 bytes) in /home/username/domains/domain.ru/public_html/somescript.php
воспользуйтесь инструкцией.
Отсутствует файл/директория для работы скрипта
Причиной ошибки может быть отсутствие требуемого для работы системы файла или некорректно установленные на него права:
Fatal error: require(): Failed opening required '/home/user/domains/domain.ru/public_html/wp-includes/load.php' (include_path='.:/opt/remi/php71/root/usr/share/pear:/opt/remi/php71/root/usr/share/php:/usr/share/pear:/usr/share/php') in /home/user/domains/domain.ru/public_html/wp-settings.php on line 19
С помощью раздела «Файловый менеджер» найдите файл, который не удается прочесть.
Убедитесь, что права на файл соответствуют 644. В случае необходимости измените их в столбце «Права».
Если файл отсутствует, восстановите его из резервной копии.
Если файл найти не удается, и он также отсутствует в резервных копиях, загрузите «чистый» образ используемой на вашем сайте версии WordPress с официального сайта, найдите необходимый файл и разместите его на сайте.
Узнать версию WordPress вы можете на главной странице административной части вашего сайта domain.ru/wp-admin/index.php в блоке «На виду».
При отсутствии доступа в административную часть вы можете узнать используемою версию в файле /home/user/domains/domain.ru/public_html/wp-includes/version.php в строке:
$wp_version = '5.2.5';
Ошибка соединения с базой данных
Ошибка «Error establishing a database connection» свидетельствует о том, что сайту не удалось выполнить соединение с базой данных.
С помощью раздела «Файловый менеджер» Панели управления перейдите в директорию /home/user/domains/domain.ru/public_html/ и найдите в ней файл wp-config.php. Убедитесь, что значения в следующих строках совпадают с теми, которые указаны в базе данных для вашего сайта в разделе «Базы данных»:
define('DB_NAME', ‘user_dbname);
define('DB_USER', 'user_dbuser');
define('DB_PASSWORD', 'password’);
Измените значения на те, которые вы использовали при создании базы данных. Если вы забыли пароль, измените его в разделе «Базы данных» Панели управления.
Утерян доступ к административной части WordPress
Вы можете сбросить пароль администратора на странице:
domain.ru/wp-login.php?action=lostpassword
где domain.ru — адрес вашего сайта.
После сброса новый пароль придет на почту администратора.
Если пароль не приходит, или доступ к почте администратора сайта утерян, вы можете изменить его вручную.
Для этого в конфигурационном файле сайта (wp-config.php) найдите строку:
define('DB_NAME', 'db_name');
db_name — имя базы данных, которую использует ваш сайт.
Перейдите в раздел «Базы данных» Панели управления, а затем в PhpMyAdmin, кликните на имя базы в левом столбце, в выпадающем списке выберите таблицу «wp_users».
В списке пользователей нажмите кнопку «изменить» слева от аккаунта администратора ( в большинстве случаев логином администратора будет admin).
Очистите значение строки user_pass, введите новый пароль, из выпадающего списка выберите функцию MD5 и нажмите «Вперед».
Переадресация на сторонние сайты при обращении к сайту
Наиболее частой причиной является смена имени сайта в настройках сайта. Чтобы исправить ошибку, перейдите в раздел «Базы данных» Панели управления → PHPMyAdmin → выберите базу данных, которую использует ваш сайт → найдите таблицу «wp_options».
Если в значениях строк siteurl и home указан адрес, отличный от адреса вашего сайта — верните корректные значения и сохраните изменения.
Для того, чтобы ограничить доступ злоумышленников к вашему сайту, измените пароли для доступа:
- в административную панель сайта;
- к Панели управления аккаунтом хостинга;
- данные для подключения по FTP.
Также выполните проверку файлов сайта на наличие вредоносного программного обеспечения с помощью утилиты ХакСкан. Сделать это можно в Панели управления → «Сайты» → «ХакСкан».
Для удаления вредоносного кода воспользуйтесь инструкцией.
Если вам не удалось удалить вредоносный код самостоятельно, обратитесь разработчику вашего сайта.
Как избежать ошибок в дальнейшем?
- Своевременно обновляйте версию WordPress и компоненты сайта.
- Устанавливайте только проверенные плагины и темы из официального магазина WordPress.
- Выполните шаги по оптимизации системы, описанные в статье.
- Настройте автоматическую проверку файлов аккаунта в разделе «ХакСкан» Панели управления.
- В случае возникновения сложностей обращайтесь за помощью в службу поддержки.