Does php require html

Подключение файлов

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

Зачем разделять и подключать PHP-сценарии

PHP-разработчики дробят исходный код проекта на отдельные сценарии, чтобы было проще работать. Если написать код в одном файле, сценарий станет необъятным, и ориентироваться будет невозможно.

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

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

Способы подключения файлов — require и require_once

Для подключения файлов в PHP есть две языковые конструкции: require и require_once . Отличия между ними минимальны. Оба этих ключевых слова подключают файл с указанным именем и вызывают ошибку, если данный файл не существует.

👉 Особенность работы require_once — он позволяет подключать файл только один раз, даже если вызывать инструкцию несколько раз с одним именем файла.

Примеры подключения файлов

Рассмотрим, как подключить один сценарий внутри другого. Для этого воспользуемся инструкцией require . Предположим, у нас есть два сценария: index.php и sub.php .

В файле index.php находится код, который подключит сценарий sub.php :

Интересный факт: require можно использовать как ключевое слово, либо как функцию.

Результат будет одним и тем же:

Результат работы:

Привет, я содержимое из sub.php! А я - index.php! 

Что произошло? Два сценария как бы склеились в один: выполнилось все содержимое sub.php и добавилось в начало сценария index.php .

О работе с функцией require подробно рассказано в этом задании.

Абсолютные и относительные пути

При подключении файла в качестве его адреса указывают абсолютный или относительный путь.

Абсолютный путь — это полный адрес файла от корня диска. Например, /var/www/web/site/inc/sub.php

Относительный путь содержит адрес относительно текущей рабочей директории. Если сценарий лежит в папке /var/www/web/site , то для подключения файла используется такой путь: inc/sub.php

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

👉 В PHP есть полезные встроенные константы, их используют в пути к подключаемым файлам.

__DIR__ — полный путь к директории с текущим сценарием.

__FILE__ — полный путь к текущему сценарию.

Видимость переменных в подключаемых сценариях

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

В PHP нет системы модулей, как в других языках программирования (Python, Java, ECMAScript 12). Невозможно «импортировать» отдельные переменные или функции из подключаемого сценария.

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

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

Does php require html

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning ( E_WARNING ) which allows the script to continue.

See the include documentation for how this works.

Читайте также:  Commenting functions in python

User Contributed Notes 23 notes

Remember, when using require that it is a statement, not a function. It’s not necessary to write:
require( ‘somefile.php’ );
?>

The following:
require ‘somefile.php’ ;
?>

Is preferred, it will prevent your peers from giving you a hard time and a trivial conversation about what require really is.

If your included file returns a value, you can get it as a result from require(), i.e.

foo.php:
return «foo» ;
?>

$bar = require(«foo.php»);
echo $bar; // equals to «foo»

A note that drove me nuts for 2 days!

Be carfull if you have a newline or blank space befor your php tags in the included/required file it will read as html and outputed.

If your running your output through javascript string evaluations which would be sensitive to newlines/white spaces be carfull that the first chars in the file are the php tages eg

When using symbolic links with PHP, specify a dotslash ‘./page.php’ path to ensure that PHP is looking in the right directory with nested requires:

E.g. when the required actual page1.php contains other require statements to, say page2.php, PHP will search the path that the symbolic link points to, instead of the path where the symbolic link lives. To let PHP find the other page2.php in the path of the symbolic link, a require(‘./page2.php’); statement will solve the puzzle.

I didn’t find mention that calling return from inside an required file is different than calling return from inside an included file.

return «aaa»; if called in the global scope of an included file will terminate the inclusion and return control to the main file givin «aaa» as a result of the include statement itself.

As far as I have tested (PHP 5.6.10) this does not apply to require

if you want always include, require, open files using some ‘root’ folder based path you may may put file ‘.htroot’ in ‘root’ folder and use this.

This code change current dir to dir where ‘.htroot’ file located and everywhere you can use relative to ‘root’ paths.

Please avoid absent of ‘.htroot’ file.

I have learnt to manipulate this code into an effecitve and easy to use form. I use it with require_once, but it could be used for require.

This mainly jumps back to the servers document root and then begins to enter the directories defined until it finds the file. In this case it would go back to the root of the server, or whatever your document root is, and then enter includes. there it would search for the top.php file. Simple to use, yet effective. espcially for people like me who re-use code or move files to different directories. I don’t have to fix the includes, because they all work the same way.

PHP’s require and include seem to differ from C’s include in another way: they can’t be used in the middle of an expression. e.g.

$ more foo1.php foo2.php
.
foo1.php
.
print «hello»
.
#»there»
require ‘foo2.php’ ;
. «\n» ;
?>
.
foo2.php
.
«there»
$ php foo1.php
PHP Parse error: syntax error, unexpected ‘.’ in foo1.php on line 6

So php’s include operates only on complete statements, whereas c’s include operates on bytes of source code.

Читайте также:  Python cycle for list

re the comment by moazzamk at gmail dot com

As the manual states require and require_once as of PHP 4.02 no longer call the file if the line of code it is on should not be executed.

If you use relativ paths in a php script (file A) that can be required by another php script (file B), be aware that the relativ paths in file A will be relativ to the directory, where file B is stored.
You can use the following syntax in file A, to be sure that the paths are relativ to the directory of file A:

Be careful when using symbolic links, because require will search the real path of the file and not the path relative to the symbolic link.

Imagine your script A.php resides on directory /a and you create a symbolic link for it on directory /b/c.
So for the code

