Page 1 of 1
Slash problem... Do I need addslashes() or something?
Posted: Tue Jan 30, 2007 9:25 pm
by jkashu
I need to make a page so that a client can easily edit a large amount of text online. I am currently using a textarea that includes() the .txt file with the necessary text. The client can make changes, hit submit, and the form sends the value to a php file that writes the new edited text over the old text. The only problems is that any quotes get slashes added to them when I write to the file. Do I need to use addslashes(), stripslashes(), or something like that?
This is the code I'm using to write to the file.
Code: Select all
$text = $_POST['textarea' ];
$file='textfile.txt;
$fh = fopen($file, 'w') or die('Could not open');
fwrite ($fh, $text)or die('Could not write');
fclose($fh);
Thanks for any suggestion!
Posted: Tue Jan 30, 2007 10:00 pm
by Christopher
It depends on what you want to do with the data in the file. If you wanted to display it in HTML then you would stripslashes() to clean up the test and htmlentities() to prevent cross-site scripting attacks. If you were transfering the file to a database then you use the database's escaping function.
Posted: Wed Jan 31, 2007 5:18 am
by jkashu
I just need to display it in HTML. How do I use stripslashes()? Thanks!
Posted: Wed Jan 31, 2007 6:17 am
by Kadanis
this would write clean text to the file. (the only change i've made here is that the variable $text is initialised to an empty string if the POST var textarea is not set.)
Code: Select all
if (isset($_POST['textarea'])){$text = $_POST['textarea'];} else {$text = '';}
$file='textfile.txt;
$fh = fopen($file, 'w') or die('Could not open');
$cleanText = stripslashes($text);
fwrite ($fh, $cleanText)or die('Could not write');
fclose($fh);
when displaying the current contents of the file you would want to use the function htmlentities() (as already mentioned).
for example
Code: Select all
$text = '';
$file='textfile.txt;
$fh = fopen($file, 'r') or die('Could not open');
while (!feof($fh )) {
$text .= fread($fh , 8192);
}
fclose($fh);
$cleanText = htmlentites($text);
echo "<textarea>$cleanText</textarea>";
Posted: Wed Jan 31, 2007 10:22 am
by pickle
The slashes are probably being added because you have the magic_quotes_gpc directive turned on in php.ini. You can check that by calling
get_magic_quotes_gpc():
Code: Select all
$cleanText = (get_magic_quotes_gpc()) ? stripslashes($dirtyText) : $dirtyText;
Posted: Wed Jan 31, 2007 2:54 pm
by jkashu
Thanks for the help! Everything is working perfectly now.