Php ошибка eval d code

When i login to my drupal page. It’s showing the following error

Parse error: syntax error, unexpected '<' in /document_root/sites/all/modules/rules/rules/modules/php.rules.inc(107) :

eval()’d code on line 1

When i just figure out to the particular page there is no problem in that function . Below is the function where the error marked..

function rules_php_eval_return($code, $arguments = array()) {
  extract($arguments);
  return eval($code);
}

Could any one can suggest me what’s the problem may be!! It’s drupal 6.x version.

asked Jun 7, 2011 at 13:20

Miko's user avatar

7

I came accross an error like this when I pasted a PHP code snippet from the Drupal site into a block to show submenus. These submenus were detected and assigned in a foreach loop, but since there weren’t any submenus, the menu variable remained unassigned and thus undeclared as well.

My obvious solution was to assign an empty string to the menu variable before the foreach loop.

answered Oct 11, 2012 at 18:20

Wilbert's user avatar

I don’t know drupal, but i think that $code contains something like :

$code = '<?php $someCode;';
eval($code);
//Produces : Parse error: syntax error, unexpected '<' in file(1) : eval()'d code on line 1

The error is telling you that $code contains a parse error (maybe the phptag)

You an echo $code to check what’s wrong.

answered Jun 7, 2011 at 13:57

Gérald Croës's user avatar

Gérald CroësGérald Croës

3,7892 gold badges18 silver badges20 bronze badges

eval’d usually comes when bad custom php codes embeded in site using php module(php filter)
If you can access site in anyway, go to Triggered Rules and Rule Sets page and find if any rule is firing a custom php code.
It’s idiot’s style to put php codes in Rules. Either you should create a module or use Rules itself :)

If you can’t access the site, go to /modules folder and move the «php» folder somewhere else. Then you will be able to access site. Quickly remove buggy code and replace the folder.
Then, start debugging it.

answered Jun 10, 2011 at 21:11

AKS's user avatar

AKSAKS

4,5982 gold badges29 silver badges48 bronze badges

I just had this same problem trying to process data returned from an HTTP request. I was using simplexml_load_string, but the HTTP response was an error, so the data was not formatted as XML, thus causing simplexml to error (propogate up). My message was the same as yours, «error in file on line X; eval’d() code on line X». So, it may not necessarily be an error within your code, or even the eval’d code.

While it looks like you don’t have the following issue, it is something to keep in mind as well. When declaring variables within the eval’d code they will scope the same as if inline in the file. Similarly, variables preceding the eval’d code are available within it, and may cause collisions, or inadvertent re-assigning (eg. $i in nested loops).

answered Nov 19, 2012 at 14:32

Wayne Weibel's user avatar

Wayne WeibelWayne Weibel

9331 gold badge14 silver badges22 bronze badges

  • #1

php синтаксис

[Wed Oct 3 01:44:12 2007] [error] PHP Parse error: syntax error, unexpected ‘<‘ in /home/рататта/include/PHPBB/php_out.php(66) : eval()’d code on line 1

вот сам файл

PHP:

if (!defined("IN_MKP")) {
    	die ("Sorry !! You cannot access this file directly.");
}

