Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 65
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Porady zamieszczone tutaj przez Darka są pomocne w wielu chwilach. Wielokrotnie tworząc jakiś złożony serwis korzystam z tych porad. Można by tworzyć samemu te skrypty, ale tak naprawdę czy nie lepiej jest wziąć skrypt z tej strony i zmodyfikowac go dla swoich potrzeb? Wprawdzie możemy taki skrypt napisać sami, ale po co, skoro stracimy czas na coś, co ktoś juz napisał, przetestował i może zagwarantować, że działa poprawnie. Któryś raz z rzędu opłacam abonament i nie raz jeszcze opłacę. Kawał dobrej roboty i ogrom wiedzy w jednym miejscu.

Piotr Karamański
Design Studio

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

addslashes

(PHP 3, PHP 4, PHP 5)

addslashes -- Quote string with slashes

Description

string addslashes ( string str )

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. Most databases do this with a \ which would mean O\'reilly. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

Przykład 1. An addslashes() example

<?php
$str
= "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

See also stripslashes(), htmlspecialchars(), quotemeta(), and get_magic_quotes_gpc().




User Contributed Notes

21-Jan-2006 08:59



ronald
27-Nov-2005 12:21

'safed' claims that addslashes() is no good for securing MySQL queries, as it does not escape \n  and \r. However the MySQL reference (http://dev.mysql.com/doc/refman/4.1/en/mysql-real-escape-string.html) states "Strictly speaking, MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. This function quotes the other characters to make them easier to read in log files."

So addslashes() should be fine from that point of view.


luciano at vittoretti dot com dot br
31-Oct-2005 12:18

Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).

function addslashes_mssql($str){
   if (is_array($str)) {
       foreach($str AS $id => $value) {
           $str[$id] = addslashes_mssql($value);
       }
   } else {
       $str = str_replace("'", "''", $str);   
   }
  
   return $str;
}

function stripslashes_mssql($str){
   if (is_array($str)) {
       foreach($str AS $id => $value) {
           $str[$id] = stripslashes_mssql($value);
       }
   } else {
       $str = str_replace("''", "'", $str);   
   }

   return $str;
}


thisisroot at gmail dot com
26-Sep-2005 06:30

In response to Krasimir Slavov and Luiz Miguel Axcar:

There are several encoding schemes for inserting binary data into places it doesn't typically belong, such as databases and e-mail bodies. Check out the base64_encode() and convert_uuencode() functions for the details.


Krasimir Slavov kkslavov at yahoo dot com
16-Sep-2005 08:51

If you have problems with adding images or other binady data with addslashes() for php 4.3 >= use:

<?php
$search
= array("\x00", "\x0a", "\x0d", "\x1a", "\x09");
$replace = array('\0', '\n', '\r', '\Z' , '\t');

$chrData .= str_replace($search, $replace, $Data );
?>

and put in your SQL field='$chrData' ! please remark quotes


Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br)
01-Sep-2005 03:16

Hello,

If you are getting trouble to SGDB write/read HTML data, try to use this:

<?php

//from html_entity_decode() manual page
function unhtmlentities ($string) {
  
$trans_tbl =get_html_translation_table (HTML_ENTITIES );
  
$trans_tbl =array_flip ($trans_tbl );
   return
strtr ($string ,$trans_tbl );
}

//read from db
$content = stripslashes (htmlspecialchars ($field['content']));

//write to db
$content = unhtmlentities (addslashes (trim ($_POST['content'])));

//make sure result of function get_magic_quotes_gpc () == 0, you can get strange slashes in your content adding slashes twice

//better to do this using addslashes
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;

?>


development at lab-9 dot com
27-Jul-2005 04:23

Dumping a binary content from your database into a valid mysql insert command can be rather tricky.

Even more tricky when you have huge data sizes.

First idea was to save these INSERT INTO `$table` SET `value`='mydata'; line after line into a file (can be compressed or not, doesn't matter).

Now there I had a few problems. It seemed as if a simple addslashes() would create a wrong syntax for the mysql parser. But it's still needed.

After a lot of testing (about 4hours) I tried to replace critical strings with valid, normal strings:

<?php
$search
= array("\x00", "\x0a", "\x0d", "\x1a");
$replace = array('\0', '\n', '\r', '\Z');
?>

and hooray, it worked fine!

here the part of the code, where I replace it:
<?php
$writestring
.= $field."='".str_replace($search, $replace, addslashes($data))."'";
?>

PLEASE NOTE: each line must be broken with a correct \n sign. If you break up in the middle of texts for example, you won't be able to restore the data. So keep an eye on how you're saving this stuff. :-)

