Escaping apostrophies and other characters in text area - php

So I have found that this form I have just falls apart and doesn't even submit the content up until the first apostrophe when someone types in an apostrophe to this text area. How do I go about escaping the contents so they make it into my MySQL table? Thanks!
<form action=\"./functions/notes.php\" method='post'>
<input type='hidden' id='ID' name='ID' value='{$row['ID']}' />
<textarea placeholder=\"Add more notes here...\" name=\"notes\"></textarea><br />
<input type='submit' name='formNotes' id='formNotes' value='Add to Notes' />
</form>
then in the notes.php file
$notesID = $_POST['ID'];
$note = $_POST['notes'];
$date= date('Y-m-d');
$result = mysql_query("UPDATE Project_Submissions SET Notes=CONCAT(Notes,'<br />".$date." ".$note."') WHERE ID ='".$notesID."'");

Apostrophes have special meaning to SQL, so to get them into the data they need to be "escaped" PHP has a quick function for this that also does some security checks to help prevent your database from getting hacked.
$note = mysql_real_escape_string($note);
DITTO on moving away from mysql and onto mysqlI
with MySQLI, it's similar you just need to supply the connection variable....
$note = mysqli_real_escape_string($link, $note);

Related

PHP form not updating sqlite database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a PHP form which is supposed to add a book to a table of books in a SQLite database. The form submits, however a book is not added to my database.
<?php
session_start();
require("books.php");
require("layout.php");
$db=sqlite_open ("products.db", 0666, $error);
echo $header;
echo "<p>
<a href='./index.php'>Bookshop</a></p>";
echo "<h1> Add Books </h1>
<p>
<form action='' method='get' id='AddBook'>
Author: <input type='text' name='Author'><br>
Title: <input type='text' name='Title'><br>
Brief_Synopsis: <input type='text' name='Synopsis'><br>
ISBN_Number: <input type='text' name='ISBN'><br>
Publisher: <input type='text' name='Publisher'><br>
imgNumber (save img with this name under /img/): <input type='text' name='imgNum'><br>
Price: <input type='text' name='Price'><br>
Category 1: <input type='text' name='Cat1'><br>
Category 2: <input type='text' name='Cat2'><br>
<input type='submit' value='Submit' name='Submit'>
</form>
</p>";
if(isset($_POST['Submit'])){
$author = $_POST['Author'];
$title = $_POST['Title'];
$Synopsis = $_POST['Synopsis'];
$ISBN = $_POST['ISBN'];
$Publisher = $_POST['Publisher'];
$imgNum = $_POST['imgNum'];
$Price = $_POST['Price'];
$Cat1 = $_POST['Cat1'];
$Cat2 = $_POST['Cat2'];
sqlite_query($db,"INSERT INTO Books (Author, Title, Brief_Synopsis, ISBN_Number, Publisher, imgNumber, price, cat1, cat2) VALUES ('$_POST[Author]', '$_POST[Title]', '$_POST[Synopsis]', '$_POST[ISBN]', '$_POST[Publisher]', '$_POST[imgNum]', '$_POST[Price]', '$_POST[Cat1]', '$_POST[Cat2]')");
echo("Book Added!");
$dbh = null;
}
?>
Why is this code not updating my database correctly? Before I added the if statement it added an empty book to the database every time the page loaded, however now it submits and resets the form, my URL looks correct but the database does not get an item added to it.
Your code is failing silently, because you're using a GET method in your form, whereas you're using POST arrays.
Change the form's method to POST.
I also need to point out that your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
The if statement is checking if submit exists and is not null. You cannot check the input type submit, there is no associated value. You can add a hidden input and check it:
<input type="hidden" name="checkSubmit" value="Submitted">
if(isset($_POST['checksubmit']))
I also noticed that the sql injection is looking at $_POST['myvariable'] making the previous checks for variable redundant at best.

pass php variables from one form to be submitted to database in another

