Failed to open stream php error

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: F...

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:

require "/path/to/file"

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";
    

    Then, in a terminal:

    cat <file path pasted>
    

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
  • if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
    • 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

Best practices :

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 :

    • at the root of your web site’s directory, create a file, e.g. config.php
    • in config.php, write

      define('SITE_ROOT', __DIR__);
      
    • in every file where you want to reference the site root folder, include config.php, and then use the SITE_ROOT constant wherever you like :

      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 :

echo get_include_path();

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:

ls -l <path/to/file>

and look at permission symbolic notation

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.

setenforce 0

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:

cache:clear

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

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.

Failed to open stream error in WordPress

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.

Regenerate htaccess file in WordPress

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

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.

TroL929

Перенес сайт на новый сервер и после этого отвалилась загрузка файлов. Код в общем стандартный и прежде прекрасно работал (Добавлять пока сюда его не буду)

Выдает «Warning: imagepng(images/upload/1090d639d14df68959c5a1ccb0e47556/logo.png): failed to open stream: Permission denied in /var/www/….»
Пути к файлам проверил. Даже права выставил на 777, но это не помогло. Есть предположение что временный файл пишется не корректно, но как проверить не знаю. Только var_dump($_FILES[«logo»]); но выдает он правильную информацию — и название и вес файла.

Прошу советы что можно еще проверить и какими способами можно проверить источники проблем?


  • Вопрос задан

    более трёх лет назад

  • 6919 просмотров

Есть подозрение, что imagepng() пытается писать в такое место, где у него нет прав.
Попробуйте вместо images/upload... указать абсолютный путь. Проверьте еще раз, есть ли права. И не только на корневую папку images, но и на вложенные.

Пригласить эксперта

Permission denied in /var/www/…. это права доступа !
если у вас на локальной машине это и как правило linux hosts то откройте права для чтения и записи

Перечень мер, если появилась ошибка «Не удалось открыть поток: отказано в доступе».
1. Узнайте код ошибки php. Для этого поместите этот код в начало файла php.
ini_set(‘error_reporting’, E_ALL);ini_set(‘display_errors’, 1);ini_set(‘display_startup_errors’, 1);
2. К папке должен быть доступ 777. Проверьте это.
3. Тег должен иметь атрибут enctype = «multipart/form-data» method = «post».
<form enctype="multipart/form-data" method="post">
4. Откройте и посмотрите массив $ _FILES на сервере.
print_r ($_FILES);
5. Откройте и посмотрите массив $ _FILES на клиенте.
file = document.getElementById(«get_avatar»).files[0];parts = file.name.split(‘.’);
var a = file.size;var b = parts.pop();var c = file.type;alert(a+b+c);
6. Проверьте права пользователя и группы пользователей на каталог.
cd /var/www/your_site/user
ls -l
Подробнее на profi.spage.me/php/check-file-input-on-php-and-jqu…
В вашем случае, проверьте права на директорию images/upload/1090d639d14df68959c5a1ccb0e47556, права должны быть 777 и проверьте права пользователя и группы пользователей на этот каталог.


  • Показать ещё
    Загружается…

09 февр. 2023, в 18:25

5000 руб./за проект

09 февр. 2023, в 18:23

2500 руб./за проект

09 февр. 2023, в 17:54

1000 руб./за проект

Минуточку внимания

do any maintainers want to chime in here? I am also experiencing this. Is it a bug, or the result of us following poor implementation.

What I’m basically doing is:

class SomeClass
{
    $client = ...;  // Injected into constructor (Dependency Injection)
    $promises = [];

    ...

    private function someFunction(int $batchSize = 0)
    {
        foreach ($list as $item) {
            $this->promises[] = $this->client->requestAsync($this->method, $path, $options)->then(
                function ($response) {
                    return $this->processResponse($response);
                },
                function (RequestException $exception) {
                     return $this->handleRequestException($exception);
                }
            );
        }

        // Process promises by batch of 20, since we have no clue how big $list is at any given run
        $offset = 0;
        $batchSize = $batchSize :? count($this->promises);  // if no arg provided, process all promises simultaneously
        $promiseCount = count($this->promises);
        while ($offset < $promiseCount) {
            $promiseSubset = array_slice($this->promises, $offset, $batchSize, true);
            $results = Promiseunwrap($set);
            foreach ($results as $key => $result) {
                $this->data[$key] = $result;
            }
            $offset += $batchSize;
        }
    }

    ...
}