And here the complete parser, that executes a file you input line after line (it's nothing big, just useful if you have large inserts or a lot of inserts which may cannot be executed with phpmyadmin):

<?php
function getfilesize($size)
{
  
$units = array(' Bytes', ' KB', ' MB', ' GB', ' TB');
   for(
$i = 0; $size > 1024; $i++)
   {
      
$size /= 1024;
   }
   return
round($size, 2).$units[$i];
}

$MAX_QUERYSIZE = 0;

$vars = mysql_query("SHOW VARIABLES");
if(
$vars == false)
{ echo
"Get variables: ".mysql_error()."<br />"; }
while(
$row = mysql_fetch_array($vars))
{
   if(
$row['Variable_name'] == "max_allowed_packet")
   {
      
$MAX_QUERYSIZE = $row["Value"];
       echo
"Max_query_size: ".getfilesize($row["Value"])."<br />";
       break;
   }
}

echo
"<form action='' method='post'>";
   echo
"<input type='text' name='href' value='".$_POST['href']."'>";
   echo
"&nbsp;";
   echo
"<input type='checkbox' name='execute' value='true'";
   if(
$_POST['execute'] == 'true')
   { echo
" checked"; }
   echo
">";
   echo
"&nbsp;";
   echo
"<input type='submit'>";
echo
"</form>";
if(
$_POST['href'] != "")
{
   if(@
file_exists($_POST['href']))
   {
       if(@
is_readable($_POST['href']))
       {
           echo
"Filesize: ".getfilesize(@filesize($_POST['href']))."<br />";
          
$buffer = @file($_POST['href']);
           if(
is_array($buffer))
           {
               echo
"Lines: ".@count($buffer)."<br />";
               if(
$_POST['execute'] == 'true')
               {
                  
$_DB = array(    'user' => '***',
                                  
'password' => '***',
                                  
'host' => '***',
                                  
'port' => '3306',
                                  
'database' => '***');
                  
                  
$connection = mysql_connect($_DB['host'], $_DB['user'], $_DB['password']);
                   if(
$connection)
                   {
                       if(
mysql_select_db($_DB['database']))
                       {
                           for(
$i=0; $i<count($buffer); $i++)
                           {
                               if(
mysql_query(trim($buffer[$i])))
                               {
                                   echo
" L ".($i+1).": executed fine :-)<br />";
                               }
                               else
                               {
                                   echo
"L ".($i+1).": ".mysql_error()." (LEN: ".getfilesize(strlen($buffer[$i])).")";
                                   if(
strlen($buffer[$i]) >= $MAX_QUERYSIZE)
                                   {
                                       echo
" [QUERY IS TOO BIG!]";
                                   }
                                   echo
"<br />";
                               }
                           }
                       }
                       else
                       { echo
"Could not access the database!"; }
                   }
                   else
                   { echo
"Database connect failed!"; }
               }
               else
               {
                   echo
"Selected to not process file.";
               }
           }
           else
           {
               echo
"File was not read!";
           }
       }
       else
       {
           echo
"Cannot read file!";
       }
   }
   else
   {
       echo
"File does not exist!";
   }
   echo
"<br /><br />";
}
?>

If someone may has an idea, how to save and insert such blob contents with hex-decoded format ( using f.ex. bin2hex() ), please mail me. I would be happy about it. :-)


thezapper303 *at* gmx.de
02-Jun-2005 03:49

This code can be inserted somewhere in your application (near the start):

if (get_magic_quotes_gpc()) {

 // Yes? Strip the added slashes

 $_REQUEST = array_map('stripslashes', $_REQUEST);
 $_GET = array_map('stripslashes', $_GET);
 $_POST = array_map('stripslashes', $_POST);
 $_COOKIE = array_map('stripslashes', $_COOKIE);

}


yet another user
07-May-2005 10:26

@unsafed: well it worked great for me adding records to my "storyDB":

$stTitle = addslashes($wholestory[$storyid][titel]);
$stInhalt = addslashes($wholestory[$storyid][inhalt]);
$aktueller_eintrag = "INSERT INTO $dbTable (titel, inhalt) VALUES ('$stTitle', '$stInhalt');";
$eintragInDB = mysql_query($aktueller_eintrag);

withot function addslashes i had problems with chars like the single quotes, and the query didn't work.

but with this function everything worked fine...

greetz


unsafed
01-May-2005 05:23

addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.


caya
07-Feb-2005 03:13

Unfortunately magic quotes is the default and violates a simple principle: what the user types is what you get.

If you want to follow that principle the following code snippet may be useful:

function cleanData() {
   foreach($_GET as $k => $v)
     $_GET[$k] = stripslashes($v);
   // likewise for $_POST, $_COOKIE
}

...

if (get_magic_quotes_gpc()) {
   cleanData();
}

You will need to add this to every page... sorry. But this is sometimes easier than convincing a webhosting company to change the settings...(if you use a front-controller pattern it's a lot easier...)

With this principle, then you always have in memory real data.

When generating HTML, you may need then to do htmlentities(...), as you are moving from the 'php data world' to the 'html data world', but you are playing on the safe side.

Same analysis apply to generating SQL sentences...


sundevil at hexagonomistico dot com
04-Feb-2005 10:12

Hey! if you will use a database to store data that will only be accessible through a web page i.e. just for web purposes, you may use other kind of filters. I recommend to use first the addcslashes() function, in order to escape line feeds and then to replace those line feeds by the corresponding html tag. And finally use the htmlentities() function in order to replace those annoying quotes or other characters by their corresponding html tag.
For example, data stored in a textarea as:

"hola"
<hola>
m

 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt