Mordent
Mar 16 2008, 02:12 PM
I'm curious as to the best methods of letting users submit data to a MySQL database, displaying that data, and removing any unwanted tags etc. from it. Currently, there's a handful of PHP functions that I know of to help with this: - mysql_real_escape_string() - perhaps the best known and most commonly used function, it should be used in pretty much any MySQL query. It escapes characters that have SQL significance.
QUOTE(php.net) ...which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a I like to think I made a pretty good attempt at finding out what \x00 and \x1a are, but I can't find anywhere that will simply tell me. I'd assume that one of them is a hyphen (-), as that has special significance in SQL? - strip_tags() - removes all HTML tags (including malformed ones) except those given in the second argument.
- nl2br() - converts all newlines (i.e. "\n") to "<br />"
- htmlspecialchars() - converts characters that have HTML significance (i.e. ", ', &, <, >) in to ones which will simply display instead of having any HTML meaning.
- htmlentities() - any idea what the difference between this and htmlspecialchars() is?
QUOTE(php.net) This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. Anyone care to comment on how that would handle a string differently from htmlspecialchars()? - addslashes() - adds "\" before quotes (both ' and "), other backslashes and NUL. According to php.net the function should be used when <i>entering</i> data into a database, although if magic_quotes_gpc is on (which, I believe, is the case both by default and on AstaHost's servers) then it is entirely unnecessary, as apparently:
QUOTE(php.net) 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.
- stripslashes() - effectively reverses (?) addslashes().
So, given the function arsenal above, what can we get out of it? Clearly we could apply a lot of overkill to some strings, which would be unnecessary, but what's the minimum that needs to be done to make user-inputted data secure and still output what you want? Let's say we have a textarea which the user can input whatever they like in to, and in all cases the data will be stored in a MySQL database and can be displayed exactly as typed (mainly because that's the bit I'm working on  ). Take this forum, as an example. I can quite happily type things such as "<b>foobar</b>" and they display exactly as entered. The quotation marks are left in, the bold tags are displayed, but not carried out. All formatting such as using bold text is done on the user's side with BB Code, which uses square brackets. For now, however, I want to leave this additional formatting alone, and just show precisely what's typed in. So, back to the textarea idea, let's say we have a form as below: CODE <fieldset> <legend>Update Text</legend> <form action="update_text.php" method="post"> <textarea cols="100" rows="10" name="text"></textarea><br /> <input type="submit" name="update" value="Update" /> </form> </fieldset> So whatever the user types in is sent (via POST) to the script update_text.php. In that file we want to store it in a MySQL database. Given that we have a method of identifying the user by an ID (via sessions, most likely), and that the required file connects to the database. CODE ... // process input $text = $_POST['text']; // access database require('includes/db.php'); mysql_query('UPDATE members SET text = "' . mysql_real_escape_string($text) . '" WHERE id = "' . mysql_real_escape_string($id) . '"') or die(mysql_error()); ... So, correct me if I'm wrong, but that would store the text so it can be recovered as entered? Newlines ("\n") would be put in, naturally, and any relevant characters would be escaped so that they're stored in MySQL correctly, and the possibility of SQL injection here would be low, right? The data would now be stored, theoretically exactly as inputted. If we want to get that data back out, so that it's shown by default in the form we could do so as shown below: CODE ... // access database require('includes/db.php'); $getMember = mysql_query('SELECT text FROM members WHERE id = "' . mysql_real_escape_string($id) . '"') or die(mysql_error()); if (mysql_num_rows($getMember) == 1) { // member found $row = mysql_fetch_array($getMember); $currentText = htmlspecialchars($row['text']); } ... ...and then echo $currentText between the textarea tags in the form? htmlspecialchars() would need to be used, I believe, to stop people from closing the textarea early themselves and going on to do anything else they want. I'm pretty sure no other functions in the list above need to be used, but I'd like to confirm that. Then, when displaying the text (i.e. not in the textarea), I assume something like this could be used: CODE ... // access database require('includes/db.php'); $getMember = mysql_query('SELECT text FROM members WHERE id = "' . mysql_real_escape_string($id) . '"') or die(mysql_error()); if (mysql_num_rows($getMember) == 1) { // member found $row = mysql_fetch_array($getMember); $text = nl2br(htmlspecialchars($row['text'])); } ... ...which is identical to the previous method except for the use of nl2br() as well. Note that it's used after htmlspecialchars(), as otherwise the "<br />" tags would else be converted to "<br />" afterwards. Would any other functions need to be used, or would that simply do the job to a high enough level of security and still give the desired result? Thanks in advance for any feedback or comments, Mordent
Reply
Jared
Apr 19 2008, 07:52 AM
I'm afraid I can't give you a very clear answer, but htmlspecialchars () would effectively remove anything that could be maliciously (bad choice of word) interpreted in HTML.. So as far as security goes, you're fine. Now we just have to worry about formatting. Essentially, the <pre> tag would make text appear exactly as shown, so we just have to think about what the <pre> tag really does. So it turns out the <pre> tag simply treats newlines and spaces as they are entered. So we just have to format those. nl2br () would take care of the newlines, but the spaces are still unaccounted for. But this may be a simple matter... we wouldn't be able to use a regular expression to replace multiple spaces with if there were tags in the midst--[i]since <a href=""> is the same as <a href=""> and not <a href="">--HOWEVER there are no tags here! Text is being displayed exactly as it is. So we have a regular expression: (\s{2,}) Also... I just remembered... we have to watch out for tabs, too. Tabs (unfortunately) cannot be forced to print as a space can with , but you can use to make it slightly more html-friendly. So my final answer would be: CODE <?php
$text = 'your mysql variable';
$text = htmlspecialchars ($text); $text = preg_replace_callback ('/(\x20{2,})/', create_function ('$matches', '$list = false; for ($i = 0; $i < strlen ($matches[1]); $i++) $list .= \' \'; return $lsit;'), $text); $text = preg_replace_callback ('/(\x09{2,})/', create_function ('$matches', '$list = false; for ($i = 0; $i < strlen ($matches[1]); $i++) $list .= \' \'; return $list;'), $text); $text = nl2br ($text);
echo $text;
?> That would work. My create_function is slightly sloppy, so you might want to fix that up if you can find a better way haha.. P.S. The only way you could "make tabs format" is if you decided to replace each tab with, say, 5 spaces. It's not the same idea as the tab (since a tab has variable space) but it's close. That would be this: CODE $text = preg_replace_callback ('/(\x09{2,})/', create_function ('$matches', '$list = false; for ($i = 0; $i < 5 * strlen ($matches[1]); $i++) $list .= \' \'; return $list;'), $text); Hope this helps!!! - Jared
Reply
Similar Topics
Keywords : letting, users, add, mysql, data, php
- Hard Drive Data Recovery Review
(6)
What You Need Before You Can Create A Text-based Game..
Using PHP, HTML and MySQL (5) Please comment and rate, after you finished reading! /smile.gif"
style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />
################################################################# Change log: Aug 22 2008: The
Tutorial Was Created. V1.0.0 Aug 30 2008: Added XHTML and a small CSS part. Also corrected some
small things and added this change log. V2.0.0
################################################################# OK.. Many people here want to
create text based games. Many of you ask us here on the forums: "how to create a text-based ....
Mysql Multiple Tables
(1) It is good practice to use multiple tables to sort out big amounts of data. But once you do that it
becomes increasingly hard to cross reference the tables. Mysql has a little beautiful command
structure that they have added. You can select multiple tables within one sql query. Example of a
basic sql query CODE $sql = "SELECT * FROM table WHERE row=1"; If you noticed
that I selected all of the rows in the table. Normally you will try to not select the entire table
from the database unless you absolutely want all of the table. I would recommend against....
Any Website Provide Free Host Mysql Host?
(4) any website provide free host mysql host? i need it because i am using 000webhost.com now but it
only provide 2 mysql database... can i know where or how can i get more databases regards....
How To: Display A Members/user List.
With PHP, Mysql, and HTML. (3) Alright, some of you might want to display your User's or Members on your site. Notes: 1.This
is to fit in with Feelay's register and Log-in scripts you can find in the tutorial section. 2.I
made this to show the members of my site who is a member and what their ID is. First off, we must
set up a connection to our MySQL Database. CODE <?php $con =
mysql_connect("localhost","database_username","database_username_password
4;); if (!$con) { die('Could not connect: ' .
mysql_error(....
Reading Xml Data
Within PHP (2) So I was idly pondering my next PHP venture today - more on that if/when I get it done - when I
realised I needed to be able to read some data in from files. Sure, I could use simple binary files
(each line having the relevant data on it, etc. etc.), but I figured I'd might as well learn how
to use this snazzy XML stuff I keep hearing about. So, after looking at W3Schools for a bit I
couldn't find an obvious way of reading XML files in PHP . There was plenty of information of
how to do it in JavaScript, but as I want to read the files in on the server rather th....
Mysql On Computer
XD (9) I posted PHP on computer? , but for some reason it doesn't show :/. Anyways I am wondering if
there is MYSQL on my computer, meaning can i make a data base on my computer? that way i make what i
want and upload it when i get hosted =)....
Can You Link Game Maker With Mysql/php
Title says it :D (0) Hello, I am new to this service and i think I am going to like it =). Anyway, my main question is
can you link executable games made by gamemaker (i have pro) to a database? And can i use the php
server i get here to transfer data to that game? If so i would appreciate a little help with it
because I am new to both =). Also is there anyway to get a www.mywebsite.com via credits from
astahost? Finally is there any group here that works with gamemaker? we might have small contests
or so /tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" /....
Mysql Database Entry By Excel Sheets
(2) Hello .. I would like to ask if i can use use Microsoft excel files in order to make entries to
mysql database. Thanks....
Mysql Database Management
(1) Hi i am new, I have a problem in understanding the query decomposition in D-DB. Can anyone help me
to understand the first question of the exercise 25.21 of Elmasri-Navath 4th edition? Consider the
following relations: BOOKS (Book#, Primary_author, Topic, Total_stock, $price) BOOKSTORE
(Store#, City, State, Zip, Inventory_value) STOCK (Store#, Book#, Qty) Consider a distributed
database for a bookstore chain called National Books with 3 sites called EAST, MIDDLE, and WEST.
Consider that BOOKS are fragmented by $price amounts into: B1:BOOK1:up to $20.....
Mysql And User File_priv
(0) HI, I've hit the grain while trying to import file to mysql database - I need to enable file
permissions of the database user but this seems not possible with most of the hosting providers.
The problem is to set file_priv of the database user to "Y" . This is done in the "user" table of
the maintanance database named "mysql". cPanel doesn't allow this. Via the cPanel you can only
allow privileges on table querries but you cannot grant host file privileges to the database user -
which makes querries like: "LOAD DATA INFILE 'filename' INTO TABLE tablen....
Mysql With My Own Server
few questions (4) Hi, I've only just joined the forum Can you link the mysql database here to your own website?
If so how would I go about it Thanks =D....
What Mac's Do You Own?
Mac users - represent! (11) Hello, Post what Mac's do you own! Let's start: - Macintosh SE (4MB RAM, 160MB HDD,
16MHz CPU) - Macintosh Quadra 950 (128MB RAM, 1GB HDD, 33MHz CPU) - PowerMacintosh 8100/80AV (256MB
RAM, 4GB HDD, 80MHz CPU) - PowerMacintosh G3 Desktop (256MB RAM, 40GB HDD, 333MHz CPU) - iBook G4
(1.5GB RAM, 80GB HDD, 1.33GHz CPU, 12" display) - iMac G5 (1.5GB RAM, 120GB HDD, 1.8GHz CPU, 20"
display) - iMac C2D (1.5GB RAM, 250GB HDD + 500GB external HDD, 2.16GHz Dual-Core CPU, 24" display)
- MacBook Pro (2GB RAM, 120GB HDD, 2.16 Dual-Core CPU, 15" display) /biggrin.gi....
Do Google Search Better Than Yahoo?
This is a question for you all google users!! (15) Do you think google search is better than yahoo?? Are they have similar search?? Well for me google
search is more effective than yahoo search engine.....
Login System Using A Mysql Db
How do i do this? (5) Hi guys, ive got a registration system that looks something like the one below: Firstname:
Lastname: Then i have inset.php, which looks like the following: $con =
mysql_connect("localhost","autobot","abc123"); if (!$con) { die('Could not connect:
' . mysql_error()); }mysql_select_db("my_db", $con);$sql="INSERT INTO person
(username, password) VALUES ('$_POST ','$_POST ')";if
(!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record
added";mysql_close....
New Windows Live Messenger 8.5 Beta!
For Vista and XP users only (13) hey, i would just like to tell you guys that the new and LEGAL copy of Windows Live Messenger 8.5
beta is now available from Microsoft at http://ideas.live.com The new slick theme is made to
'blend in' to Windows Vista's Glass effects throughout the Operating System. I have
downloaded it and It does match Windows Vista perfectly. I reccommend everyone to download WLM 8.5
beta if you got XP or especially Windows Vista /smile.gif" style="vertical-align:middle" emoid=":)"
border="0" alt="smile.gif" />....
Data Recovery
what should i use? (14) I sent a computer in for a motherboard replacement. I could have done it myself, but i figured why
not save some time. The computer came back from the shop with not only the motherboard replaced, but
the hard drive reformatted and windows reinstalled as well. After yelling at the guy for his
stupidity, I've now settled down to try to recover the lost data. The problem with what i'm
using (R-studio) is that it will recover a formatted partition, but because windows has been
installed again on top it only sees that one. What are my chances of recovering the data, a....
Qupis : Free Cpanel Web Hosting (one Line Text Ad At Bottom)
150 MB space, 10000 MB Bandwidth, php, mysql, CPanel (10) Hello Members, We are proud to introduce a new member to Xisto group of sites.
Qupis : Free Web Hosting 150 MB space, 5000 MB Bandwidth, php,
mysql, CPanel (Latest). Emails, FTP, Addon domains, Parked Domains etc.
http://www.Qupis.com
Feel free to add your reviews and comments about it. -AstaHost
Management ....
Navcat For MySQL
is Navcat any good? (8) Hello all, i ve recently come across NavCat (GUI tool) for MySQL. I have not bought a copy yet, just
played around with the demo. Has any one used it beore, if so please let me know if its worth
buying. I already have PhpMyadmin, Just wanna know if NavCat is better than PhpMyAdmin in usibility
and functionality. Regards....
PHP & MySQL: Displaying Content From A Given ID
(6) Okay so I got this sample link (not working): http://www.acosta.com/joo.asp?id=654 Now suppose
I have a PHP file that would use MySql in order to get all values in the row where id 654 is found.
Here's a sample DB: Table: demnyc ______________________________________ | id |
Name | Age | Email | *----------------------------------------------------* | 1
| Albert | 17 | no email |
*----------------------------------------------------* | 2 | YaPow | 888 |
no email | |__________....
Games For Samsung D900
Install games with data cable (3) Hello everyone. I have a problem and perhaps you can help me out? I have a samsung d900 and I want
to install games using a data cable. Does anyone know how to do it? Thanks in advance!....
MySQL, Multiple Tables
(24) Ok, I'm coding a project which is a leap than what I'd normally do. Before, I've always
learned ONE table... put EVERYTHING in one database table. I'm making a profile system so there
needs to be at least two tables: 1 for users, 1 for content. My problem is, how do I link the two
together? I could probably figure this out faster if someone explained and posted sample SQL code
that shows how the two are linked together. Thanks!! F....
MySQL Output Database Question
(18) I am new to MySql and have just created a database after using a script. My problem is not the
script, but what it says about putting it into the output file. I cant figure out the right terms
to put it in, I keep getting errors. I try using; SELECT*FROM 'database name' WHERE
'location' but it isnt working. I'm lost with this stuff, I really am. Can someone
please help me out?....
[PHP + MySQL] Encrypting Data
To protect the password of your DB, for example. (9) Hi! This is my 2nd code of PHP + MySQL. This code is VERY simple: it encript the data in the
MySQL DB. Here we go! ------------------------------------------------------------------------
CODE <?php $password = "abc"; $new_password = md5($password);
echo $new_password; ?> The password "abc" was codfied using md5() This will be:
900150983cd24fb0d6963f7d28e17f72 CODE <?php $normal_pass = "abc";
$encripted_pass = "900150983cd24fb0d6963f7d28e17f72"; if(md5($norm....
Need Help With A PHP - MySQL Registration Script
Wont INSERT into the database (13) hey well can some one helpme make this code work it won't INSERT INTO THE DATABSE CODE
<?php # register1.php # common include file to MySQL include("DB.PHP");
$Username=$_POST['Username'];
$Password=$_POST['Password'];
$Name=$_POST['Name']; $Last=$_POST['Last'];
$Sex=$_POST['Sex']; $Month=$_POST['Month'];
$Day=$_POST['Day']; $Year=$_POST['Year&....
Convert Fat32 To Ntfs Without Data Loss (dos-mode)
(5) Some computer's are sold with windows XP pre installed and with FAT32 FORMAT, so there is a way
to change it without data loss. Go do MS-DOS and type convert c: /fs:ntfs, dont forget to change
the drive c:\, d:\ , e:\ for the one that you wanna convert . PS : This process
is impossible to return to FAT32, once you convert you can't turn back , unless you format your
pc /biggrin.gif' border='0' style='vertical-align:middle' alt='biggrin.gif' /> cheers
m8's /biggrin.gif' border='0' style='vertical-align:middle' alt='biggrin.gif'....
Phishing In Myspace
Any users of myspace should have a read. (8) A friend of mine had some trouble with a guy posting comments on her myspace page. He posted
messages that once loaded into the users browsers, would redirect the user back to the myspace login
page. I checked it out and found out that it was more than a little problem. The message that was
posted on the page was a simple flash object that seems to be hosted on:
http://itr.****youanddie.com/ I cracked the flash file, it doesn't have a lot to it, all it
has is some actionscript: getURL("http://itr.****youanddie.com/index.php", "_parent", "GET"); What
this mean....
Recover Tables From A MySQL .frm File
(8) I have a couple of .frm files with no corresponding data or index files. Is it possible to recover
the table structure (field names, types, sizes, rows,col, etc) from these files? The table type is
innodb....
MySQL Realtime Replication
how to replicate mysql in realtime (4) i dont know if this might be useful to ppl here, but this is a very good knowledge for serious
siteadmins. while i was digging for mysql backup techniques, i've found that mysql is able to
do realtime replication. the idea is that there are master server and slave server. both are having
the same version of mysql installed. the data flows; Master >copy> Slave ( in realtime!)
you'll never have to manually copy the database file of wasting your time to manually use the
mysqldump command. here are the links; http://dev.mysql.com/doc/mysql/en/Replication_HOW....
MySQL - Trouble With Bulk Insert Statements
(3) I'm trying to insert about 500 rows into mysql, but I keep getting errors. If I copy and paste
too many (about 50) insert statements at a time I get errors sometimes. I sometimes even get errors
but then the row is skipped so I don't know there was an error (I'm using linux and SSH).
What's the best way to get my insert statements to put the data in MySQL? Is there anyway that I
can have it tell me if there where any errors all the statements are executed? Thanks for your
help.....
Looking for letting, users, add, mysql, data, php
|
|
Searching Video's for letting, users, add, mysql, data, php
|
advertisement
|
|