The code works perfectly in most of my use cases, where I don’t set a $batchSize, but rather let all of my requests process at once. This can handle pretty large numbers of requests/responses at once. However, I just created a new use case where the processing load is just too big, and it resulted in the error this issue is about. So, I decided to try to batch the number of promises processed by passing in $batchSize = 20, and the same error results. Even if I pass in $batchSize = 1 it still results in the same error. Basically, it looks like, despite the while loop, all of my promises are getting processed simultaneously… or the temp files that are causing the error aren’t being cleared after each batch unwrap. Am I misunderstanding how unwrap() and promises work?

I too am using a shared single Client object (via Dependency Injection), as is best practice (i think?) as @shtrih mentioned.

I also tried the following configurations in my client, based on @darkot013’s suggestion in #1977, and neither worked:

'curl' => [
    CURLOPT_FORBID_REUSE => true,
    CURLOPT_FRESH_CONNECT => true,
]
'headers' => [
    'Connection' => 'close',
],
'curl' => [
    CURLOPT_FORBID_REUSE => true,
    CURLOPT_FRESH_CONNECT => true,
]
'headers' => [
    'Connection' => 'close'
],
CURLOPT_FORBID_REUSE => true,
CURLOPT_FRESH_CONNECT => true,

I’ve tried those configuration with a plain old default Client, and also with a Client where I injected a HandlerStack containing a CurlHandler into the 'handler' key of the Client config, a la the Guzzle 6 documentation. I am not sure if the 'curl' options do anything if you haven’t injected a CurlHandler. Regardless, none of the above has resolved the error.

I guess now is as good a time as any to mention that I am running Guzzle 6 on PHP 7.2.

This blog post is all about how to handle errors from the PHP file_get_contents function, and others which work like it.

The file_get_contents function will read the contents of a file into a string. For example:

<?php
$text = file_get_contents("hello.txt");
echo $text;

You can try this out on the command-line like so:

$ echo "hello" > hello.txt
$ php test.php 
hello

This function is widely used, but I’ve observed that error handling around it is often not quite right. I’ve fixed a few bugs involving incorrect I/O error handling recently, so here are my thoughts on how it should be done.

How file_get_contents fails

For legacy reasons, this function does not throw an exception when something goes wrong. Instead, it will both log a warning, and return false.

<?php
$filename = "not-a-real-file.txt";
$text = file_get_contents($filename);
echo $text;

Which looks like this when you run it:

$ php test.php 
PHP Warning:  file_get_contents(not-a-real-file.txt): failed to open stream: No such file or directory in test.php on line 3
PHP Stack trace:
PHP   1. {main}() test.php:0
PHP   2. file_get_contents() test.php:3

Warnings are not very useful on their own, because the code will continue on without the correct data.

Error handling in four steps

If anything goes wrong when you are reading a file, your code should be throwing some type of Exception which describes the problem. This allows developers to put a try {} catch {} around it, and avoids nasty surprises where invalid data is used later.

Step 1: Detect that the file was not read

Any call to file_get_contents should be immediately followed by a check for that false return value. This is how you know that there is a problem.

<?php
$filename = "not-a-real-file.txt";
$text = file_get_contents($filename);
if($text === false) {
  throw new Exception("File was not loaded");
}
echo $text;

This now gives both a warning and an uncaught exception:

$ php test.php 
PHP Warning:  file_get_contents(not-a-real-file.txt): failed to open stream: No such file or directory in test.php on line 3
PHP Stack trace:
PHP   1. {main}() test.php:0
PHP   2. file_get_contents() test.php:3
PHP Fatal error:  Uncaught Exception: File was not loaded in test.php:5
Stack trace:
#0 {main}
  thrown in test.php on line 5

Step 2: Suppress the warning

Warnings are usually harmless, but there are several good reasons to suppress them:

  • It ensures that you are not depending on a global error handler (or the absence of one) for correct behaviour.
  • The warning might appear in the middle of the output, depending on php.ini.
  • Warnings can produce a lot of noise in the logs

Use @ to silence any warnings from a function call.

<?php
$filename = "not-a-real-file.txt";
$text = @file_get_contents($filename);
if($text === false) {
  throw new Exception("File was not loaded");
}
echo $text;

The output is now only the uncaught Exception:

$ php test.php 
PHP Fatal error:  Uncaught Exception: File was not loaded in test.php:5
Stack trace:
#0 {main}
  thrown in test.php on line 5

Step 3: Get the reason for the failure

Unfortunately, we lost the “No such file or directory” message, which is pretty important information, which should go in the Exception. This information is retrieved from the old-style error_get_last method.

This function might just return empty data, so you should check that everything is set and non-empty before you try to use it.