echo realpath ( «../» );
?>

you might expect the directory /b, but actually you get the root directory /.

If you need to include the file /b/B.php inside your A.php, you can’t use the following

require «../B.php» ;
?>

because it will search the root directory, not the /b directory.

// Looks like I might have a fix for some on the
// relative path issue.

if (!function_exists(‘bugFixRequirePath’))
function bugFixRequirePath($newPath)
$stringPath = dirname(__FILE__);
if (strstr($stringPath,»:»)) $stringExplode = «\\»;
else $stringExplode = «/»;

$stringNewPath = implode($stringExplode,$paths).
$stringExplode.implode($stringExplode,$newPaths);

Discovered a bit of weird behavior yesterday involving require() (using PHP 5.2.3). If you use require() inside a function, the «globals» in the file will be local to the function. An example of this:

test.php:
function TestFunc ()
require( ‘test2.php’ );
echo «

" . print_r ( $GLOBALS , true ) . "

» ;
>
?>

test2.php:
$MyTestGlobal = Array();
?>

This happens because require is a statement that _inlines_ the target code — not a function that gets called.

To fix this, use the $GLOBALS superglobal:

test2.php:
$GLOBALS [ «MyTestGlobal» ] = Array();
?>

Just for those who may wonder about receiving E_WARNING (in custom error handlers) — PHP generates an E_WARNING when require or require_once fails — and before control returns to your script, it generates an E_COMPILE_ERROR.

So when require() or require_once() fails — don’t be surprised to see two messages in your logs (if you have your logging setup this way) — once for the E_WARNING caught by your custom error handler, and once for getting the error from error_get_last() in your shutdown function (which is the actual E_COMPILE_ERROR you were expecting)

if you want to include files with an absolut path reference, you can use:

this way you can organize your files in subdirectories trees.

Thanks a lot for this information Brian! This drove me nuts for many hours! This is the first information I found in the web that a white page can be caused by a require -> your script will die if the file is not found.

$_SERVER[‘DOCUMENT_ROOT’] is very useful, but it is not available with all web servers. Apache has it; IIS doesn’t.

I use the following to make my PHP applications work in more situations:
if (! defined ( «BASE_PATH» )) define ( ‘BASE_PATH’ , isset( $_SERVER [ ‘DOCUMENT_ROOT’ ]) ? $_SERVER [ ‘DOCUMENT_ROOT’ ] : substr ( $_SERVER [ ‘PATH_TRANSLATED’ ], 0 , — 1 * strlen ( $_SERVER [ ‘SCRIPT_NAME’ ])));
?>

Читайте также:  Html checkbox yii2 checked

. but even that gets tripped up by symlinks to different mount points, etc. You could substitute realpath($_SERVER[‘PATH_TRANSLATED’]), but that function has been reported not to work on some (Windows) servers. One could use the PATH_TRANSLATED for both servers, but I figure if Apache is going to tell me exactly what I want to know, I should listen.

I have found a problem when I try to access a php file via require($class_directory)

// # $class_directory contain a long full path and dot into the last folder.
// # $class_directory = «/var/. /app/system/plugintoto_1.0/class_plugintoto_1.0.php»;

// dot (‘.’) and minus (‘-‘) are not accepted in require !

If you are experiencing a bug related to using relative paths with include or require, it may be related to a grandparent directory that is executable but not readable. It will cause __FILE__ to return a relative path instead of the full path which it is supposed to show. This manifests itself in interesting ways that can be seemingly unrelated. For instance, I discovered it using the Smarty command which failed to find its template due to this issue. Please see the following for more details:

In response to some dot user at notarealdomain dot com:

This is because require executes the code «as if» it was code written inside of the function, inheriting everything including the scope. But here there is something even more interesting:

$this -> a .= » is visible also under a require\n» ;
$b = «While the variable b is a local variable of the function\n» ;
function FunctionUnderRequire () echo «But the functions declared inside of a require called from a class function, just as when defined from inside any other function, are always global\n» ;
>
?>

:

error_reporting ( E_ALL | E_STRICT );

public function UserFunction () $this -> a = ‘The class variable a’ ;
require ‘requiredfile.php’ ;
echo $this -> a ; // «The class variable a is visible also under a require\n»
echo $this -> b ; // Notice: Undefined property: UserClass::$b
echo $b ; // «While the variable b is a local variable of the function\n»
$this -> FunctionUnderRequire (); //Fatal error!
FunctionUnderRequire (); // «But the functions. »
>
>

$UserClass =new UserClass ;
$UserClass -> UserFunction ();
?>

I’m wondering if there is a method for declaring class public/private/protected functions from inside a require/include.

Note when calling any require or include function, that the call will block if the script given as the parameter is excecuting.
Because of this one should be careful when using blocking functions like sleep() in a script which is included by another.

When using an include file to define one or more global variables (to avoid having to redefine them in multiple files), make sure you’re referencing the same variable.

[global.php]
$app_dir = «/app/path/here»;

/* the following obviously won’t work but hopefully I can save somebody else hours trying to figure out why their global include isn’t working */

If you want to verify that a file can be included or required, the simplest solution I’ve found is just to check that the file exists.

if( file_exists ( $pageContentInc )) require_once $pageContentInc ;
>else $pageContentInc = «common/content_404.inc» ;
require_once $pageContentInc ;
>
?>

Does it really need to be any harder than that?

Источник

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