arianhojat Posted April 27, 2007 Share Posted April 27, 2007 With the various operations going on a page when magic qoutes is enabled(or disabled depending on server), i was wondering what is best logic to approach each situation (sitations of: getting the field's value from database when arriving to page, displaying the field's value on page, and when reposting the form): Note: this is just logic, not how i would code the page. Like if get_magic_quotes_gpc(), what to do in those 3 situations.... if( get_magic_quotes_gpc() ) //magic qoutes enabled { //if getting values from database via SELECT statement when arriving onto form page... not sure, do i need to strip or add slashes??? $query = 'SELECT * FROM bleh WHERE id='.$id; ... $value = $row['textfield']; //Dont need to use addslashes when inserting/updating database (assume $value is re-posted value $_POST['textfield'] ) $query = 'UPDATE bleh SET textfield='. $value .' WHERE id='.$id; //strip slashes be4 displaying posted text in form... echo '<textarea>'.htmlspecialchars( stripslashes($value) ). '<textarea>'; } else //(magic qoutes not enabled) { //if getting values from database via SELECT statement when arriving onto form page... not sure, do i need to strip or add slashes??? $query = 'SELECT * FROM bleh WHERE id='.$id; ... $value = $row['textfield']; //Use addslashes on (textfield/textarea) values when inserting/updating database (assume $value is re-posted value $_POST['textfield'] ) $query = 'UPDATE bleh SET textfield='. addslashes($value) .' WHERE id='.$id; //Dont need to do anything when displaying value on form, aka just a htmlspecialchars($value) without need for add/strip slashes on that value echo '<textarea>'.htmlspecialchars($value). '<textarea>'; } Quote Link to comment Share on other sites More sharing options...
per1os Posted April 27, 2007 Share Posted April 27, 2007 If get_magic_quotes_gpc is on, do not add slashes and when the data comes out of the db you DO NOT need to stripslashes. The goal is to NEVER stripslashes. If magic quotes is off than add slashes to the data BEFORE entering it into the DB, DO NOT stripslashes when retrieve the data. If after you entered the DB into the DB and the magic_quotes_gpc is ON, you want to display that raw data, stripslashes WOULD BE requried to do this. If after you entered the DB into the DB and the magic_quotes_gpc is OFF, you want to display that raw data AFTER doign addaslshes, stripslashes WOULD BE requried to do this so the data does not display the escaped characters. Hope that clears it up. Quote Link to comment Share on other sites More sharing options...
arianhojat Posted April 28, 2007 Author Share Posted April 28, 2007 So... basically u only use stripslashes if magic qoutes was turned on and therefore it added slashes on submitting the form? Seems like then you would only use stripslashes on form submission part of your script then. Would the followjg below be a good example of how to take on magic qoutes in each part of a submission form (pretned is a page u can insert a new entry into database or update an existing one ). $submit = $_POST['submitBtn']; function getValues() { global $submit, $textfield; //getting all values i need for this fucntion. simply set up global if( isset($submit) ) { $id = isset($_POST['theTextfield']) ? $_POST['theTextfield'] : NULL;// if edit page, will use $id later to UPDATE versus insert new $textfield = get_magic_quotes_gpc() ? stripslashes($_POST['theTextfield']) : $_POST['theTextfield']; } else { if($_GET['id']) //get from database as it came from { $id = $_GET['id']; //...database connection/query code left out $textfield = $row['Description']; } else //just arrived to page, put default values { $textfield = 'ENTER TEXT HERE'; } } } function processform() {//pretend validation was good for all fields, then this fucntion runs global $submit, $textfield; if($submit=='Update') { //at this point variables cleaned up in getValues should be cleaned up and have no slashes, so have to use addslashes $query = "UPDATE table SET Description="'.addslashes($textfield).'" WHERE id=".$id; //..rest of database code left out } else { $query = "INSERT INTO table (id, Description) VALUES (NULL, '". addslashes($textfield) ."')"; } } function showform() { global $submit, $textfield; //... pretend alot of html echo statements here echo '<div>'.htmlspecialchars($textfield) .'</div>';//should be without slashes at this point so dont need to use any stripslashes here ... } Quote Link to comment Share on other sites More sharing options...
per1os Posted April 28, 2007 Share Posted April 28, 2007 Your not listening. You only want to strip slashes when data is being printed if it came from a form submission. But really what I would do is this: <?php $submit = $_POST['submitBtn']; function getValues() { global $submit, $textfield; //getting all values i need for this fucntion. simply set up global if( isset($submit) ) { // this way all data has slashes no matter what. foreach ($_POST as $key => $val) { $_POST[$key] = get_magic_quotes_gpc() ? $_POST['theTextfield'] : addslashes($_POST['theTextfield']); } $id = isset($_POST['theTextfield']) ? $_POST['theTextfield'] : NULL;// if edit page, will use $id later to UPDATE versus insert new $textfield = $_POST['theTextfield']; } else { if($_GET['id']) //get from database as it came from { $id = $_GET['id']; //...database connection/query code left out $textfield = $row['Description']; } else //just arrived to page, put default values { $textfield = 'ENTER TEXT HERE'; } } } function processform() {//pretend validation was good for all fields, then this fucntion runs global $submit, $textfield; if($submit=='Update') { $query = "UPDATE table SET Description="'.$textfield.'" WHERE id=".$id; //..rest of database code left out } else { $query = "INSERT INTO table (id, Description) VALUES (NULL, '". $textfield ."')"; $id = mysql_insert_id($queryRes); // get the last id entered } $return = "SELECT description,id FROM table WHERE id = " . $id; $textfield = $returnRow['description']; } function showform() { global $submit, $textfield; //... pretend alot of html echo statements here echo '<div>'.htmlspecialchars($textfield) .'</div>'; ... } ?> This way you do not have to worry about the slashes technicalities. Quote Link to comment Share on other sites More sharing options...
arianhojat Posted April 28, 2007 Author Share Posted April 28, 2007 sorry if i am not understanding... //1st let me get to the meat of your update to the script... <?php if( isset($submit) ) { // this way all data has slashes no matter what. foreach ($_POST as $key => $val) { $_POST[$key] = get_magic_quotes_gpc() ? $_POST['theTextfield'] : addslashes($_POST['theTextfield']); //i think you really meant here $_POST[$val] : addslashes($_POST[$val]), right? } //below should really be... $id = isset($_POST['id']) ? $_POST['id'] : NULL; // if edit page, will use hidden form element of the id in UPDATE query later $textfield = $_POST['theTextfield']; //anyway $textfield here uses the value with the slashes added u updated in your for loop } ?> Now when you do showForm(), shouldnt you be concerned that the variable has the slashes added for you? Like if user entered 'cool' in the textfield, on post, it will add slashes no matter whats turned on, and the line echo '<div>'.htmlspecialchars($textfield) .'</div>'; would output <div>\'cool\'</div> Again really sorry if i am being retarded. I am really trying to understand what is best practice. Quote Link to comment Share on other sites More sharing options...
arianhojat Posted April 28, 2007 Author Share Posted April 28, 2007 sorry ignore this post (accidentally pressed twice), look at one above it. would be nice if u can delete Posts here. Quote Link to comment Share on other sites More sharing options...
Barand Posted April 28, 2007 Share Posted April 28, 2007 This thread might help http://www.phpfreaks.com/forums/index.php/topic,137059.0.html Quote Link to comment Share on other sites More sharing options...
arianhojat Posted April 30, 2007 Author Share Posted April 30, 2007 okay so i incorporated i think what a basic edit/insert page should have based on feedback here and reading a few more threads/php manual... 1. if arriving at the page and need to get database values... Don't strip slashes from retrieving values from database. right now normal variable with no prepended slashes. 2. If POSTed the form, and magic qoutes are on, clean out slashes from the submitted (text) fields, as we need to do validation on the normal text. 3. When processing form (INSERT/UPDATing form), add slashes temporarily at this point, preferably with mysql_real_escape_string (or addslashes ) 4. When displaying form, use htmlspecialchars on the normal un-slashed variable. And here is a 'basic' form incorporating all of that (, well not a simple hello world form). Hopefully i understood everything previously mentioned as i tried absorbing everything i could from previous posters and other threads. But if i dont get it right still, let me know specifics again of how my logic went bad (sorry in advance if i goofed somewhere). <?php function secure_query($var)//returns variable for database insertion { //i heard mysql_real_escape_string is better than addslashes as its more specific to the connection's current character set, so i use that if (!is_numeric($var))//string return "'". mysql_real_escape_string($var) ."'"; else return $var;//number } function getValues() { global $submit, $description, $comments;//getting all values i need for this fucntion. simply set up global here. (usually i pass values i need into fucntion though) //set up database connection on arrival to page $host = "localhost"; $user = "test"; $pass = "pass"; $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); if( isset($submit) )//posted form { $id = isset($_POST['id']) ? $_POST['id'] : NULL;// if edit page, will use $id later to UPDATE versus insert new OR it might be a new entry, then i set the id later with mysql_insert_id() $description = get_magic_quotes_gpc() ? stripslashes(trim($_POST['Description'])) : trim($_POST['Description']); //start off with clean variable without slashes added(, as we are going to check and validate variables, so we need the strings without slashes for regex validation etc.) $comments = get_magic_quotes_gpc() ? stripslashes(trim($_POST['Comments'])) : trim($_POST['Comments']); } else //just arrived to this page via link to thisPage.php?id=### ('Edit this Entry' page) or thisPage.php (New Entry page) { if($_GET['id']) //get info from database as it came from thisPage.php?id=### { $id = $_GET['id']; $query = "SELECT * FROM theDB.table WHERE id=". $id; $result = mysql_query($query); if( $row = mysql_fetch_array($result) ) { $description = $row['Description'];//dont need to do anything here, comes out fine from database $comments = $row['Comments']; } } else //just arrived to this page via link to thisPage.php, put default values in for textfields { $description = 'ENTER TEXT HERE'; } } } function validateForm() { global $submit, $description, $comments; //data is all good for validation, no slashes added in at this point //pretend i do a regex here to see if user submitting annoying words i dont want if($description!="") //something written to textfield so check for validation { $arrayWords = array_map( "trim", explode("," , "lol, rofl, dallas cowboys, nazis, asparagus, durian, the shredder, OMG, paris hilton"); foreach($arrayWords as $word) { if( preg_match( "/$word/i" , $description ))//if finds this word in the textfield, dont process form, and report error $errors['wordNotAllowedInField'] = '<br/>Word not allowed: '. $word; } } return $errors; } function processform() {//pretend validation was good for all fields, then this fucntion runs global $submit, $description, $comments, $id, $databaseResults; if($submit=='Update') { //At this point you want to 'addslashes' via addslashes() or even better mysql_real_escape_string() $query = "UPDATE theDB.table SET Description=".secure_query($description).", Comments=".(($comments!="") ? secure_query($comments) : 'NULL' )." WHERE id=".$id; $query = sprintf ( "UPDATE theDB.table SET Description=%s, Comments=%s WHERE id=%d"; , secure_query($description), (($comments!="") ? secure_query($comments) : 'NULL' ), $id );//hmmmm, for any of the Querys (SELECT, UPDATE, INSERT)... is a Prepared statement safer than a normal query with formatted with sprintf? $result = mysql_query($query); if($result) { $databaseResults['update']['success'] = true; } else $databaseResults['update']['failed'] = true; } else { $query = sprintf ( "INSERT INTO theDB.table (id, Description, Comments) VALUES (NULL, %s, %s)"; secure_query($description), (($comments!="") ? secure_query($comments) : 'NULL' ) ); $result = mysql_query($query); if($result) { $id = mysql_insert_id(); $databaseResults['insert']['success'] = true; } else $databaseResults['insert']['failed'] = true; } } function showform() { global $submit, $description, $comments, $id, $databaseResults; //... pretend alot of html echo statements here $num_args = func_num_args();//if an errors variable passed to this function, set $error if( $num_args > 0 ) $error=func_get_arg(0); if(isset($error)&& (count($error)>0)) echo '<div class="error">*** Please Fix the highlighted errors below.</div>'; if(isset($error['wordNotAllowedInField'])) echo '<div class="error">* '.$error['wordNotAllowedInField'].'</div>'; if( $databaseResults['update']['success']===true) echo '<div class="success">Updated Successfully</div>'; else if( $databaseResults['update']['failed']===true) echo '<div class="success">Failed to Update.</div>'; else if( $databaseResults['insert']['success']===true) echo '<div class="success">Inserted New Field Successfully</div>'; else if( $databaseResults['insert']['failed']===true) echo '<div class="success">Failed to Insert New Field</div>'; if(isset($id))//hidden input which stores id for UPDATE/editing echo '<input type="hidden" name="id" value="'. isset($id) .'" />'; echo '<div><textarea name="Description">'.htmlspecialchars($description) .'<textarea/></div>';//should be without slashes at this point so dont need to use any stripslashes here, but need to do htmlspecialchars to make sure < > escaped so wont ruin my html. also good for making user inserted javascript useless? echo '<div><textarea name="Comments">'.htmlspecialchars($comments) .'<textarea/></div>'; echo '<div><input type="submit" name="SubmitForm" value="'. ( isset($id)? 'Edit' : 'Insert New' ) .'" /></div>'; } function runForm() { global $submit; $submit = $_POST['SubmitForm']; getValues(); if( isset($submit) )//POSTed { $formErrors = validateForm(); if(isset($formErrors))//errors { showForm($formErrors);//display errors } else { processForm();//process form (Insert or Update) showForm(); //display form (successly insderted/updated message etc) } } else//just arrived to page via thisPage.php?id=### or thisPage.php { showForm(); } } runForm(); ?> Quote Link to comment Share on other sites More sharing options...
arianhojat Posted April 30, 2007 Author Share Posted April 30, 2007 I feel pretty comfortable with above code after reviewing it. probably use that as my base form code if i ever need to start a form. The only thing i guess i have a question from reviewing my own code is... For Querys (SELECT, UPDATE, INSERT, DELETE)... is a prepared statement in php safer than say a normal query with formatted with sprintf which is what i have currently? Like what would you use? <?php $query = sprintf ( "UPDATE theDB.table SET Description=%s, Comments=%s WHERE id=%d", , secure_query($description), (($comments!="") ? secure_query($comments) : 'NULL' ), $id ); ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.