Php warning fopen failed to open stream no such file or directory in

Ошибка в админке wordpress «failed to open stream: No such file or directory» — как исправить?

Всем привет! Есть сайт на wordpress с установленным плагином WP Hide Post. Есть необходимость переноса сайта на новый хостинг, но решил перестраховаться и проверить его работоспособность после импорта на локальный Open Server.
И не зря — вверху админпанели получаю следующие ошибки:

fopen(C:\OSPanel\domains\localhost\site/wp-content/plugins/C:\OSPanel\domains\localhost\site\wp-content\plugins\wp-hide-post\wp-hide-post.php): failed to open stream: No such file or directory in
in C:\OSPanel\domains\localhost\site\wp-includes\functions.php on line 4848

Warning: fread() expects parameter 1 to be resource, boolean given in C:\OSPanel\domains\localhost\site\wp-includes\functions.php on line 4851

Warning: fclose() expects parameter 1 to be resource, boolean given in C:\OSPanel\domains\localhost\site\wp-includes\functions.php on line 4854

На которые указывает следующие строки кода в functions.php

/** * Retrieve metadata from a file. * * Searches for metadata in the first 8kiB of a file, such as a plugin or theme. * Each piece of metadata must be on its own line. Fields can not span multiple * lines, the value will get cut at the end of the first line. * * If the file data is not within that first 8kiB, then the author should correct * their plugin file and move the data headers to the top. * * @link https://codex.wordpress.org/File_Header * * @since 2.9.0 * * @param string $file Path to the file. * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name'). * @param string $context Optional. If specified adds filter hook . * Default empty. * @return array Array of file headers in `HeaderKey => Header Value` format. */ function get_file_data( $file, $default_headers, $context = '' ) < // We don't need to write to the file, so just open for reading. $fp = fopen( $file, 'r' ); // Pull only the first 8kiB of the file in. $file_data = fread( $fp, 8192 ); // PHP will close file handle, but we are good citizens. fclose( $fp ); // Make sure we catch CR-only line endings. $file_data = str_replace( "\r", "\n", $file_data ); . >

Как можно их исправить? Если плагин деактивирую — ошибка исчезает. Как можно исправить ошибки в включенным плагином?

Или это ошибка только из-за локального сервера? Кеш очищал.

Средний 2 комментария

Источник

PHP – Failed to open stream : No such file or directory

In PHP scripts, whether calling include() , require() , fopen() , or their derivatives such as include_once , require_once , or even, move_uploaded_file() , one often runs into an error or warning:

Failed to open stream : No such file or directory.

What is a good process to quickly find the root cause of the problem?

Читайте также:  Удалить все переменные python

Solution

There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.

Let’s consider that we are troubleshooting the following line:

Checklist

1. Check the file path for typos

  • either check manually (by visually checking the path)
  • or move whatever is called by require* or include* to its own variable, echo it, copy it, and try accessing it from a terminal:
$path = "/path/to/file"; echo "Path : $path"; require "$path"; 