<?php
$filename = "not-a-real-file.txt";
error_clear_last();
$text = @file_get_contents($filename);
if($text === false) {
  $e = error_get_last();
  $error = (isset($e) && isset($e['message']) && $e['message'] != "") ?
      $e['message'] : "Check that the file exists and can be read.";
  throw new Exception("File '$filename' was not loaded. $error");
}
echo $text;

This now embeds the failure reason directly in the message.

$ php test.php 
PHP Fatal error:  Uncaught Exception: File 'not-a-real-file.txt' was not loaded. file_get_contents(not-a-real-file.txt): failed to open stream: No such file or directory in test.php:9
Stack trace:
#0 {main}
  thrown in test.php on line 9

Step 4: Add a fallback

The last time I introduced error_clear_last()/get_last_error() into a code-base, I learned out that HHVM does not have these functions.

Call to undefined function error_clear_last()

The fix for this is to write some wrapper code, to verify that each function exists.

<?php
$filename = 'not-a-real-file';
clearLastError();
$text = @file_get_contents($filename);
if ($text === false) {
    $error = getLastErrorOrDefault("Check that the file exists and can be read.");
    throw new Exception("Could not retrieve image data from '$filename'. $error");
}
echo $text;

/**
 * Call error_clear_last() if it exists. This is dependent on which PHP runtime is used.
 */
function clearLastError()
{
    if (function_exists('error_clear_last')) {
        error_clear_last();
    }
}
/**
 * Retrieve the message from error_get_last() if possible. This is very useful for debugging, but it will not
 * always exist or return anything useful.
 */
function getLastErrorOrDefault(string $default)
{
    if (function_exists('error_clear_last')) {
        $e = error_get_last();
        if (isset($e) && isset($e['message']) && $e['message'] != "") {
            return $e['message'];
        }
    }
    return $default;
}

This does the same thing as before, but without breaking other PHP runtimes.

$ php test.php 
PHP Fatal error:  Uncaught Exception: Could not retrieve image data from 'not-a-real-file'. file_get_contents(not-a-real-file): failed to open stream: No such file or directory in test.php:7
Stack trace:
#0 {main}
  thrown in test.php on line 7

Since HHVM is dropping support for PHP, I expect that this last step will soon become unnecessary.

How not to handle errors

Some applications put a series of checks before each I/O operation, and then simply perform the operation with no error checking. An example of this would be:

<?php
$filename = "not-a-real-file.txt";
// Check everything!
if(!file_exists($filename)) {
  throw new Exception("$filename does not exist");
}
if(!is_file($filename)) {
  throw new Exception("$filename is not a file");
}
if(!is_readable($filename)) {
  throw new Exception("$filename cannot be read");
}
// Assume that nothing can possibly go wrong..
$text = @file_get_contents($filename);
echo $text;

You could probably make a reasonable-sounding argument that checks are a good idea, but I consider them to be misguided:

  • If you skip any actual error handling, then your code is going to fail in more surprising ways when you encounter an I/O problem that could not be detected.
  • If you do perform correct error handling as well, then the extra checks add nothing other than more branches to test.

Lastly, beware of false positives. For example, the above snippet will reject HTTP URL’s, which are perfectly valid for file_get_contents.

Conclusion

Most PHP code now uses try/catch/finally blocks to handle problems, but the ecosystem really values backwards compatibility, so existing functions are rarely changed.

The style of error reporting used in these I/O functions is by now a legacy quirk, and should be wrapped to consistently throw a useful Exception.

Samba Shares

If you have a Linux test server and you work from a Windows Client, the Samba share interferes with the chmod command. So, even if you use:

chmod -R 777 myfolder

on the Linux side it is fully possible that the Unix Groupwww-data still doesn’t have write access. One working solution if your share is set up that Windows admins are mapped to root: From Windows, open the Permissions, disable Inheritance for your folder with copy, and then grant full access for www-data.

To add to the (really good) existing answer

Shared Hosting Software

open_basedir is one that can stump you because it can be specified in a web server configuration. While this is easily remedied if you run your own dedicated server, there are some shared hosting software packages out there (like Plesk, cPanel, etc) that will configure a configuration directive on a per-domain basis. Because the software builds the configuration file (i.e. httpd.conf) you cannot change that file directly because the hosting software will just overwrite it when it restarts.

With Plesk, they provide a place to override the provided httpd.conf called vhost.conf. Only the server admin can write this file. The configuration for Apache looks something like this

<Directory /var/www/vhosts/domain.com>
    <IfModule mod_php5.c>
        php_admin_flag engine on
        php_admin_flag safe_mode off
        php_admin_value open_basedir "/var/www/vhosts/domain.com:/tmp:/usr/share/pear:/local/PEAR"
    </IfModule>
