php include php variable
PHP pass variable to include
I’m trying to pass a variable into an include file. My host changed PHP version and now whatever solution I try doesn’t work.
I think I’ve tried every option I could find. I’m sure it’s the simplest thing!
OPTION ONE
In the second file:
OPTION TWO
OPTION THREE
None of these work for me. PHP version is 5.2.16.
13 Answers 13
You can use the extract() function
Drupal use it, in its theme() function.
./index.php :
./header.php :
option 1 is the most practical. include() will basically slurp in the specified file and execute it right there, as if the code in the file was literally part of the parent page. It does look like a global variable, which most people here frown on, but by PHP’s parsing semantics, these two are identical:
Considering that an include statment in php at the most basic level takes the code from a file and pastes it into where you called it and the fact that the manual on include states the following:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
These things make me think that there is a diffrent problem alltogether. Also Option number 3 will never work because you’re not redirecting to second.php you’re just including it and option number 2 is just a weird work around. The most basic example of the include statment in php is:
Considering that option number one is the closest to this example (even though more complicated then it should be) and it’s not working, its making me think that you made a mistake in the include statement (the wrong path relative to the root or a similar issue).
require/include into variable
I want to require/include a file and retrieve its contents into a variable.
test.php
index.php
Like file_get_contents() but than it should still execute the PHP code. Is this possible?
9 Answers 9
If your included file returned a variable.
include.php
. then you can assign it to a variable like so.
Otherwise, use output buffering.
I’ve also had this issue once, try something like
You can write in the included file:
And in the file from which you are including:
In PHP/7 you can use a self-invoking anonymous function to accomplish simple encapsulation and prevent global scope from polluting with random global variables:
An alternative syntax for PHP/5.3+ would be:
You can then choose the variable name as usual:
I think eval(file_get_contents(‘include.php’)) help you. Remember that other way to execute like shell_exec could be disabled on your hosting.
require/include does not return the contents of the file. You’ll have to make separate calls to achieve what you’re trying to do.
EDIT
It is possible only if required or included php file returns something (array, object, string, int, variable, etc.)
But if it isn’t php file and you would like to eval contents of this file, you can:
Or maybe something like this
in file include.php:
in some other php file (doen’t matter what is a content of this file):
return will be look like this for example:
The point is, that the content of included file has the same scope as a content of function in example i have provided about.
How to include a PHP variable inside a MySQL statement
5 Answers 5
The rules of adding a PHP variable inside of any MySQL statement are plain and simple:
So as your example only involves data literals, then all variables must be added through placeholders (also called parameters). To do so:
And here is how to do it with all popular PHP database drivers:
Adding data literals using mysql ext
Adding data literals using mysqli
The code is a bit complicated but the detailed explanation of all these operators can be found in my article, How to run an INSERT query using Mysqli, as well as a solution that eases the process dramatically.
For a SELECT query you will need to add just a call to get_result() method to get a familiar mysqli_result from which you can fetch the data the usual way:
Adding data literals using PDO
In PDO, we can have the bind and execute parts combined, which is very convenient. PDO also supports named placeholders which some find extremely convenient.
Adding keywords or identifiers
Sometimes we have to add a variable that represents another part of a query, such as a keyword or an identifier (a database, table or a field name). It’s a rare case but it’s better to be prepared.
In this case, your variable must be checked against a list of values explicitly written in your script. This is explained in my other article, Adding a field name in the ORDER BY clause based on the user’s choice:
Unfortunately, PDO has no placeholder for identifiers (table and field names), therefore a developer must filter them out manually. Such a filter is often called a «white list» (where we only list allowed values) as opposed to a «black-list» where we list disallowed values.
So we have to explicitly list all possible variants in the PHP code and then choose from them.
Here is an example:
Exactly the same approach should be used for the direction,
The last thing to mention about identifiers, they must be also formatted according to the particular database syntax. For MySQL it should be backtick characters around the identifier. So the final query string for our order by example would be
include
Выражение include включает и выполняет указанный файл.
Если путь указан — не важно, абсолютный (начинающийся с буквы диска или с \ в Windows или с / в Unix/Linux системах) или относительно текущей директории (начинающийся с . или ..) — директива include_path будет проигнорирована в любом случае. К примеру, если начинается с ../, парсер проверит родительскую директорию на наличие запрошенного файла.
Для большей информации о том, как PHP обрабатывает включаемые файлы и включаемые пути, смотрите документацию для директивы include_path.
Когда файл включается, его код наследует ту же область видимости переменных, что и строка, на которой произошло включение. Все переменные, доступные на этой строке во включающем файле будут также доступны во включаемом файле. Однако все функции и классы, объявленные во включаемом файле, будут доступны в глобальной области видимости.
Пример #1 Простой пример include
vars.php
= ‘green’ ;
$fruit = ‘apple’ ;
Если включение происходит внутри функции включающего файла, тогда весь код, содержащийся во включаемом файле, будет вести себя так, как будто он был определен внутри этой функции. То есть, он будет в той же области видимости переменных этой функции. Исключением к этому правилу являются магические константы, которые выполняются парсером перед тем, как происходит включение.
Пример #2 Включение внутри функции
Когда файл включается, парсинг в режиме PHP кода прекращается и переключается в режим HTML в начале указанного файла и продолжается снова в конце. По этой причине любой код внутри включаемого файла, который должен быть выполнен как PHP код, должен быть заключен в верные теги начала и конца PHP кода.
Версии PHP для Windows до PHP 4.3.0 не поддерживают возможность использования удаленных файлов этой функцией даже в том случае, если включена опция allow_url_fopen.
Пример #3 Пример include через HTTP
// Не сработает; file.txt не обрабатывается www.example.com как PHP
include ‘http://www.example.com/file.txt?foo=1&bar=2’ ;
// Сработает.
include ‘http://www.example.com/file.php?foo=1&bar=2’ ;
$foo = 1 ;
$bar = 2 ;
include ‘file.txt’ ; // Сработает.
include ‘file.php’ ; // Сработает.
Предупреждение безопасности
Удаленные файлы могут быть обработаны на удаленной стороне (в зависимости от расширения файла и того, что удаленный сервер выполняет скрипты PHP или нет), но это все равно должно производить валидный PHP скрипт, потому что он будет затем обработан уже на локальном сервере. Если файл с удаленного сервера должен быть обработан там и выведен его результат, предпочтительнее воспользоваться функцией readfile() В противном случае, должны быть предусмотрены дополнительные меры, чтобы обезопасить удаленный скрипт от ошибок и нежелательного кода.
Смотрите также раздел Удаленные файлы, функции fopen() и file() для дополнительной информации.
Обработка возвращаемых значений: оператор include возвращает значение FALSE при ошибке и выдает предупреждение. Успешные включения, пока это не переопределено во включаемом файле, возвращают значение 1. Возможно выполнить выражение return внутри включаемого файла, чтобы завершить процесс выполнения в этом файле и вернуться к выполнению включающего файла. Также, возможно вернуть значение из включаемых файлов. Вы можете получить значение включения как если бы вы вызвали обычную функцию. Хотя это не возможно при включении удаленного файла, только если вывод удаленного файла не содержит правильные теги начала и конца PHP кода (так же, как и локальный файл). Вы можете определить необходимые переменные внутри этих тегов и они будут представлены в том месте, где файл был включен.
Пример #4 Сравнение возвращаемого значения при include
// не сработает, интерпретируется как include((‘vars.php’) == ‘OK’), т.е. include(»)
if (include( ‘vars.php’ ) == ‘OK’ ) <
echo ‘OK’ ;
>
// сработает
if ((include ‘vars.php’ ) == ‘OK’ ) <
echo ‘OK’ ;
>
?>
Пример #5 Выражения include и return