I have a pop up box which checks if the user is signed in or not. If he is, I'm echoing out a small form which the user will press a button and it will submit to the DB. The variables are displayed on the popup but when pressed submit, they do not pass to the submit php file.
$add_wish = "<form action='memWishList.php' method='post' id='memWishList'>
<h3>Add this item to your Wish List?</h3><br>
<input type='hidden' name='title' value='".$title."'>".$title."</input><br>
<input type='hidden' name='link' value='".$link."'></input><br>
<input type='submit' name='submit' value='Add'/><button id='cancel'>
Cancel</button>
</form>";
echo $add_wish;
I want to pass the values title and link to be submitted to the DB. Here's my memWishList.php file:
if (isset($_POST['submit'])){
//get member id
$title = mysqli_real_escape_string($_POST['title']);
$link = mysqli_real_escape_string($_POST['link']);
$mysql = "INSERT INTO wish_list (memNum, title, link, date) VALUES ('$memnum', \
'$title', '$link', now())";
$myquery = mysqli_query($mysqli_connect, $mysql);}
Doing it this way, I only get the member id and the date inserted, not the title and the link. What's the problem? The reason why I'm echoing out this form is there's an if/else statement for logged in users and non logged in. Would be much easier to do it in html but can't...
DB: memnum(varchar), title(longtext), link(longtext), date(date). I have other tables where long links and titles are inserted just fine as longtext. They're coming from rss feeds.
please check documentation: mysqli_real_escape_string function expect the string as 2nd parameter if you use a procedural approach. It could be i.e.:
$link = mysqli_real_escape_string($mysqli_connect, $_POST['link']);
You have some markup errors. Your hidden input tags should look like:
<input type='hidden' name='link' value="<?php echo $link ?>">
Update your HTML file to look like this and all of the values will be sent to the $_POST variable:
<form action='memWishList.php' method='post' id='memWishList'>
<h3>Add this item to your Wish List?</h3><br>
<input type='hidden' name='title' value="<?php echo $title ?>"><?php echo $title ?><br>
<input type='hidden' name='link' value="<?php echo $link ?>"><br>
<input type='submit' name='submit' value='Add'/><button id='cancel'>Cancel</button>
</form>

when i refresh the page the text removes by itself , php?

