apostrophe in PHP string - php

This is weird! I have a form which gets info from a DB and then fills in a form with the details. I am trying to cater for cases where a person has a name like O'Neill. At the top of the page (outside the actual form itself) is a line that echoes the user's name to the screen:
<h2>Member Details for <?php echo $thefn; ?></h2>
And this does indeed display on the page properly, i.e., Member Details for Mike O'Neill
However, in the actual form, where the code runs:
<td><?php echo "<input type='text' name='fname' value='$thefn' size='30' maxlength='30'>"; ?></td>
The name is shown with everything after the apostrophe gone! The variable is the same, so what am I doing wrong? This has got me tearing my hair out (and there's a fair amount of that!)

Let's say I put in my name as:
' /><script type="text/javascript">alert("You've just been hacked!");</script><input type="hidden" name="lol" value='hax
Now what?
htmlspecialchars($thefn)
Should help.

Use double quotes " " in your HTML like so :
echo "<input type='text' name='fname' value=\"$thefn\" size='30' maxlength='30'>";
Note that you have to escape them with \ since you already use double quotes to delimit your string (in PHP). Another solution is to use single-quotes on the PHP side (echo ' ';) and use double quotes inside the string, so that you don't need escaping.
Also note that this code is vulnerable to XSS attacks, you can use htmlspecialchars() to prevent that, here's the corrected code (both the XSS and the quotes) :
echo '<input type="text" name="fname" value="'.htmlspecialchars($thefn).'" size="30" maxlength="30">';

Ignoring the obvious security red herring here (I assume the format of your $thefn variable is correct for going between single quotes in HTML), I would be wrapping the PHP variables inside of {} brackets, like so. This has two major advantages. One - it is easier to spot replaceable parts, plus, makes it crystal clear to PHP what part is dynamic. Two - you can use fancier variables, like arrays. {$my_array['my_key']}.
<td>
<?php
echo "<input type='text' name='fname' value='{$thefn}' size='30' maxlength='30'>";
?>
</td>
See also: PHP string parsing (in the manual)

Related

Input field being rendered as plain text

Im using PHP to render a page. I have echo statements such as
echo "<input type=\"text\" name=\"numPlate\" id=\"numPlate\" onblur=\"caps(this.id);\" $focusPlate required value=\"" . isset($_POST['numPlate']) ? $_POST['numPlate'] : "" ."\">";
but the value is being output as plain text rather than in the input field. If i take the ternary out then the input field is being rendered, which tells me that causes the issue, but i really don't understand why. The problem is is that I have about 20 other fields on this page in a similar fashion, so it's not a very clean solution to evaluate each of these statements to a variable and have the respective variables input into the value property.
Are there any other ways I could achieve this? Thanks
Edit:
Rendered html:
<div class="row"><label for="plate">Rendszám*</label>GMS245</div>
As you can see the string is just a text.
I tested it out and I believe my second suggestion could solve it. Wrap the ternary in parenthesis. From my test, it was trying to evaluate the true response to the ternary instead of setting it as the value or ignoring it. I also replaced the inner quotes with a single quote to clean up the code while still allowing the variables to be evaluated.
echo "<input type='text' name='numPlate' id='numPlate onblur='caps(this.id);' $focusPlate required value='" . (isset($_POST['numPlate']) ? $_POST['numPlate'] : "") ."'>";

Changing " to ' in PHP - HTML Form

I'm building a form in PHP and I have a field that currently works fine like this:
<input type='text' name='Name' value='Name'/>
But I dont want the users to have to rub out the value manually so I did this:
<input type='text' name='Name' value='Name'
onblur="if(this.value==''){ this.value='Name'; this.style.color='#BBB';}"
onfocus="if(this.value=='Name'){ this.value=''; this.style.color='#000';}"
style="color:#BBB;" />
But obviously since this is in PHP and the form starts with $output="<form... it didnt work and brought up errors because of the "
So I then created this:
<input type='text' name='Name' value='Name'
onblur='if(this.value==''){ this.value='Name'; this.style.color='#BBB';)'
onfocus='if(this.value=='Name'){ this.value=''; this.style.color='#000';}'
style='color:#BBB' />
Which doesn't through up errors, but simply doesn't work. I mean the form shows up correctly, but the value does not disappear with clicks. So I thought of changing the ' inside the onblur and onfocus to " and this worked in html but brought up the same error as before in php. So what is the solution to this?
Escape the quotes:
$output = "<input type='text' name='Name' value='Name'
onblur=\"if(this.value==''){ this.value='Name'; this.style.color='#BBB';}\"
onfocus=\"if(this.value=='Name'){ this.value=''; this.style.color='#000';}\"
style='color:#BBB;' />";
There's one really really simple solution to this: use HTML5 placeholders:
<input type="text" name="Name" placeholder="Name">
(This will automatically be a lighter color than the original, so the style attribute is not required here)
This is supported by all modern browsers, as seen here. Only IE versions 9 and lower don't support this, and those browsers only have 5% of all browser usage, so generally it's better to drop support for older browsers in favour of features that make your life much easier.
Use backslashes before '
For example:
<input type='text' name='Name' value='Name'
onblur='if(this.value==\'\'){ this.value=\'Name\'; this.style.color=\'#BBB';)'
You can use backslash to escape quote characters inside strings. Eg: "…\"…" or '…\'…'. The problem is that this easily becomes hard to read. What can really improve readability is to use HEREDOC syntax:
$output = <<<_
<input type='text' name='Name' value='Name'
onblur="if(this.value==''){ this.value='Name'; this.style.color='#BBB';}"
onfocus="if(this.value=='Name'){ this.value=''; this.style.color='#000';}"
style="color:#BBB;" />
_;
You can even expand variables inside it and still keep the markup fairly readable. Example:
$output = <<<_
<div class="$c">$t</div>
_;