</Directory>

Have your server admin consult the manual for the hosting and web server software they use.

File Permissions

It’s important to note that executing a file through your web server is very different from a command line or cron job execution. The big difference is that your web server has its own user and permissions. For security reasons that user is pretty restricted. Apache, for instance, is often apache, www-data or httpd (depending on your server). A cron job or CLI execution has whatever permissions that the user running it has (i.e. running a PHP script as root will execute with permissions of root).

A lot of times people will solve a permissions problem by doing the following (Linux example)

chmod 777 /path/to/file

This is not a smart idea, because the file or directory is now world writable. If you own the server and are the only user then this isn’t such a big deal, but if you’re on a shared hosting environment you’ve just given everyone on your server access.

What you need to do is determine the user(s) that need access and give only those them access. Once you know which users need access you’ll want to make sure that

  1. That user owns the file and possibly the parent directory (especially the parent directory if you want to write files). In most shared hosting environments this won’t be an issue, because your user should own all the files underneath your root. A Linux example is shown below

     chown apache:apache /path/to/file
    
  2. The user, and only that user, has access. In Linux, a good practice would be chmod 600 (only owner can read and write) or chmod 644 (owner can write but everyone can read)

You can read a more extended discussion of Linux/Unix permissions and users here

  1. Look at the exact error

My code worked fine on all machines but only on this one started giving problem (which used to work find I guess). Used echo «document_root» path to debug and also looked closely at the error, found this

