Sounds very simple, but I'm kinda confused at the moment.
I have this DB object which includes some values that I want to output in an html form.
Simplified Problem:
$result is my db object and this is the html input where I want to output some text which can include double or single quotes.
<input class="someclass" name="desc" id="descID" type="text" value="<?=$result['desc'];?>" placeholder="<Description>" />
So if $result['desc'] contains text like this: 'Did you hear about "foobar"?'
everything after the first double quote gets cut off and ends up like this: 'Did you hear about '.
What i have tried already without success:
htmlspecialchars like this value="<?=htmlspecialchars($result['desc']);?>" or like this value="<?=htmlspecialchars($result['desc'], ENT_QUOTES);?>"
addslashes
Note: My DB(mssql) saves the string properly. Only have the problems in my html.
I would be glad if you could help me out here. Thanks.
Thanks for the help so far, but i managed to find a solution to this:
<?$descEscaped = str_replace('"', '"', $result['desc']);?>
<input class="someclass" name="desc" id="descID" type="text" value="<?= htmlspecialchars($descEscaped);?>" />
htmlspecialchars replaces quotes with """.
I am using my simple function htmlliteral:
function htmlliteral($s){
return '"'.htmlspecialchars($s).'"';
}
With this function you can use:
$descEscaped = htmlliteral($result['desc']);
print "<input class=someclass name=desc id=descID type=text value=$descEscaped />";
Related
I have a piece of php code inside html tag which is supposed to change the tag's style in accordance with the contents of the URL.
There is an html login form which looks like this:
<form class="userdata" action="login.php" method="post">
<input type="text" name="email" placeholder="E-mail" <?php fillin('email'); enlight_unfilled('email');?>><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit" name="login-submit">Login</button>
</form>
Here are the functions fillin and enlight_unfilled:
<?php
function fillin($key) {
if (isset($_GET[$key])) echo "value=".$_GET[$key];
else echo NULL;
}
function enlight_unfilled($key) {
if (isset($_GET['error']))
if (isset($_GET[$key]) and $_GET[$key] !== "") echo NULL;
else echo "style='border-color: red'";
else echo NULL;
}
?>
If I only apply one of the functions within the tag, they both do what they are expected to – either save the email in the field if it has been already typed in or enlighten the email field if it has been left empty. But if I apply them together, when the field is empty, php assigns the field value 'style='border-color:. I also tried to use functions like print and printf, but the result is the same:
I am a beginner at php coding and mixing it with html, so the question may appear to be dumb, but I did not manage to find any sort of a solution to this issue, so thanks for help and patience in advance!
It looks like you don't properly encase value in quotes, so it just renders the 'style='border-color:.
Let's assume that $_GET[$key] has a value of hello#hello.com. What your PHP & HTML renders is the following:
value=hello#hello.com
See the problem? There are no quotes. That's why the renderer goes forward searching for a valid value. To fix the issue you must add quotes around your $_GET[$key] in the fillin function. Something like this should do the job:
if (isset($_GET[$key])) echo "value='".$_GET[$key] . "'";
It works when ran alone because it reaches the end > and just assumes the value to be hello#hello.com
I have a profile page in which I want to display informations from the database for most users, and a form with the current data as default value for the users with modification rights.
if ($IDprofile == $_SESSION['userID'])
{
echo "<form method='post'>
Surname: <input type='text' required name='surname' maxlength=50
value=".htmlentities($user['Surname'])."><br>
Name: <input type='text' required name='name' maxlength=50
value=".htmlentities($user['Name'])."><br>
Birthdate (format YYYY-MM-DD): <input type='text' required name='BirthDate' value='";
if ($user['BirthDate'] != null)
echo $user['BirthDate'];
else
echo "-";
echo "'><br>
Description: <input type='text' maxlength=255 name='description' value='";
if ($user['Description'] != null)
echo htmlentities($user['Description']);
else
echo "-";
echo "'><br>
<input type='submit' value='OK'></form>";
}
As you can see, I tried with htmlentities, which should transform the apostrophe into ', but it doesn't work. Other methods like addslashes and addcslashes don't work either.
What is displayed is my form input with the value it should have, until the place where there should be an apostrophe, where it just ends. addslashes does the same, with a / before the end.
What puzzles me the most is that I have a surname with an apostrophe in it in my database, and this one is displayed just fine.
htmlentities by default only encodes " double quotes, because those are the more common terminators for HTML attributes. If you want it to encode ' single quotes too, you need to set the ENT_QUOTES flag:
htmlentities($foo, ENT_QUOTES | ENT_HTML401)
(ENT_HTML401 is the other default flag; these days you may want to use ENT_HTML5 instead.)
You should also actually delimit your attributes with quotes! Currently your result looks like value=James, which isn't incorrect, but will get you into trouble once your values contain spaces or, well, quotes or other special characters.
Please try outputting your variables like this:
htmlspecialchars($user['Surname'], ENT_QUOTES);
Also be sure to disable magic quotes in your system so you don't get any extra slashes automagically when posting new data.
Thanks again for the help with a similar question earlier. I have one more similar, but I think more complicated.
It looks like this in HTML:
<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById('WADADeleteRecordID').value=<?php echo($row_WADAactivities2['ActivityID']); ?>;document.getElementById('WADADeleteRecordName').innerHTML='<?php echo($row_WADAactivities2['Activity']); ?>';document.getElementById('deleteBox').style.display = 'block';document.getElementById('deleteMessage').style.display = 'table';" />
I get so far with it, but just get a bit lost, e.g.:
echo '<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById('WADADeleteRecordID').value=' . rawurlencode($row_WADAactivities2['ActivityID']) . ;document.getElementById('WADADeleteRecordName').innerHTML=' . rawurlencode($row_WADAactivities2['Activity']);';document.getElementById('deleteBox').style.display = 'block';document.getElementById('deleteMessage').style.display = 'table';" \"/>";
This is pretty much the last bit of something I've been looking at that needs tidying up.
Thanks again.
You need to escape all the single-quote characters that are inside the single-quoted string:
echo '<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById(\'WADADeleteRecordID\').value=' . rawurlencode($row_WADAactivities2['ActivityID']) . ;document.getElementById(\'WADADeleteRecordName\').innerHTML=' . rawurlencode($row_WADAactivities2['Activity']);';document.getElementById(\'deleteBox\').style.display = \'block\';document.getElementById(\'deleteMessage\').style.display = \'tabl\e';" \"/>";
I strongly recommend against writing such long strings of inline Javascript. Move it out into a Javascript function, and use onclick="functionName(...)".
See, you should always decide on whether or not its necessary to even echo something like this, or instead just use short tags like <?=$someVar?> directly in your view section of the code. Why? Because its much easier to deal with NOT escaping quotes :D Anyway, the way you should choose your quotes single or double, is if you're planning on NOT having any variables inside the string, use single quotes..if you're planning on using variables in the string use double quotes to avoid having to concatenate. Since you've used single quotes, you don't have to escape doubles, but you do have to escape other single quotes inside:
echo '<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById(\'WADADeleteRecordID\').value=' . rawurlencode($row_WADAactivities2['ActivityID']) .' ;document.getElementById(\'WADADeleteRecordName\').innerHTML=' . rawurlencode($row_WADAactivities2['Activity']).';document.getElementById(\'deleteBox\').style.display = \'block\';document.getElementById(\'deleteMessage\').style.display = \'table\';" />';
Morning,
I have created a small form to store some information to a database.
I have magic_quotes_gpc turned off on my server.
If i enter a " or a £ sign in the box is stores into the database without a worry.
When i echo it back with php it displays, but if i use the value in an input form field the " close the value field.
<input type="text" name="variable" value="<?php echo $row[variable]; ?>" />
I have now used htmlspecialchars around the input value and it works.
<input type="text" name="variable" value="<?php echo htmlspecialchars($row[variable]); ?>" />
But i have looked at open cart source as a reference and they do not use htmlspecialchars but store the data in a different way.
I tried using the urlencodes method they have used :
urlencode(html_entity_decode($_POST[variable],ENT_QUOTES, 'UTF-8'));
but this seems to store as a lot of numbers and + signs which did not display back correctly.
I would rather encode the update database instead of using the method i am with htmlspecialschars.
But not quite sure which way would be best?
Thank You
you may use
htmlentities() function in php
Perhaps try mysqli_real_escape_string($dblink, $string) instead of htmlspecialchars
For storing the HTML Character change the charters and then store them:
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>
To get back the correct HTML Character do the decoding as:
<?php
$str = "<p>this -> "</p>\n";
echo htmlspecialchars_decode($str);
// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>
For more information refer to http://www.php.net/manual/en/function.htmlspecialchars.php
I'm trying to pass a parameter from php into my javascript function inside html. Is this at all possible? This is what I've got so far, but it seems to crash once it hits the condition:
$str="<input type='submit' value='-' onclick='Call(".$row['field1'].");'/>";
I hope that I won't have to find a work around for this.
Thanks.
EDIT:
This is the function that I'm trying to call
function Call(stuff)
{
alert(stuff);
$.get('reports.php',
{'param':'section', 'text':stuff},
function(returned_data)
{
alert(returned_data);
});
//alert('end');
}
And this is the function that I'm populating a table with.
function PopTable()
{
alert('end');
document.getElementById('table').innerHTML = 'Loading...';
$.get('reports.php',
{'param':'getstuff'},
function(returned_data)
{
document.getElementById('table').innerHTML = returned_data; // Clear the select
});
alert('end');
}
This is the php that I'm sending back population the table:
$str.= '<tr>';
$str.='<td bgcolor="#ffffff">' . $row['stuff'] .'</td>';
$str.='<td><input type='submit' value='-' onclick="Call('$row['stuff']');"/></td>';
$str.='</tr>'; //accumulate table
I can't seem to get a return value for Call(), and the alert doesn't even pop up
Try:
$str='<input type="submit" value="-" onclick="Call(\''.$row['field1'].'\');"/>';
I would bet you need quotes around the value if it is a string value
For example if $row['field1'] = 'test'; then:
Your version: <input type='submit' value='-' onclick='Call(test);'/> which would fail because test is not a valid variable
My Version <input type="submit" value="-" onclick="Call('test');"/> which would work becase 'test' is a string
What you're trying to do is possible, whereas it is not possible to pass a parameter from JavaScript into a PHP function.
When you say it crashes once it hits the condition, do you mean when you click on the input on the page? In that case, it's an error in your JavaScript syntax. I would try using Firebug with Firefox to track down the issue.
My first guess is there are no quotation marks inside the Call() method. So you're doing this:
Call(something)
and it should be like this:
Call('something')
This is possible, but I would be very careful about mixing PHP echos and javascript inline with strings because you need to escape javascript datatypes properly
In your example, $row['field1'] is probably from a database, so it's a string, so you need to surround the value with quotes in your javascript call. But that's not all, because what if there's a quote in your string, or a special character like a newline which needs to be escaped in javascript? And then what about html escaping?
A better approach is to import your javascript values in one place using json_encode(), then use your variables from there.
E.g.:
<?php
$jsonrow = json_encode($row);
?>
<script type="text/javascript">
var jsrow = <?=htmlspecialchars($jsonrow);?>;
</script>
<?php // some time later... ?>
<input type="submit" value="-" onclick="Call(jsrow.field1);" />