Ошибка no such file or directory php

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

The ‘Failed to Open Stream: No Such File or Directory’ error is a common issue that developers face while working with file system functions in PHP, such as fopen(), file_get_contents(), require(), and include(). This error occurs when the specified file or directory is not found in the given path. In this guide, we will walk you through different solutions to troubleshoot this issue.

Table of Contents

  1. Check File or Directory Path
  2. Verify File Permissions
  3. Use Absolute Path Instead of Relative Path
  4. Check PHP Configuration
  5. FAQ

Check File or Directory Path

One of the most common reasons for the ‘Failed to Open Stream: No Such File or Directory’ error is an incorrect file or directory path. Double-check the path to ensure that you have not made any typographical errors or included any extra characters.

// Incorrect path
require_once('wrong/path/to/file.php');

// Correct path
require_once('correct/path/to/file.php');

Verify File Permissions

If the file or directory path is correct, check if the file or directory has the proper permissions. The file should have read permission for the user running the PHP script. You can use the chmod command to change the permissions of the file.

# Change file permissions to read, write, and execute for the owner
chmod 700 path/to/file.php

For more information about file permissions, visit the official documentation.

Use Absolute Path Instead of Relative Path

Using an absolute path instead of a relative path can help avoid the ‘Failed to Open Stream: No Such File or Directory’ error. You can use the __DIR__ magic constant to get the current directory and build the absolute path from there.

// Using a relative path
require_once('relative/path/to/file.php');

// Using an absolute path
require_once(__DIR__ . '/relative/path/to/file.php');

For more information about magic constants, refer to the official documentation.

Check PHP Configuration

The PHP configuration file (php.ini) may also cause this error if specific settings are incorrect or misconfigured. One such setting is the open_basedir directive, which limits the files that can be opened by PHP to the specified directory tree.

Ensure that the open_basedir directive includes the paths to the required files, or you can disable the directive by commenting it out or setting it to none.

; Disable the open_basedir directive
; open_basedir = "/path/to/allowed/directory"

; Or set it to none
open_basedir = none

For more information about the open_basedir directive, refer to the official documentation.

FAQ

1. How do I check the file permissions of a file or directory?

You can use the ls command with the -l flag to check the file permissions of a file or directory in Unix-based systems, like Linux and macOS.

ls -l path/to/file.php

For Windows, you can check the file permissions by right-clicking the file, selecting ‘Properties’, and navigating to the ‘Security’ tab.

2. How do I change file permissions on Windows?

To change file permissions on Windows, right-click the file, select ‘Properties’, and navigate to the ‘Security’ tab. Click the ‘Edit’ button to modify the permissions for different users and groups.

3. Can I use the file_exists() function to check if a file exists before using require_once() or include()?

Yes, you can use the file_exists() function to check if a file exists before using require_once() or include(). However, this is not recommended, as it may introduce additional overhead and complexity to your code. It’s better to ensure that the required files exist and have the correct permissions during the deployment process.

4. What is the difference between require() and include() in PHP?

The primary difference between require() and include() is the way they handle errors. If the specified file is not found, require() will produce a fatal error and halt the execution of the script. In contrast, include() will only generate a warning, and the script will continue to execute.

5. Can incorrect file permissions cause security issues?

Yes, incorrect file permissions can lead to security issues. For example, if a file has write permissions for everyone, an attacker may be able to modify the file and inject malicious code. It’s essential to set the correct permissions for your files and directories to maintain the security of your application.

Learn more about PHP file system functions

Ошибка «No such file or directory» появляется, когда нужный файл отсутствует.

Давайте исключим самое банальное:

1. Файла нет на диске

user@pc1:~$ cat hello.cpp
cat: hello.cpp: No such file or directory

Поскольку отсутствует файл hello.cpp , то выводится ошибка

2. Кириллица в названии

Проверьте, что в названии файла буква «с» не написана кириллицей. Например в расширении «.cpp».

3. Неправильный путь

Пример из Python

data_file= open ("../text.txt",'r')

«../» в общем случае говорит о том, что файл будет искаться на 1 директорию выше, чем файл с кодом.

Если файл лежит в директории с кодом, то следует писать:

data_file= open ("./text.txt",'r')

4. Неправильная битность

Вы можете увидеть ту же ошибку, если пытаетесь запустить например 64-битное приложение на 32-битной Windows

5. Более экзотические причины.

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

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

Нашли опечатку или ошибку? Выделите её и нажмите Ctrl+Enter

Помогла ли Вам эта статья?

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