Warning:
include(D:/MyProjects/testproject//functions/connections.php):
failed to open stream:

You can easily see where the problems are. The problems are // before functions

$document_root = $_SERVER['DOCUMENT_ROOT'];
echo "root: $document_root";
include($document_root.'/functions/connections.php');

So simply remove the lading / from include and it should work fine. What is interesting is this behaviors is different on different versions. I run the same code on Laptop, Macbook Pro and this PC, all worked fine untill. Hope this helps someone.

  1. Copy past the file location in the browser to make sure file exists. Sometimes files get deleted unexpectedly (happened with me) and it was also the issue in my case.

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:

require "/path/to/file"

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";
    

    Then, in a terminal:

    cat <file path pasted>
    

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
  • if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
    • 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

Best practices :

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 :

    • at the root of your web site’s directory, create a file, e.g. config.php
    • in config.php, write

      define('SITE_ROOT', __DIR__);
      
    • in every file where you want to reference the site root folder, include config.php, and then use the SITE_ROOT constant wherever you like :

      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 :

echo get_include_path();

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:

ls -l <path/to/file>

and look at permission symbolic notation

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.

setenforce 0

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:

cache:clear

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

Вы видите ошибку “Failed to Open Stream” в WordPress? Эта ошибка, как правило, указывает на расположение скриптов, где произошла ошибка. Тем не менее, это довольно сложно для начинающих пользователей, чтобы понять ее. В этой статье мы покажем вам, как легко исправить в WordPress ошибку “Failed to Open Stream”.

Почему происходит ошибка “Failed to Open Stream”?

Перед тем, как попытаться исправить ошибку, было бы полезно понять, что заставляет выводить ошибку “Failed to Open Stream” в WordPress.

Эта ошибка возникает, когда WordPress не может загрузить файл, упомянутый в веб-коде. При возникновении этой ошибки, иногда WordPress продолжит загрузку сайта и только покажет предупреждающее сообщение, в то время как другой сайт на WordPress покажет фатальную ошибку и ничего не загрузится.

Фразировка сообщения будет отличаться в зависимости от того, где происходит ошибка в коде, и причина отказа. Это также даст вам подсказки о том, что должно быть исправлено.

Как правило, это сообщение будет выглядеть примерно так:

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 21
 
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 21

Вот еще один пример:

Last Error: 2018-05-11 15:55:23: (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’

Сказав это, давайте посмотрим на то, как диагностировать и исправить  ошибку “Failed to Open Stream” в WordPress.

Исправление ошибки “Failed to Open Stream” в WordPress

Как мы уже упоминали ранее, ошибка может быть вызвана различными причинами, и сообщение об ошибке будет отличаться в зависимости от причины и местоположения файла, который вызывает ошибку.

В каждом экземпляре не удалось открыть потоковую фразу, за которой следует причина. Например, отказано в разрешении, нет такого файла или каталога, сбой операции и многое другое.

Теперь, если ваше сообщение об ошибке содержит ‘no such file or directory’, то вам нужно смотреть код, чтобы выяснить, какой файл упоминается в этой конкретной строке.

Если это файл плагина или темы, то это означает, что файлы плагина или темы были удалены или установлены неправильно. Просто деактивируйте и переустановите тему/плагин, о котором идет речь, чтобы исправить ошибку.

Тем не менее, также возможно, что WordPress не может найти файлы из-за отсутствия файла .htaccess в корневой папке. В этом случае вам нужно перейти на страницу Настройки » Постоянные ссылки в вашей админки в WordPress и просто нажать кнопку “Сохранить изменения”, чтобы восстановить файл .htaccess.

Что такое: Permalinks (постоянные ссылки)

Если сообщение об ошибке сопровождается ‘Permission denied’, то это означает, что WordPress не имеет правильного разрешения на доступ к файлу или каталогу, на который ссылается в коде.

Чтобы это исправить, вам нужно проверить разрешения на файлы икаталоги в WordPress и исправить их в случае необходимости.

Наконец, некоторые плагины в WordPress загружают скрипты из сторонних источников, таких как Google Analytics, Facebook API,, Google Maps и других API третьих сторон.

Некоторым из этих API, может потребоваться аутентификация или может быть изменен способ к которым разработчики могут получить доступ. Сбой аутентификации или неправильный метод доступа приведет WordPress не в состоянии открыть необходимые файлы.

Чтобы это исправить, вам нужно будет связаться с автором плагина для поддержки. Они должны в состоянии помочь вам исправить ошибку.

Если ни один из этих советов не поможет устранить проблему, то выполните действия, описанные в нашем руководстве поиска и устранения неисправностей в Worpdress . Этот шаг за шагом руководство поможет вам определить проблему, так что вы можете легко найти решение.

Мы надеемся, что эта статья помогла вам исправить ошибку “Failed to Open Stream” в WordPress. Вы также можете добавить список 25 наиболее распространенных ошибок в WordPress и как их исправить.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

You might get the following error while trying to run Laravel for the first time.

Warning: require(/var/www/laravel/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/laravel/bootstrap/autoload.php on line 17

Fatal error: require(): Failed opening required ‘/var/www/laravel/bootstrap/../vendor/autoload.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/laravel/bootstrap/autoload.php on line 17

Problem Scenario:

This error generally occurs when you download/clone Laravel from Github and then you put it in your web server. Then, you try to access it through your browser (e.g. http://localhost/laravel/public).

Cause:

Though you have downloaded the Laravel code and put it in your server, there’s still missing dependencies (library files/codes) in the code. The missing dependencies should be installed in order to make Laravel run properly.

Solution:

To solve this error, you need to install the missing dependencies via composer. Composer is a dependency manager tool for PHP. If you don’t have composer installed in your system then you need to install it first. You can get/download composer from here: https://getcomposer.org.

Once you have installed composer on your system/computer, then you need to follow the steps below to install the missing dependencies:

  • Open terminal or command prompt
  • Go to your Laravel directory
    • For example, in Ubuntu Linux the web root is /var/www/, in Windows if you install Wampp in C: Drive then the web root will be C://wampp/www
    • Suppose, you downloaded and copied the Laravel files in directory named ‘laravel’
    • Then, your Laravel directory on your web server in Ubuntu will be /var/www/laravel
    • You can go to that directory by running the following command on terminal: cd /var/www/laravel
  • Run the following command
composer install
  • This will install the required dependencies to run Laravel. It will take some time to install all the dependencies.
  • Now, you should be able to access Laravel properly without any error, e.g. http://localhost/laravel/public

If you already have run composer install command and still getting the error, then you can try running the following command:

composer update

Note: If you are on Linux then you should also set write permission to bootstrap/cache and storage directories.

Here’s the command to do so:

sudo chmod -R 777 bootstrap/cache storage

Alternatively, the better way to create laravel project / install Laravel will be directly through composer. Instead of downloading/cloning Laravel from GitHub, you can run the following composer command in terminal/command-prompt:

  • Go to your web server root (in Ubuntu, it’s /var/www/)
  • Run the following command in terminal:
composer create-project laravel/laravel name-of-your-project
  • This will create a directory with name-of-your-project and install Laravel files in it
  • This will also install all the required dependencies to run Laravel
  • Then, you can simply browse http://localhost/name-of-your-project/public to access Laravel

Hope this helps. Thanks.

Понравилась статья? Поделить с друзьями:
  • Failed to open registry key hklm software infotecs installiplirlwf64 error code 2
  • Failed to open registry error code 5 forza horizon 5 как исправить
  • Failed to open nvenc codec generic error in an external library
  • Failed to open dlllist txt for reading error code 2
  • Failed to open descriptor file gears 5 как исправить