magic_quotes_gpc confusion

Hello all,
I need some help getting this understood.
I got magic_quotes_gpc on by default on my host, and i cannot change it from anywhere, the only way i can change it is adding the stripslashes function, but in the same time i also must use mysql_real_escape.
So i came across a problem, i got a form where ppl can uplaod comments, each newline gets transferred to <br>, however the function nl2br fails to transfer anything after i use both functions above.

So i tried a few ways (all fail, need explanation on why and how to solve)

  1. adding stripslashes and right after that mysql_real_escape
    result: backslashes banish but nl2br function fails to add newlines.
  2. using only mysql_real_escape
    result: nl2br fails and backslashes are there.
  3. using only stripslashes
    result: nl2br success but regular backslashes added by the user are vanished, also as i read guides i see that its not safe not using mysql_real_escape, altho i dont know about the particular case where magic_quotes are on
  4. using neither functions.
    result: everything’s get uploaded as expected, but same as 3, not sure about the security when mysql_escape is not used.

Any ideas?

At the top of the script, use strip_slashes.

Only on the values you will use for database stuff, use mysql_real_escape_string.

$sql = "
  FROM tablename
  WHERE name = '" . mysql_real_escape_string($_POST['name']) . "'

Use nl2br only when you want to display the value to the user (and not in a textarea):

echo nl2br($_POST['name']);

If you want to sanitize the user input before outputting it to the screen, take a look at PHP functions like strip_tags

I was actually planning on inserting the input to the database with brs so when displaying i wont have to call the <br /> function on every comment box, then when someone wants to edit their post (via textarea) ill use a reverse function such as :
str_replace(‘<br />’,‘’,$post)
and the newlines will be there since the \r
are not removed.

Most web hosts allow customers to change PHP configuration settings using a php.ini file. You would create a php.ini file and stick this line in it:

magic_quotes_gpc = Off  

If your web host does not allow you to make simple configuration changes to shut off that annoying and stupid magic quotes, you need to find a better web hosting company.