Totoro

47 / 23 / 3

Регистрация: 28.05.2012

Сообщений: 150

Записей в блоге: 1

1

10.10.2012, 13:27. Показов 18305. Ответов 16

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте уважаемые обитатели форума при написании скрипта:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
    //Переменные для подключения
    require_once 'appvarsconnections.php';
    
    //Подключение к базе данных
        $dbc = mysqli_connect('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME') 
        or die('connection to bd fail');
    
    //Запрос на получение списка подписчиков
    $query = 'SELECT * FROM email_list';
    
    //Запрос в БД
    $result = mysqli_query($dbc, $query) or die('Query to bd fail');
    
    //Цикл построения табличного списка подписчиков
    echo '<table>';
    while ($row = mysqli_fetch_array($result)) {
        echo '<tr><td class="table_head">'. $row['first_name']. '<td>';
        echo '<tr><td class="table_head">'. $row['last_name']. '<td>';
        echo '<tr><td class="table_head">'. $row['email']. '<td>';
    }
    echo '</table>';
    
    mysqli_close($dbc);
?>

При проверке выходит ошибка:

Warning: require_once(appvarsconnections.php) [function.require-once]: failed to open stream: No such file or directory in Z:hometest.mywwwtoolsemaillist_subscribers.php on line 3

Fatal error: require_once() [function.require]: Failed opening required ‘appvarsconnections.php’ (include_path=’.;C:phppear’) in Z:hometest.mywwwtoolsemaillist_subscribers.php on line 3

Содержание файла connections.php:

PHP
1
2
3
4
5
6
<?php
        define('DB_HOST', 'localhost');
    define('DB_USER', 'root');
    define('DB_PASSWORD', '');
    define('DB_NAME', 'sm_shop');
?>

Я только учусь PHP поэтому не знаю причину возникновения ошибки пути до файла проверил(файлы тоже присутствуют).
кодировки файлов одинаковые.
Скрипт тестирую на Denwer.
Скрипты пишу на Aptana Studio 3, build: 3.2.1.201207261642

Если не сложно подскажите способы решения ошибки(На сколько я понял возникает ошибка открытия потока из за того что он не может найти файл)



0



alpex

603 / 578 / 103

Регистрация: 16.07.2012

Сообщений: 1,762

10.10.2012, 13:31

2

слеши не в ту сторону

PHP
1
require_once '/app/vars/connections.php';

Добавлено через 49 секунд
и в </td> кстати тоже

Добавлено через 1 минуту
и вобще вы в таблице тег <tr> не закрываете



0



47 / 23 / 3

Регистрация: 28.05.2012

Сообщений: 150

Записей в блоге: 1

10.10.2012, 13:45

 [ТС]

3

Только учусь
Слэши поменял но ошибку это не решило.

Warning: require_once(app/vars/connections.php) [function.require-once]: failed to open stream: No such file or directory in Z:hometest.mywwwtoolsemaillist_subscribers.php on line 3

Fatal error: require_once() [function.require]: Failed opening required ‘app/vars/connections.php’ (include_path=’.;C:phppear’) in Z:hometest.mywwwtoolsemaillist_subscribers.php on line 3

Таблицы ещё просто не дописал.



0



Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

10.10.2012, 13:51

4

функция не находит его по этому пути. Проверьте, существует ли он там, и нет ли ошибки в названии (возможно даже буква где то русская вместо английской )



1



47 / 23 / 3

Регистрация: 28.05.2012

Сообщений: 150

Записей в блоге: 1

10.10.2012, 14:13

 [ТС]

5

Пути переписал заново наличие проверил.
Ошибка не исчезает.
Не знаю важно или нет ось Win7 x64.

Добавлено через 10 минут
Вот сам проект:
test.my.zip

Если не сложно помогите разобраться с ошибкой.

Заранее премного благодарен.



0



KOPOJI

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

10.10.2012, 14:15

6

а так?

PHP
1
require_once $_SERVER['DOCUMENT_ROOT'].'/app/vars/connections.php';



0



115 / 115 / 39

Регистрация: 11.10.2011

Сообщений: 649

10.10.2012, 14:16

7



0



KOPOJI

10.10.2012, 14:18

Не по теме:

Heidel, здесь ошибка не в том, что константы уже где то декларировались или еще что то не так с функцией, а в неверном пути к файлу (или отсутствии прав на чтение)



0



psk-ru

3 / 3 / 2

Регистрация: 13.08.2012

Сообщений: 53