function mkportal_board_out() {
		global $db, $userdata, $Checkmkout, $mkportals, $DB, $Skin, $MK_PATH, $MK_TEMPLATE, $mklib, $ForumOut, $mklib_board, $board_config;
		$MK_PATH = "../";
		require $MK_PATH."mkportal/conf_mk.php";
		$mkportals->base_url = $MK_PATH.$FORUM_PATH."/index.php";
		$mkportals->forum_url = $MK_PATH.$FORUM_PATH;

		require_once $MK_PATH."mkportal/include/mk_mySQL.php";
		$DB = new db_driver;
		$DB->db_connect_id = $db->db_connect_id;
		// assign member information
		$mkportals->member['id'] = $userdata['user_id'];
		$mkportals->member['name'] = $userdata['username'];

		if($userdata['user_id'] == -1) {
			$mkportals->member['id'] = "";
		}
		$mkportals->member['last_visit'] = $userdata['user_lastvisit'];
		$mkportals->member['session_id'] = $userdata['session_id'];

		$mkportals->member['user_new_privmsg'] = $userdata['user_unread_privmsg']."/".$userdata['user_new_privmsg'];
		if ($userdata['user_last_privmsg'] > $userdata['user_lastvisit'] && $userdata['user_new_privmsg'] > 0) {
			$mkportals->member['show_popup'] = 1;
		}
		$mkportals->member['email'] = $userdata['user_email'];
		$mkportals->member['timezone'] = $userdata['user_timezone'];
		//$mkportals->member['dateformat'] = $userdata['user_dateformat'];

		//assign member group -> attention don't change this !!
		$mkportals->member['mgroup'] = 3;
		
		// assign to forum admin access to MKportal CPA
		if($userdata['user_level'] == 1) {
			$mkportals->member['g_access_cp'] = 1;
			$mkportals->member['mgroup'] = 1;
		}
		if($userdata['user_id'] == -1) {
			$mkportals->member['mgroup'] = 9;
		}
		if($userdata['user_level'] == 2) {
			$mkportals->member['mgroup'] = 2;
		}
		$mkportals->member['theme'] = $userdata['user_style'];
		if (empty($userdata['user_style'])) {
			$mkportals->member['theme'] = $board_config['default_style'];
		}
		$mkportals->member['mk_lang'] = $userdata['user_lang'];
		if (empty($mkportals->member['mk_lang'])) {
			$mkportals->member['mk_lang'] = $board_config['default_lang'];
		}
		require_once $MK_PATH."mkportal/include/functions.php";
		require_once $MK_PATH."mkportal/include/PHPBB/php_board_functions.php";
		require_once "$mklib->template/tpl_main.php";
		if($MK_OFFLINE && !$mkportals->member['g_access_cp'] && !$mklib->member['g_access_cpa']) {
				$message = $mklib->lang['offline'];
				$mklib->off_line_page($message);
				exit;
		}

		ob_start();
    		eval($ForumOut);  !!!!!!<== ВОТ ето 66 строка!!!!!!
    		$contentspage = ob_get_contents();
     		ob_end_clean();

		$ForumOut = $mklib->printpage_forum("$mklib->forumcs", "$mklib->forumcd", "Forum", $ForumOut);
		print $ForumOut; 

}

Я подписал 66ю строку

Пишет мол синтаксическая ошибка, нимогу понять в чем суть :(

  • #2

PHP Parse error: syntax error, unexpected ‘<‘ in /home/рататта/include/PHPBB/php_out.php(66) : eval()’d code on line 1

ошибка в коде, который выполняется eval().

Mr_Max

Mr_Max

Первый класс. Зимние каникулы ^_^


  • #3

PHP Parse error: syntax error, unexpected ‘<‘ in /home/рататта/include/PHPBB/php_out.php(66) : eval()’d code on line 1

[m]eval[/m]

  • #4

eval($ForumOut); !!!!!!<== ВОТ ето 66 строка!!!!!!

а что находится в переменной $ForumOut ?

  • #5

PHP:

$ForumOut .= ob_get_contents();
      ob_end_clean();
} else  {
    eval($this->compiled_code[$handle]);

}

Mr_Max

Mr_Max

Первый класс. Зимние каникулы ^_^


  • #6

echo $ForumOut;
Думаю без коментариев станет ясно.

  • #7

а теперь для тех кто в танке :)

  • #8

что тут непонятного?

ошибка синтаксиса — не в приведенном тобой коде, а в том коде, который eval’ится приведенным тобой кодом. Поэтому мы предлагаем тебе посмотреть на этот eval’юируемый код. Сделать это можно, распечатав значение переменной $ForumOut, в которой этот код лежит как строка.

Mr_Max

Mr_Max

Первый класс. Зимние каникулы ^_^


  • #9

Mongolor

eval() evaluates the string given in code_str as PHP code.

То-есть грубо-говоря вставив в «чистый» скрипт значение переменной [m]$ForumOut[/m]

И выполнив этот скрипт Вы получите ответ всё ли в порядке с $ForumOut ну или где допущены ошибки.

$a = ‘echo «test passed»;’;
eval($a);
результат работы —
test passed

$a = ‘echo «test passed»‘;
eval($a);
результат работы —
Parse error: parse error, unexpected $, expecting ‘,’ or ‘;’ eval()’d code on line 1

Ищем глюк
echo $a —-> echo «test passed»

После вставки в «чистый» скрипт
<?php
echo «test passed»
die();
?>
Parse error: parse error, unexpected T_EXIT, expecting ‘,’ or ‘;’

