Php run code in string

how to run php code within string?

how to write this script?
any comments are welcome.
thanks.

how to write this script?
any comments are welcome.

But only use it if strictly necessary, consider other options first.

and if u’re really interested in learning php, u’ll like to go

thanks all your reply.
But the answer isn’t what I want.

I know function eval(), it will execute the string pass to the function
as php script.

$a is a string, it will retrive from db.
I want to insert some php script to the $a, like in Smarty
of PHP. The code with special tag will be processed as php script.
like

thanks all your reply.
But the answer isn’t what I want.

I know function eval(), it will execute the string pass to the function
as php script.

$a is a string, it will retrive from db.
I want to insert some php script to the $a, like in Smarty
of PHP. The code with special tag will be processed as php script.
like

Just make sure you make the boundaries clear of the PHP code in the string
you store in the database.
eg:
$myStr = «result,**PHP**if ($b==1) echo \»b=1\»**PHP** testing.»;
Now if you retrieve that string from DB, you can get the parts you want to
execute using explode(«**PHP**»,$myStr) and a little coding.

Of course, be sure that the seperatorstring (**PHP** in this example) cannot
be used elsewhere, or this will fail.

I must warn you, like others did, that you should try to avoid such design.

If the content of the executable PHP-code is coming from users, don’t trust
it. I can contain anything, and you do NOT want to eval that. Beware.

A sidenote:
I have been coding PHP for years nonstop, and I only needed eval once.
I got so paranoid that I needed 2 days of additional coding and testing to
be sure it was safe.
My point: You probably do not need eval().

thanks all your reply.
But the answer isn’t what I want.

I know function eval(), it will execute the string pass to the function
as php script.

$a is a string, it will retrive from db.
I want to insert some php script to the $a, like in Smarty
of PHP. The code with special tag will be processed as php script.
like

Just make sure you make the boundaries clear of the PHP code in the string
you store in the database.
eg:
$myStr = «result,**PHP**if ($b==1) echo \»b=1\»**PHP** testing.»;
Now if you retrieve that string from DB, you can get the parts you want to
execute using explode(«**PHP**»,$myStr) and a little coding.

Of course, be sure that the seperatorstring (**PHP** in this example) cannot
be used elsewhere, or this will fail.

I must warn you, like others did, that you should try to avoid such design.

If the content of the executable PHP-code is coming from users, don’t trust
it. I can contain anything, and you do NOT want to eval that. Beware.

A sidenote:
I have been coding PHP for years nonstop, and I only needed eval once.
I got so paranoid that I needed 2 days of additional coding and testing to
be sure it was safe.
My point: You probably do not need eval().

I just used eval for the first time yesterday.

Part of a search function where $word would only ever be [a-z0-9_] —
Even then, I wasn’t sure if I really wanted to use it. A few hours
later, it was replaced by something else (different algo). 😉

thanks all your reply.
But the answer isn’t what I want.

I know function eval(), it will execute the string pass to the function
as php script.

$a is a string, it will retrive from db.
I want to insert some php script to the $a, like in Smarty
of PHP. The code with special tag will be processed as php script.
like

Just make sure you make the boundaries clear of the PHP code in the
string you store in the database.
eg:
$myStr = «result,**PHP**if ($b==1) echo \»b=1\»**PHP** testing.»;
Now if you retrieve that string from DB, you can get the parts you want
to execute using explode(«**PHP**»,$myStr) and a little coding.

Of course, be sure that the seperatorstring (**PHP** in this example)
cannot be used elsewhere, or this will fail.

I must warn you, like others did, that you should try to avoid such
design.

If the content of the executable PHP-code is coming from users, don’t
trust it. I can contain anything, and you do NOT want to eval that.
Beware.

A sidenote:
I have been coding PHP for years nonstop, and I only needed eval once.
I got so paranoid that I needed 2 days of additional coding and testing
to be sure it was safe.
My point: You probably do not need eval().

I just used eval for the first time yesterday.

Part of a search function where $word would only ever be [a-z0-9_] —
Even then, I wasn’t sure if I really wanted to use it. A few hours
later, it was replaced by something else (different algo). 😉

I do not see how that piece of code makes sure that no naughty commands are
executed.
It completely depends on what $scoring contains.
If you let me deliver that $scoring-array, I think I can delete the content
of your harddrive.
But maybe I miss something completely. :-/

Источник

How To Execute PHP code in a PHP String (and return the output to another string)

Well you’re in luck my friend, PHP was thinking of you when they created the eval function.

The syntax for eval is very simple:

Unfortunately, the output of eval does not work like you might expect it to. You can’t, for instance, do this:

$string_awesome = eval(string $code_str)

The string will remain empty and eval will function as though it weren’t at the right hand side of an assignment. This is because of the way eval works. Eval is not intended to deal solely with code that outputs something to the screen. It simply executes the provided code inline with the rest of the code. It can share variables, functions, and anything else with the main body. So the following would work just fine:

$number = 1; eval ("$number = $number + 1"); echo $number;

