downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Por que usar Magic Quotes?> <Dados Enviados pelo Usuário
[edit] Last updated: Mon, 01 Nov 2010

view this page in

Capítulo 31. Magic Quotes

Magic Quotes é um processo de inserção automática de caracteres de escape (\) em todos os dados indo para o script PHP. É preferível escrever código com essa opção desligada e adicionar esses caracteres manualmente quando necessário.

O que são Magic Quotes

Quando ligada, qualquer ' (aspas simples), " (aspas duplas), \ (barra invertida) e NULL será colocado uma barra-invertida antes (' vira \') automaticamente. Isso é identico ao que a função addslashes() faz.

Existem três diretivas relacionadas a Magic Quotes:

  • magic_quotes_gpc

    Afeta os dados de requisições HTTP GET, POST, e COOKIE). Não pode ser alterada em tempo de execução e tem o valor padrão on no PHP.

    Veja também get_magic_quotes_gpc().

  • magic_quotes_runtime

    Se habilitada, a maioria das funções que retorna dados de uma fonte externa, incluindo bancos de dados e arquivos de texto, serão alterados. Pode ser alterado em tempo de execução e tem o valor padrão de off no PHP.

    Veja também set_magic_quotes_runtime() e get_magic_quotes_runtime().

  • magic_quotes_sybase

    Se habilitada, uma aspa simples é usada como caracter de escape quando encontrar outra aspa simples (' vira ''). Se ligada, sobrepõe completamente magic_quotes_gpc. Ligar ambas as diretivas significa que apenas aspas simples são substituídas por ''. Aspas duplas, barras invertidas e NULLs permanecerão intocados e não serão escapados.

    Veja também ini_get() para pegar esse valor.



add a note add a note User Contributed Notes Magic Quotes
cHao 14-Mar-2011 08:38
The very reason magic quotes are deprecated is that a one-size-fits-all approach to escaping/quoting is wrongheaded and downright dangerous.  Different types of content have different special chars and different ways of escaping them, and what works in one tends to have side effects elsewhere.  Any sample code, here or anywhere else, that pretends to work like magic quotes --or does a similar conversion for HTML, SQL, or anything else for that matter -- is similarly wrongheaded and similarly dangerous.

Magic quotes are not for security.  They never have been.  It's a convenience thing -- they exist so a PHP noob can fumble along and eventually write some mysql queries that kinda work, without having to learn about escaping/quoting data properly.  They prevent a few accidental syntax errors, as is their job.  But they won't stop a malicious and semi-knowledgeable attacker from trashing the PHP noob's database.  And that poor noob may never even know how or why his database is now gone, because magic quotes (or his spiffy "i'm gonna escape everything" function) gave him a false sense of security.  He never had to learn how to really handle untrusted input.

Data should be escaped where you need it escaped, and for the domain in which it will be used.  (mysql_real_escape_string -- NOT addslashes! -- for MySQL (and that's only unless you have a clue and use prepared statements), htmlentities or htmlspecialchars for HTML, etc.)  Anything else is doomed to failure.
shazdeh1358 at yahoo dot com 29-Jan-2011 05:41
for those who want an automatic sanitization of GET, POST, COOKIE, etc variables:

the code escapes ALL vars! That is, it effectively prevents SQL injection and XSS attaks. It lifts the need for 'magic_quotes_gpc = On' directive.

However it treats all variables as text and does not do type-cheking. So it is suitable only for making SQL queries or displaying html content.

the following code can be included in all pages which need html and sql sanitization.

<?php

// escaping and slashing all POST and GET variables. you may add $_COOKIE and $_REQUEST if you want them sanitized.
array_walk_recursive($_POST, 'sanitizeVariables');
array_walk_recursive($_GET, 'sanitizeVariables');

// sanitization
function sanitizeVariables(&$item, $key)
{
    if (!
is_array($item))
    {
       
// undoing 'magic_quotes_gpc = On' directive
       
if (get_magic_quotes_gpc())
           
$item = stripcslashes($item);
       
       
$item = sanitizeText($item);
    }
}

// does the actual 'html' and 'sql' sanitization. customize if you want.
function sanitizeText($text)
{
   
$text = str_replace("<", "&lt;", $text);
   
$text = str_replace(">", "&gt;", $text);
   
$text = str_replace("\"", "&quot;", $text);
   
$text = str_replace("'", "&#039;", $text);
   
   
// it is recommended to replace 'addslashes' with 'mysql_real_escape_string' or whatever db specific fucntion used for escaping. However 'mysql_real_escape_string' is slower because it has to connect to mysql.
   
$text = addslashes($text);

    return
$text;
}

// export POST variables as GLOBALS. remove if you want
foreach (array_keys($_POST) as $ehsanKey)
   
$GLOBALS[$ehsanKey] = $_POST[$ehsanKey];

// export GET variables as GLOBALS. remove if you want
foreach (array_keys($_GET) as $ehsanKey)
{
   
$GLOBALS[$ehsanKey] = $_GET[$ehsanKey];
}

// preventing the key used above for iteration from getting into globals (in case  'register_globals = On')
unset($ehsanKey);

// the reverse function of 'sanitizeText'. you may use it in pages which need the original data (e.g. for an HTML editor)
function unsanitizeText($text)
{
   
$text stripcslashes($text);

   
$text = str_replace("&#039;", "'", $text);
   
$text = str_replace("&gt;", ">", $text);
   
$text = str_replace("&quot;", "\"", $text);   
   
$text = str_replace("&lt;", "<", $text);
   
    return
$text;
}
?>

 
show source | credits | sitemap | contact | advertising | mirror sites