PHP echo changing text?

I'm a beginner PHP programmer, and I was wondering what was wrong with my code.
Here is the small excerpt from the affected spot:
echo "<form action='?tab=4' name='toedit5' method='get'><input value='text' onblur='edit('toedit5')' /></form>";
In Chrome's Developer Tools, the form element totally disappears, and the edit('toedit5') becomes edit(' toedit5').
The edit() function doesn't execute.
Is there anything wrong with this one line of code? Otherwise it is outside code messing with it. Sorry I didn't include it, but I don't know what to include. If you need more information, please tell me.
Thanks.
You need to escape your quotes inside your quoted echo'd statement, like this:
<?php
echo "<form action='?tab=4' name='toedit5' method='get'>";
echo "<input value='text' onblur='edit(\"toedit5\")' />"; // escaped..!
echo "</form>";
?>
It helped me to think about it like this when I was starting out: how does your browser know if the second single quote in onblur='edit('toedit5')' is closing your onblur statement or opening up the parameter? In this example, your browser will pair up the first 2 quotes it sees and assign that to the onblur attribute, i.e.: onblur='edit(' only!
Update 1:
Using the code above, I inspected a quick PHP page I created in Chrome's developer tools and was able to see the following (form available for inspection):
You really should use the more standard double quotes around the HTML properties and use single quotes around your string, with escaped single quotes within the javascript method calls. Like this:
echo '<form action="?tab=4" name="toedit5" method="get"><input value="text" onblur="edit(\'toedit5\')" /></form>';

getting SQL database infor to a dynamically created text box

Hi I have a text box dynamically created to get a value from a database. The specific line in the code is as follows and it works fine;
<input name='routename' class='colr' type='text' id='routename' size='20' maxlength='40' value=".$row['route']."></td>
How ever my database has a value 'colombo/ srilanka' and when the result is loaded to the text box it captured only 'colombo/' and 'srilanka' is missing. In other words text after the space is not loaded to the textbox. Can someone help me with a workaround?
Thanks for looking!
You missed the quotes of the value, and don't forget using htmlspecialcharor htmlentities.
"<input name='routename' class='colr' type='text' id='routename' size='20' maxlength='40' value='".htmlspecialchar($row['route'])."'></td>"
Try htmlentities():
echo "<input name='routename' class='colr' type='text' id='routename' size='20' maxlength='40' value='".htmlentities($row['route'])."' /></td>";
When you echo anything from PHP into HTML, you should always wrap the string with htmlentities to make sure the outputted string is safe for HTML to display (without inadvertently writing markup to the page instead).