The preceding would output 2. Notice that it was necessary to escape each dollar sign. Eval requires a pure PHP string. Any normal PHP operations have to be escaped out, including single quotes, double quotes, dollar signs, etc or it will not work properly.

Since eval is not primarily concerned with output, it doesn’t return any. In order to capture the output to a string you have to do something called output buffering. Output buffering simply captures any output of desired PHP statements and allows you to manipulate it before display (or even choose not to display at all). It has many applications beyond the scope of eval. Output buffering uses a variety of functions. We will demonstrate most of them in the following examples.

Back to our original example, let’s assume we have a string of PHP code which we are going to execute via an eval statement and we would like any output to be captured to a string. To do this, we’d simply run:

ob_start(); eval("echo "This is some really fine output.""); $this_string = ob_get_contents(); ob_end_clean();

Simple enough right? With ob_start , we…start output buffering. We use ob_get_contents to capture the collected output to a string, and we use ob_end_clean to exit the whole thing nicely. The value of $this_string will be “This is some really fine output.”

But what if we had two eval statements to run and wanted two different strings? Well, we could just run the above code twice, but PHP provides a function called ob_get_clean that simplifies the task. The resulting code looks like:

ob_start(); eval("echo "This is some really fine output.""); $this_first_string = ob_get_clean(); eval("echo "This is some more fine output.""); $this_second_string = ob_get_contents(); ob_end_clean();

Using ob_get_clean for the first part of the capture scrubs the output buffer and allows it to collect more output without restarting the whole process. This results in cleaner code (and I expect faster executions).

There is one more trick in the output buffering bag that may prove useful. If you want to capture the output of an eval to a string but also display it as if it were simply being executed inline, you can simply use one of the flush functions. Flushing sends the output buffer along its merry way, as if it were never captured. It also cleans the output buffer so it is important to run one of the ob_get* functions before we use flush. PHP even provides variations of the core functions using flush:

ob_start(); eval("echo "Some awesome output. ""); $this_string = ob_get_contents(); ob_end_flush();

The preceding code will output the output buffer and also store it in $this_string. You can also use ob_get_flush or ob_flush to further simplify this depending on your particular application.

Comments

Thank you for this clear explanation, kind stranger. It was a great relief to me this afternoon to find this page!

Your code samples are coming up as hex strings: the first one’s displaying as “deee70b3a62ff9ddd4faa45401478de8000”, for instance. Perhaps your code samples are being executed?

How bizarre – they’re now displaying as normal code. Maybe finding this site through Google had something to do with it…

Thank you very much!
With your code I file the result of a whole page into a var. Like this:
ob_start();eval(“if($show_news==1) < require_once(“news.php”);>”);$news= ob_get_clean();ob_start();

Thank you very much!
With your code I file the result of a whole page into a var. Like this:
ob_start();eval(“if($show_news==1) < require_once(“news.php”);>”);$news= ob_get_clean();ob_start();

Very good article. I changed something in order to make it work with “include” files like this: ob_start();
eval(‘?>’ . file_get_contents( $fileToRequire, TRUE ) . ‘ php ‘);
$string = ob_get_contents();
ob_end_clean(); Thanks a lot for your help 😉

Источник

eval

Исполняет строку, переданную в параметре code , как код PHP.

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

Список параметров

Исполняемая строка кода PHP.

Код не должен быть обрамлен открывающимся и закрывающимся тегами PHP, т.е. строка должна быть, например, такой ‘echo «Привет!»;’, но не такой ». Возможно переключатся между режимами PHP и HTML кода, например ‘echo «Код PHP!»; ?>Код HTML.

Передаваемый код должен быть верный исполняемым кодом PHP. Это значит, что операторы должны быть разделены точкой с запятой (;). При исполнении строки ‘echo «Привет!»‘ будет сгенерирована ошибка, а строка ‘echo «Привет!»;’ будет успешно выполнена.

Указание в коде ключевого слова return прекращает исполнение кода в строке.

Исполняемый код из строки будет выполняться в области видимости кода, вызвавшего eval() . Таким образом, любые переменные, определенные или измененные кодом, выполненным eval() , будут доступны после его выполнения в теле программы.

Возвращаемые значения

Функция eval() возвращает NULL пока не вызывается return, в случае чего возвращается значение, переданное return. Если в исполняемом коде присутствует ошибка, то eval() возвращает FALSE и продолжается нормальное выполнение последующего кода. Ошибку обработки кода парсером невозможно использовать в set_error_handler() .

Примеры

Пример #1 Пример функции eval() — простое слияние текста

$string = ‘cup’ ;
$name = ‘coffee’ ;
$str = ‘This is a $string with my $name in it.’ ;
echo $str . «\n» ;
eval( «\$str = \» $str \»;» );
echo $str . «\n» ;
?>

Результат выполнения данного примера:

This is a $string with my $name in it. This is a cup with my coffee in it.

Примечания

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

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

Замечание:

В случае фатальной ошибки в исполняемом коде прекращается исполнение всего скрипта.

Смотрите также

Источник

Читайте также:  Python element wise and
Оцените статью