Всё понятно?

По крайней мере мне лишь таким образом удалось отловить eval()’d глюки в одном из проектов.

  • #10

бррр.. Это не отладка, это ад просто… Не, правду мама говорила, что eval — это зло!

Mr_Max

Mr_Max

Первый класс. Зимние каникулы ^_^


  • #13

boombick
Полностью согласен.
К сожалению, иногда такое в руки попадается. :(

  • #14

ярым примером может служить использование ENUM в Mysql. Других вариантов выцеживания пунктов этого типа я не нашел. Тjлько eval. Правда в других с этой ф-ией не сталкивался :)

  • #15

> ярым примером может служить использование ENUM в Mysql. Других вариантов выцеживания пунктов этого типа я не нашел. Тjлько eval.
Чего?

  • #16

Nogrogomed

причем тут это?

  • #17

hammet, в данной теме непричем. рызмышления на тему использования eval и не более того.

SiMM, приходилсь сталкиваться с проектами, использующими тип ENUM(‘Заказ принят к рассмотрению’, ‘Заказ выполнен’), и добавлять к ним третий элемент например ‘Заказ в обработке’. Так вот формировать <select> проще всего было с использованием eval, хотя по хорошему надо было бы создать еще одну таблицу.

  • #18

Nogrogomed а пример формирования селекта из енама, с помощью евал можно?

-~{}~ 04.10.07 16:51:

вообще, ещё есть alter table

  • #19

ALTER TABLE — это и так ясно. Но потом надо по любому переписывать код с выбором «текущего состояния» допустим с двух пунктов до трех.

На доделках чужих проектов чаще всего легче вставить «заплатку», чем переделывать структуру. Вот в качестве таких заплаток и используется примерно такой код:

PHP:

$sql = "DESCRIBE `zakaz` `status`";
$r = mysql_query($sql) or die(mysql_error());
$mas = mysql_fetch_assoc($r);
$Type = str_replace('enum', 'array', $mas['Type']);
$strEval = '$'.$mas['Field'].'='.$Type.';';
eval($strEval);

Хотя подобный подход нарушает нормализацию отношений по теории БД, но в условиях «надо побыстрее сделать» — помогает :)

П.С. В конце кода для проверки вставляем var_dump($$mas[‘Field’]);

  • #20

Не, правду мама говорила, что eval — это зло!

+1

во всех рекомендациях говорится — что это признак плохого тона.

First, the issues I have with your code:

  1. eval is very, very rarely needed, and extremely dangerous, use with caution. I’ve been developing in PHP for over 10 years, and never really encountered a situation that needed eval. This is no exception. Eval is not required
  2. You’re sanitizing the entire $_POST array. That’s great, but there are special functions for doing that, like: filter_input_array, array_filter and many, many more… not to mention ready-made, open source projects and frameworks that already contain a solid request validation component.
  3. Always check the return values of functions, which you seem to be doing with strstr, but be weary of functions that return different types (like strstr: it returns false if the needle isn’t found, but returns 0 if the needle is found at the start of the haystack string). Your if statement might not work as intended.
  4. You’re assuming sanitize($value) values will not contain any single quotes. Why? Because if they do, you’ll end up with a syntax error in your evaled string

Be that as it may, you could easily write your code using variable variables and add a simple check not to step on existing variables in scope:

$sanitized = array_filter($_POST, 'sanitize');//call sanitize on all values
foreach ($sanitized as $key => $value)
{
    if (!isset($$key) && strstr($key, 'removeFile') === false)
        $$key = $value;
}

But really, $_POST values belong together, they are part of the request, and should remain grouped… either in an array, or in an object of some sort. Don’t assign each value to its own variable, because pretty soon you’ll loose track of what variables are set and which are not. Using an unset variable creates that variable, assigning value null, so what you have now makes for very error-prone code:

//request 1: POST => id=123&foo=bar
foreach ($sanitized as $k => $v)
    $$k = $v;
$query = 'SELECT x, y, z FROM tbl WHERE id = ?';//using posted ID as value
$stmt = $db->prepare($query);
$stmt->execute(array($id));

All is well, because $id was set, but never trust the network, don’t assume that, just because $_POST is set, all the keys will be set, and their values will be correct:

