2011-11-03 7 views
-1

Привет, парень, я делаю сайт, который включает в себя предоставление объявления для игрового сервера. Мне интересно, можно ли отделять теги от PHP от содержимого текстового поля? Как будто я оставлю его как сейчас, он может стать угрозой безопасности позже. В настоящее время единственное, что я делаю с контентом, - nl2br(). Каков наилучший способ сделать это?PHP - Удаление содержимого PHP внутри текстового поля?

Спасибо.

+0

Вы имеете в виду PHP * tags * или PHP * function call strings *? – BenM

+0

напишите свой код ... –

+0

Возможный дубликат [PHP: конечная чистая/защищенная функция] (http://stackoverflow.com/questions/4223980/php-the-ultimate-clean-secure-function) –

ответ

0
  1. Почему вы заботитесь о PHP код в текстовое поле, она может быть выполнена в любом случае?
  2. Я предполагаю, что вы хотите оставить html-теги, но удалить только код php (в другом случае вы могли бы просто использовать функцию strip_tags или htmlspecialchars).

Таким образом, решение:

<?php 
//here is content from the textarea (filled it for example) 
$content = 'some <?php echo "test"; ?> <?=test?> content <br/> here'; 

$content = preg_replace('/<\?((?!\?>).)*\?>/s', '', $content); //strip all the php code 
+0

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

+0

Код PHP не будет выполнен, если вы не назовете 'eval()' на отправленной строке. @DuncanPalmer. Ваша первая забота действительно должна быть HTML/JS (к которой относится этот ответ). Единственным другим причудливым угловым случаем, который я мог бы подумать, является ввод пользовательского ввода, запись его в файл, а затем 'include()' ing, но даже тогда его дезинфекция в первую очередь применяется. –

1
  1. Я не вижу никаких угроз безопасности с кодом PHP. Скажем, я размещаю десятки кодов в день здесь, и ни один из них не получает объяснений.
  2. Зачем беспокоиться о тегах PHP, когда обычные HTML-теги представляют реальную опасность? используйте htmlspecialhars(), чтобы сделать их неактивными, вот и все.
-1

Предисловие: это не связано только с PHP теги

Прежде всего, вы должны решить, какие разрешенная характер там, и которые не являются. Постарайтесь максимально ограничить их (и вы можете проверить с помощью регулярных выражений).

Затем защитите от XSS. Ниже приведен фрагмент кода, используемый для этого (в качестве примера):

public function clean_xss($str, $charset = 'ISO-8859-1') { 
/* 
* Remove Null Characters 
* 
* This prevents sandwiching null characters 
* between ascii characters, like Java\0script. 
* 
*/ 
$str = preg_replace('/\0+/', '', $str); 
$str = preg_replace('/(\\\\0)+/', '', $str); 

/* 
* Validate standard character entities 
* 
* Add a semicolon if missing. We do this to enable 
* the conversion of entities to ASCII later. 
* 
*/ 
$str = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u',"\\1;",$str); 

/* 
* Validate UTF16 two byte encoding (x00) 
* 
* Just as above, adds a semicolon if missing. 
* 
*/ 
$str = preg_replace('#(&\#x*)([0-9A-F]+);*#iu',"\\1\\2;",$str); 

/* 
* URL Decode 
* 
* Just in case stuff like this is submitted: 
* 
* <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a> 
* 
* Note: Normally urldecode() would be easier but it removes plus signs 
* 
*/ 
$str = preg_replace("/%u0([a-z0-9]{3})/i", "&#x\\1;", $str); 
$str = preg_replace("/%([a-z0-9]{2})/i", "&#x\\1;", $str);  

/* 
* Convert character entities to ASCII 
* 
* This permits our tests below to work reliably. 
* We only convert entities that are within tags since 
* these are the ones that will pose security problems. 
* 
*/ 
if (preg_match_all("/<(.+?)>/si", $str, $matches)) {   
    for ($i = 0; $i < count($matches['0']); $i++) { 
     $str = str_replace($matches['1'][$i], 
      html_entity_decode($matches['1'][$i], ENT_COMPAT, $charset), $str); 
    } 
} 

/* 
* Convert all tabs to spaces 
* 
* This prevents strings like this: ja vascript 
* Note: we deal with spaces between characters later. 
* 
*/  
$str = preg_replace("#\t+#", " ", $str); 

/* 
* Makes PHP tags safe 
* 
* Note: XML tags are inadvertently replaced too: 
* 
* <?xml 
* 
* But it doesn't seem to pose a problem. 
* 
*/  
$str = str_replace(array('<?php', '<?PHP', '<?', '?>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str); 

/* 
* Compact any exploded words 
* 
* This corrects words like: j a v a s c r i p t 
* These words are compacted back to their correct state. 
* 
*/  
$words = array('javascript', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window'); 
foreach ($words as $word) { 
    $temp = ''; 
    for ($i = 0; $i < strlen($word); $i++) { 
     $temp .= substr($word, $i, 1)."\s*"; 
    } 

    $temp = substr($temp, 0, -3); 
    $str = preg_replace('#'.$temp.'#s', $word, $str); 
    $str = preg_replace('#'.ucfirst($temp).'#s', ucfirst($word), $str); 
} 

/* 
* Remove disallowed Javascript in links or img tags 
*/  
$str = preg_replace("#<a.+?href=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>.*?</a>#si", "", $str); 
     $str = preg_replace("#<img.+?src=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>#si","", $str); 
$str = preg_replace("#<(script|xss).*?\>#si", "", $str); 

/* 
* Remove JavaScript Event Handlers 
* 
* Note: This code is a little blunt. It removes 
* the event handler and anything up to the closing >, 
* but it's unlikely to be a problem. 
* 
*/  
$str = preg_replace('#(<[^>]+.*?)(onblur|onchange|onclick|onfocus|onload|onmouseover|onmouseup|onmousedown|onselect|onsubmit|onunload|onkeypress|onkeydown|onkeyup|onresize)[^>]*>#iU',"\\1>",$str); 

/* 
* Sanitize naughty HTML elements 
* 
* If a tag containing any of the words in the list 
* below is found, the tag gets converted to entities. 
     * 
* So this: <blink> 
* Becomes: &lt;blink&gt; 
* 
*/  
$str = preg_replace('#<(/*\s*)(alert|applet|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|layer|link|meta|object|plaintext|style|script|textarea|title|xml|xss)([^>]*)>#is', "&lt;\\1\\2\\3&gt;", $str); 

/* 
* Sanitize naughty scripting elements 
* 
* Similar to above, only instead of looking for 
* tags it looks for PHP and JavaScript commands 
* that are disallowed. Rather than removing the 
* code, it simply converts the parenthesis to entities 
* rendering the code un-executable. 
* 
* For example: eval('some code') 
* Becomes:  eval&#40;'some code'&#41; 
* 
*/ 
$str = preg_replace('#(alert|cmd|passthru|eval|exec|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2&#40;\\3&#41;", $str); 

/* 
* Final clean up 
* 
* This adds a bit of extra precaution in case 
* something got through the above filters 
* 
*/ 

$bad = array(
     'document.cookie' => '', 
     'document.write' => '', 
     'window.location' => '', 
     "javascript\s*:" => '', 
     "Redirect\s+302" => '', 
     '<!--'   => '&lt;!--', 
     '-->'   => '--&gt;' 
); 

foreach ($bad as $key => $val) { 
     $str = preg_replace("#".$key."#i", $val, $str); 
} 

return $str; 

}

0

Вау, много плохих ответов здесь.

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

$code = '<?php echo "hi"; ?>'; 
echo $code; 

Это не делает ничего.

Однако вам необходимо беспокоиться о HTML.

$code = '<script>alert("hi");</script>'; 
echo $code; 

Это будет работать и предупреждать «привет». Чтобы этого не произошло, вы должны очистить все, что вы получаете от пользователя, прежде чем отображать его с помощью htmlspecialchars.

$code = '<script>alert("hi");</script>'; 
echo htmlspecialchars($code); 

Here is a live example и здесь a more complete answer on sanitization.

1

Там именно 3 способа для PHP кода, чтобы получить казнены:

  1. побегать.PHP скрипт
  2. передать текст, содержащий PHP код через eval()
  3. include()/require() файл, содержащий PHP код

Имея что-то вроде:

<?php 

$txt ="<" . "?php echo 'Hi mom!' ?" . ">"; 
echo $txt 

не будет волшебно сделать свой браузер вертел «Привет, мама!». Он выплюнет сам PHP-код.

Если приведенный выше код был введен в файл и вывод следующим образом:

$txt = file_get_contents('file_with_the_hi_mom_code.php'); 
echo $txt; 

было бы также не получить выполнен - ​​пользователь будет просто увидеть некоторые сырые код PHP показать на своих экранах.

Теперь, если вы:

include('file_with_the_hi_mom_code.php'); 

или

eval (file_get_contents('file_with_the_hi_mom_code.php')); 

то код будет выполняться.

+0

Я думаю, вы случайно там. –

+0

I ** смотреть ** что вы сделали там. Благодарю. –

Смежные вопросы