10.10.2012, 15:59

9

Запустите скрипт connections.php с таким кодом

PHP
1
2
3
4
5
6
7
<?php
        define('DB_HOST', 'localhost');
    define('DB_USER', 'root');
    define('DB_PASSWORD', '');
    define('DB_NAME', 'sm_shop');
    echo "<h3>"."Путь к файлу ".$_SERVER['PHP_SELF'].':'."</h3>"."<h1>".__FILE__."</h1>";
?>

проверьте путь к файлу



0



Totoro

47 / 23 / 3

Регистрация: 28.05.2012

Сообщений: 150

Записей в блоге: 1

10.10.2012, 21:26

 [ТС]

10

Цитата
Сообщение от psk-ru
Посмотреть сообщение

Запустите скрипт connections.php с таким кодом

PHP
1
2
3
4
5
6
7
<?php
        define('DB_HOST', 'localhost');
    define('DB_USER', 'root');
    define('DB_PASSWORD', '');
    define('DB_NAME', 'sm_shop');
    echo "<h3>"."Путь к файлу ".$_SERVER['PHP_SELF'].':'."</h3>"."<h1>".__FILE__."</h1>";
?>

проверьте путь к файлу

Проверил пути, символы на наличие латиницы.

результат:

Добавлено через 2 минуты

Цитата
Сообщение от KOPOJI
Посмотреть сообщение

а так?

PHP
1
require_once $_SERVER['DOCUMENT_ROOT'].'/app/vars/connections.php';

Результатов не принесло =(



0



3 / 3 / 1

Регистрация: 23.01.2012

Сообщений: 97

10.10.2012, 21:37

11

Цитата
Сообщение от Totoro
Посмотреть сообщение

Warning: require_once(appvarsconnections.php) [function.require-once]: failed to open stream: No such file or directory in Z:hometest.mywwwtoolsemaillist_subscribers.php on line 3

а что это за файл list_subscribers.php ?



0



3 / 3 / 2

Регистрация: 13.08.2012

Сообщений: 53

10.10.2012, 21:52

12

Проверьте на всякий случай нет ли ошибки в имени файла



0



KOPOJI

10.10.2012, 22:55

Не по теме:

Цитата
Сообщение от ibragimof
Посмотреть сообщение

а что это за файл list_subscribers.php

Это файл, из которого пытаются подключить connections.php



0



47 / 23 / 3

Регистрация: 28.05.2012

Сообщений: 150

Записей в блоге: 1

11.10.2012, 13:42

 [ТС]

14

Проектируя другое приложение заметил вот такую ошибку:

и появилось подозрение что такая же ситуация возникает и в этом случае с подключением файла т.е путь указан верно но так как корень находится не в корне а в:

C:WebServershometest.mywwwtoolsemail

то он ищет в:

C:WebServershometest.mywwwtoolsemailappvarsconnections.php

и соответственно там этого файла нет потому он его и не находит.

Поэтому хотелось бы узнать как устранить эту проблему.
Есть ли способ «занулить» путь?

Буду благодарен за любую помощь.

P.S проверка файла HEX редактором не выявила кириллицы или скрытых символов в указаном мной пути.

Миниатюры

Ошибка с require_once (No such file or directory)
 



0



47 / 23 / 3

Регистрация: 28.05.2012

Сообщений: 150

Записей в блоге: 1

11.10.2012, 14:00

 [ТС]

15

Подъем скрипта в корень т.е:

Z:hometest.mywww

устранил проблему и скрипт заработал.

Но хотелось бы узнать как выполнять вызовы из внутренних каталогов или это невозможно???

Заранее благодарен за помощь.



0



Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

11.10.2012, 14:14

16

./ — путь от текущей директории



1



Totoro

47 / 23 / 3

Регистрация: 28.05.2012

Сообщений: 150

Записей в блоге: 1

11.10.2012, 14:35

 [ТС]

17

Цитата
Сообщение от KOPOJI
Посмотреть сообщение

./ — путь от текущей директории

Если не сложно не могли бы вы привести пример или статью где об этом можно прочитать а то не совсем понял мысль.

Добавлено через 9 минут
Благодарю всех за помощь ответ нашел.
Надо было указывать так:

PHP
1
    require_once '../../app/vars/connect.conf.php';



0



Понравилась статья? Поделить с друзьями:
  • Ошибка no such file or directory linux
  • Ошибка no such file or directory exit status 1
  • Ошибка no such file or directory android
  • Ошибка no such file found
  • Ошибка no such device ostree