//request 2: POST => foo=bar&page=2
foreach ($sanitized as $k => $v)
    $$k = $v;
$query = 'SELECT x, y, z FROM tbl WHERE id = ?';//using posted ID as value
$stmt = $db->prepare($query);
$stmt->execute(array($id));//id is null

Now we have a problem. This is just one example of how your code might cause issues. Imagine the script grows a bit, and look at this:

//request 3: POST => id=123&foo=bar&page=2
foreach ($sanitized as $k => $v)
    $$k = $v;
//$id is 123, $foo is bar and $page = 2
$query = 'SELECT x, y, z FROM tbl WHERE id = ? LIMIT 10';//using posted ID as value
//a lot more code containing this statement:
$page = someFunc();
$log->write('someFunc returned log: '.$page);
//more code
$offset = 10*($page-1);//<-- page is not what we expected it to be
$query .= sprintf(' OFFSET %d', $offset);
$stmt = $db->prepare($query);
$stmt->execute(array($id));

Now this may seem far-fetched, and idiotic, but believe me: all of these things happen, more than I care to know. Adding some code that accidentally overwrites an existing variable that is used further down happens all the time. Especially in procedural code. Don’t just blindly unpack an array. Keep that single variable, and use the keys to avoid:

  • grey hair
  • sudden, dramatic baldness
  • loss of sanity
  • bleeding ulcers
  • In a work environment: catastrophic loss of data
  • Sudden loss of job
  • … because code like this makes unicorns cry, and bronies will hunt you down

Есть такая вот проблемка:

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

PHP Fatal Error: syntax error, unexpected ')' in Form/Validate/DinamicFormulaValues.php(149) : eval()'d code on line 1

Как вывести в консоль текст выражения, которое не удалось проевалить?

У меня в голове такой вариант:

$expression = "1 + 2)"; // тут явно похожая синтаксическая ошибка - незакрытая скобка
$file = tempnam('/tmp', 'eval')
file_put_contents($file, "<?php return {$expression};");
$value = include($file);

После этого возникает ошибка

Parse error:  syntax error, unexpected ')' in /tmp/eval1kGtG7 on line 1

(при должной сноровке и чуточке разума это сообщение уходит почтой админу или разработчикам)

Открываю файл /tmp/eval1kGtG7 и вижу синтаксическую ошибку

Ещё вариант:

$result = exec('php -l "'.$file.'"', $output); // это консольная команда проверки синтаксиса файла PHP
echo $result; // -> Errors parsing /tmp/eval1kGtG7
echo implode("n", $output);  // -> PHP Parse error:  syntax error, unexpected ')' in /tmp/eval1kGtG7 on line 1

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

Ещё вариант

if (false === @eval($expression)) {
    var_dump(error_get_last()); // выводится текст сообщения об ошибке
}

Недостаток этого варианта: в error_get_last() остаётся результат от интерпретации предыдущего неудачного выражения, а проверок будет сотни — получается, что будет много ложных срабатываний на рекорректность.

Есть ли другие варианты?

Messages of the following form:

Fatal error: Call to undefined function in administratorcomponentscom_rsformhelpersrsform.php : eval()’d code on line 1

are being generated by the fact that PHP has detected an error in the syntax of your custom PHP code that you have added in either one of RSForm!Pro’s PHP Scripts areas (Script called on form display, Script called on form process, Script called after form has been processed), PHP Email Scripts areas (Script called before the User Email is sent, Script called before the Admin Email is sent and Script called before the Additional Emails are sent), as well as the Manage Directories‘s PHP Scripts areas (Scripts called on listing layout, Scripts called on details layout and Script called before the Directory Emails are sent).

To fix this, simply check your PHP custom code and fix its syntax errors. To make sure you write the code correctly, please have a look at the PHP reference.

If you are getting the same type of error when using custom PHP code inside a field’s Default value area or in a select field’s Items area, you have probably already noticed that you will no longer be able to access your website’s backend area to correct the code. In this situation, you will need to change the values set for these areas directly in the database tables, specifically in the _rsform_properties table.


4 persons found this article helpful.


Was this article helpful?

Yes
No

Понравилась статья? Поделить с друзьями:
  • Php ошибка 500 как вывести
  • Php отобразить все ошибки
  • Php ошибка 405
  • Php отображение ошибок php ini
  • Php ошибка 404 header