In PHP, how do I make a mySQL select query that contains both quotation marks and apostrophes?

I'm getting data into my database without any problem using mysql_real_escape_string.
So an entry in the database might be:
1/4" Steve's lugnuts
So that's perfectly in the database.
Now I want to search for that exact thing. But, it will mess up at either the " or the ' (I've tried a number of things, and it always messes up somewhere).
Here's what I have now:
(user_input comes from a form on the previous page)
$user_input=mysql_real_escape_string($_REQUEST['user_input']);
$search_row=mysql_query("SELECT * FROM some_table WHERE some_column LIKE '%$user_input%' ");
while($search = mysql_fetch_array($search_row))
{stuff happens}
echo "<form action='search_results.php' method='post'>";
echo "<input name='user_input' type='text' size='50' value='" . $user_input. "'>";
echo "<input type='submit' value='Lookup Parts' />";
echo "</form>";
But the problem is, I can't seem to get anything but errors.
The search field (which is supposed to populate with what they already put in) just has:
1/4\" Steve\
What am I doing wrong?
The search field (which is supposed to populate with what they already put in) just has 1/4\" Steve\
of course it has!
You misplaced your escaping.
mysql_real_escape_string is for SQL only! but you're using it's result for the html. While for the HTML you have to use completely different way of escaping.
So, make it
$user_input=mysql_real_escape_string($_REQUEST['user_input']);
$search_row=mysql_query("SELECT * FROM some_table WHERE some_column LIKE '%$user_input%' ");
while($search = mysql_fetch_array($search_row))
{stuff happens}
$user_input =htmlspecialchars($_REQUEST['user_input'],ENT_QUOTES); // here it goes
echo "<form action='search_results.php' method='post'>";
echo "<input name='user_input' type='text' size='50' value='$user_input'>";
echo "<input type='submit' value='Lookup Parts' />";
echo "</form>";
also note that there is no use in echoing such large chunks of HTML. Just close PHP tag and then write pure HTML:
?>
<form action='search_results.php' method='post'>
<input name='user_input' type='text' size='50' value='<?=$user_input?>'>
<input type='submit' value='Lookup Parts' />
</form>
Looks WAY more clear, readable and convenient
Well, your problem is proper quoting. Your problem is that you need different quoting for MySQL and for HTML, and you probably could also have magic_quotes_gpc set! When quoting, you always quote text for some particular output, like:
string value for mysql query
like expression for mysql query
html code
json
mysql regular expression
php regular expression
For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (assure it is switched off!!!).
So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)
mysql_real_escape_string($str)
mysql_real_escape_string(addcslashes($str, "%_"))
htmlspecialchars($str)
json_encode() - only for utf8! I use my function for iso-8859-2
mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times!
preg_quote()
EDIT: Regarding your original question - if you correct your quoting, you can then of course use any characters in the strings, including the single and double quotes.
Print your sentece "SELECT * FROM some_table WHERE some_column LIKE '%$user_input%' " to see what it is doing (and escaping).
Not a solution but take a look to mysqli or pdo (http://stackoverflow.com/questions/548986/mysql-vs-mysqli-in-php), they have utilities for prepared statements.
don't know if it helps for sure, but shouldn't you escape for the query and another time for the html?
$query = sprintf("SELECT * FROM some_table WHERE some_column LIKE '%s' ", mysql_real_escape_string($user_input));
echo "<input name='user_input' type='text' size='50' value='".htmlentities($user_input)."'>";
edit
you maybe don't want to change (escape) your input ($user_input) everytime you submit ..although if its only ' and " thats affected it might not matter anyway

Categories