When I type something in a text box and save it in mysqli it works perfectly but when I refresh that same page the text that i wrote stuff, it disappears for no reason. I also I have another text box in that page and it works perfectly fine. How can I fix that? The bio text box is the one I'm having issues.
$getpro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));$pro = $getpro;
$bios = $pro["bios"];
$realtionship = $pro["realtionship"];
$impmessage = $pro["impmessage"];
if ($_POST['bio']){
$bio = $_POST['bio'] ;
$query;
}
if ($_POST['impmessage']){
$impmessage = $_POST['impmessage'] ;
$query;
}
$query = mysql_query("UPDATE `profile` SET bios ='$bio', impmessage = '$impmessage' WHERE username = '".$user_data['username']."'");<form name="bio"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="bio" rows="7" ><? echo $bios; ?></textarea><br />
<input type="submit" value="change">
</form><hr /><form name="impmessage"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="impmessage" rows="7" ><? echo $impmessage; ?></textarea><br />
<input type="submit" value="change">
</form>
I have rearranged & removed some of the code and tried tidying it a bit:
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) // if form is submitted using POST method
{
if ( isset( $_POST['bio'] ) ){
$bio = mysql_real_escape_string( $_POST['bio'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET bios ='$bio' WHERE username = '".$user_data['username']."'"); //update bios
}
if (isset( $_POST['impmessage'] ) ){
$impmessage = mysql_real_escape_string( $_POST['impmessage'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET impmessage = '$impmessage' WHERE username = '".$user_data['username']."'"); //update impmessage
}
}
$pro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));
?>
<form name="bio" action="" method="post">
<p>Bios</p>
<textarea cols="50" style="resize:none" name="bio" id="bio" rows="7" ><?php echo $pro["bios"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
<hr />
<form name="impmessage" action="" method="post">
<p>Important Message</p>
<textarea cols="50" style="resize:none" name="impmessage" id="impmessage" rows="7" ><?php echo $pro["impmessage"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
Some notes for you:
First of all avoid mysql_* functions. Instead use mysqli or PDO
I would always prefer writing the code for processing of user inputs in the very beginning of the page, ie. before outputting anything. Because, if the user inputs makes any changes on the output, it would easily display the updates since we are doing the processing before outputting anything. So, when we query the db, it would fetch the updated data. Also, if we wanted to redirect to another page or have to send some other headers to the browser, we could do it, as the headers should always be sent before outputting anything.
Another thing is, always escape user inputs. Otherwise, prone to sql injections. Best thing would be to use prepared statements which is available in mysqli & PDO.
When you name id of elements in your HTML, make sure that it is unique. Because no same ids could occur twice. But class names can occur for any number of times.
Also make sure that your PHP code doesn't get mixed up with the HTML. Properly enclose the PHP code with the <?php & ?> tags. I would always prefer avoiding shorthands.
Since you are using two forms, both the input won't reach the server side. Only a single one. If you wanted to both inputs to be reached at the same time, then use a single form.
I have also avoided unwanted assignment operations from the fetched data, to other variables.
Also, you should always properly indent your code for better readability.
I hope this would help. Wish you good luck. :)
Looks like you're running your update query every page load. If the post value isn't filled and you refresh it's going to update with empty values.
Ps sberry is right lots of other things to fix before this goes production.

PHP - Input hidden fields with variables that contain quotes

I try to make a editor for a job offer. It must have a preview function. There are 2 form. First form submits the preview, the second one appears when the preview is there and sends the variables to save them in the database. The problem is, that when the second form get submitted, all quotes disappear. I tryed mysql_real_escape_string, htmlspecialchars, htmlentitles, but nothing works. Do you got an idea where the problem is?
Could it be that there's a problem, because I use the variable '$content' to store the site's content, instead to make a direct output with 'echo'?
Thanks!
<td><input style='float:left;' type='submit' name='jobpreview' value='preview' />
</form>";
if(isset($_GET['preview']))
{
$_POST['titel'] = htmlentities($_POST['titel']);
$_POST['elm1'] = htmlentities($_POST['elm1']);
$content .= " <td><form action='?s=intern&sub=neuerjob&preview' method='POST'>
<input type='hidden' name='titel' value='".$_POST['titel']."' />
<input type='hidden' name='elm1' value='".$_POST['elm1']."' />
<input style='float:left;' type='submit' name='jobsave' value='save' />
</form></td></tr></table>";
}
You need to use the second parameter to htmlentities() to encode the quotes.
$titel = htmlentities($_POST['titel'], ENT_QUOTES);
$elm1 = htmlentities($_POST['elm1'], ENT_QUOTES);
<input type='hidden' name='titel' value='".$titel."' />
<input type='hidden' name='elm1' value='".$elm1."' />
For this purpose, htmlentities() is overkill though, and you can use htmlspecialchars()
also with the ENT_QUOTES param.
$titel = htmlspecialchars($_POST['titel'], ENT_QUOTES);
$elm1 = htmlspecialchars($_POST['elm1'], ENT_QUOTES);

PHP string cut off when emailed: simple bug fix help please

There's a comment card feature on the website I work at, that after filling out the forms, a php mail call is made to email people the comments. However, one of the strings, "comments" is getting cut off. Could someone look at this code and possibly tell me why?
EDIT: Did some testing and discovered that single and double quotes cause the problem. Any advice on dealing with this would be great. Do I want to use stripslashes or some such?
Here is an example of the problem:
Location: The place
Quality: Good
Comments: The Hot Dog at the Grill was labeled with the \\
Email: someemail#email.com
Date: 05/23/11
Time: 13:34
Here is the confirmation page: (help much appreciated, it's my first day on the job and I can't figure this out!
<?php
$date=date("m/d/y");
$time=date("H:i");
$loc=$_POST['location'];
$qual=$_POST['quality'];
$comm=$_POST['comments'];
$em=$_POST['email'];
echo("<p class=\"bodytext\">You are about to send the following information:<span><br><br><span class=\"bodytextbold\">Location:</span> ".$loc."<br><br><span class=\"bodytextbold\">How was your food?:</span>".$qual."<br><br><span class=\"bodytextbold\">Comments: </span>".$comm."<br><br><span class=\"bodytextbold\">Your email address: ".$em);
echo("<form method=\"post\" action=\"comment_card_email.html\">
<input type=\"hidden\" name=\"location\" value=\"".$loc."\">
<input type=\"hidden\" name=\"quality\" value=\"".$qual."\">
<input type=\"hidden\" name=\"comments\" value=\"".$comm."\">
<input type=\"hidden\" name=\"email\" value=\"".$em."\">
<input type=\"hidden\" name=\"date\" value=\"".$date."\">
<input type=\"hidden\" name=\"time\" value=\"".$time."\">
<input type=\"submit\" class=\"bodytext\" value=\"submit comments\" name=\"submit\"></form>");
?>
And here's the html page php script that receives it:
<?php
$location = $_POST['location'];
$quality = $_POST['quality'];
$comments = $_POST['comments'];
$email = $_POST['email'];
$date = $_POST['date'];
$time = $_POST['time'];
$recipients = "someemail#email.com";
function mail_staff($recipients, $location, $quality, $comments, $email, $date, $time){
mail($recipients, "Comment Card#[".$location."]".time(), "The following comment has been submitted:
Location: $location
Quality: $quality
Comments: $comments
Email: $email
Date: $date
Time: $time
", "From:".$email);
}
Went ahead and pulled my comments together and combined them into this answer.
You might want to consider using heredoc for those long echo statements, it will make it much cleaner and easier.
echo <<<FORM
<form method="post" action="comment_card_email.html">
<input type="hidden" name="location" value="$loc">
<input type="hidden" name="quality" value="$qual">
<input type="hidden" name="comments" value="$comm">
<input type="hidden" name="email" value="$em">
<input type="hidden" name="date" value="$date">
<input type="hidden" name="time" value="$time">
<input type="submit" class="bodytext" value="submit comments" name="submit"></form>
FORM;
Your comment about the "\" makes me think that you've accidentally escaped the rest of the string. Make sure your quotes aren't causing issues. From the look of your sample comment, it looks like the user used a double quote and that escaped the rest of your string. Try using htmlspecialchars to escape those quotes instead. htmlspecialchars is a PHP function that escapes HTML friendly entities from text. So the quotes would be in the &xxxx; format. Thus you would not need to worry about escaping quotes any longer as that would be taken care of with entities. And its reversible with htmlspecialchars_decode. So this should work.
$raw = $_POST['comments'];
$stripped = stripslashes($_POST['comments'];
$comments = htmlspecialchars($stripped, ENT_QUOTES);
Edit: Oops, the form didn't go through for the heredoc, edited it to work.

Categories