2. Check that the file path is correct regarding relative vs absolute path considerations

  • if it is starting by a forward slash “/” then it is not referring to the root of your website’s folder (the document root), but to the root of your server.
    • for example, your website’s directory might be /users/tony/htdocs
    • thus, not relative to the path of your web site’s root, or to the file where you are typing
    • for that reason, always use absolute file paths

    In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :

    1. use require __DIR__ . «/relative/path/from/current/file» . The __DIR__ magic constant returns the directory of the current file.
    2. define a SITE_ROOT constant yourself :
    3. at the root of your web site’s directory, create a file, e.g. config.php
    4. in config.php , write
    require_once __DIR__."/../config.php"; . require_once SITE_ROOT."/other/file.php"; 

    These 2 practices also make your application more portable because it does not rely on ini settings like the include path.

    3. Check your include path

    Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.

    Such an inclusion will look like this :

    include "Zend/Mail/Protocol/Imap.php" 

    In that case, you will want to make sure that the folder where “Zend” is, is part of the include path.

    You can check the include path with :

    You can add a folder to it with :

    set_include_path(get_include_path().":"."/path/to/new/folder"); 

    4. Check that your server has access to that file

    It might be that all together, the user running the server process (Apache or PHP) simply doesn’t have permission to read from or write to that file.

    To check under what user the server is running you can use posix_getpwuid :

    $user = posix_getpwuid(posix_geteuid()); var_dump($user); 

    To find out the permissions on the file, type the following command in the terminal:

    5. Check PHP settings

    If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.

    Three settings could be relevant :

    1. open_basedir
      • If this is set PHP won’t be able to access any file outside of the specified directory (not even through a symbolic link).
      • However, the default behavior is for it not to be set in which case there is no restriction
      • This can be checked by either calling phpinfo() or by using ini_get(«open_basedir»)
      • You can change the setting either by editing your php.ini file or your httpd.conf file
    2. safe mode
      • if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is still being supported.
    3. allow_url_fopen and allow_url_include
      • this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system
      • this can be checked with ini_get(«allow_url_include») and set with ini_set(«allow_url_include», «1»)

    Corner cases

    If none of the above enabled to diagnose the problem, here are some special situations that could happen :

    1. The inclusion of library relying on the include path

    It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :

    require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php" 

    But then you still get the same kind of error.

    This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.

    For example, the Zend framework file mentioned before could have the following include :

    include "Zend/Mail/Protocol/Exception.php" 

    which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.

    In such a case, the only practical solution is to add the directory to your include path.

    2. SELinux

    If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.

    To check whether SELinux is enabled on your system, run the sestatus command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.

    To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.

    If you no longer have the problem with SELinux turned off, then this is the root cause.

    To solve it, you will have to configure SELinux accordingly.

    The following context types will be necessary :

    • httpd_sys_content_t for files that you want your server to be able to read
    • httpd_sys_rw_content_t for files on which you want read and write access
    • httpd_log_t for log files
    • httpd_cache_t for the cache directory

    For example, to assign the httpd_sys_content_t context type to your website root directory, run :

    semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?" restorecon -Rv /path/to/root 

    If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs boolean :

    setsebool -P httpd_enable_homedirs 1 

    In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.

    3. Symfony

    If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app’s cache hasn’t been reset, either because app/cache has been uploaded, or that cache hasn’t been cleared.

    You can test and fix this by running the following console command:

    4. Non ACSII characters inside Zip file

    Apparently, this error can happen also upon calling zip->close() when some files inside the zip have non-ASCII characters in their filename, such as “é”.

    A potential solution is to wrap the file name in utf8_decode() before creating the target file.

    Credits to Fran Cano for identifying and suggesting a solution to this issue

    This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

    Источник

    Ошибка log.php

    NSUN

    Создайте аккаунт или войдите в него для комментирования

    Вы должны быть пользователем, чтобы оставить комментарий

    Создать аккаунт

    Зарегистрируйтесь для получения аккаунта. Это просто!

    Войти

    Уже зарегистрированы? Войдите здесь.

    Похожие публикации

    Ошибка с корзиной

    Ошибка VQMOD

    Ошибка при установке

    После обновления модификатора — ошибка 500

    Подскажите о чем говорит ошибка (куда копать)

    Сейчас на странице 0 пользователей

    Покупателям

    Разработчикам

    Полезная информация

    Последние дополнения

    Движок интернет магазина OpenCart (ocStore) — официальный сайт OpenCartForum.com Powered by Invision Community

    Раздел покупок

    ocStore

    Шаблоны

    OpenCart.Pro

    Важная информация

    На нашем сайте используются файлы cookie и происходит обработка некоторых персональных данных пользователей, чтобы улучшить пользовательский интерфейс. Чтобы узнать для чего и какие персональные данные мы обрабатываем перейдите по ссылке. Если Вы нажмете «Я даю согласие», это означает, что Вы понимаете и принимаете все условия, указанные в этом Уведомлении о Конфиденциальности.

    .sale_block_img<>.sale_block_img .sale_block_img_grid<>.sale_block_img .sale_block_img_grid ul.sale_block_img .sale_block_img_grid ul li.sale_block_img .sale_block_img_grid ul li img

    Источник

    Ошибка в админке wordpress «failed to open stream: No such file or directory» — как исправить?

    Всем привет! Есть сайт на wordpress с установленным плагином WP Hide Post. Есть необходимость переноса сайта на новый хостинг, но решил перестраховаться и проверить его работоспособность после импорта на локальный Open Server.
    И не зря — вверху админпанели получаю следующие ошибки:

    fopen(C:\OSPanel\domains\localhost\site/wp-content/plugins/C:\OSPanel\domains\localhost\site\wp-content\plugins\wp-hide-post\wp-hide-post.php): failed to open stream: No such file or directory in
    in C:\OSPanel\domains\localhost\site\wp-includes\functions.php on line 4848

    Warning: fread() expects parameter 1 to be resource, boolean given in C:\OSPanel\domains\localhost\site\wp-includes\functions.php on line 4851

    Warning: fclose() expects parameter 1 to be resource, boolean given in C:\OSPanel\domains\localhost\site\wp-includes\functions.php on line 4854

    На которые указывает следующие строки кода в functions.php

    /** * Retrieve metadata from a file. * * Searches for metadata in the first 8kiB of a file, such as a plugin or theme. * Each piece of metadata must be on its own line. Fields can not span multiple * lines, the value will get cut at the end of the first line. * * If the file data is not within that first 8kiB, then the author should correct * their plugin file and move the data headers to the top. * * @link https://codex.wordpress.org/File_Header * * @since 2.9.0 * * @param string $file Path to the file. * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name'). * @param string $context Optional. If specified adds filter hook . * Default empty. * @return array Array of file headers in `HeaderKey => Header Value` format. */ function get_file_data( $file, $default_headers, $context = '' ) < // We don't need to write to the file, so just open for reading. $fp = fopen( $file, 'r' ); // Pull only the first 8kiB of the file in. $file_data = fread( $fp, 8192 ); // PHP will close file handle, but we are good citizens. fclose( $fp ); // Make sure we catch CR-only line endings. $file_data = str_replace( "\r", "\n", $file_data ); . >

    Как можно их исправить? Если плагин деактивирую — ошибка исчезает. Как можно исправить ошибки в включенным плагином?

    Или это ошибка только из-за локального сервера? Кеш очищал.

    Средний 2 комментария

    Источник

Оцените статью