Basically I'm developing a (very) simple search engine. You can enter a search term and you are taken to the results page - which works fine. However on the results page, I have a button that will take you to the next 10 results: where $term is the $_POST['term'] value.
echo "<input type='hidden' name='term' value='" . $term . "'>";
This causes the following problem with the term is for example "aidan's".
When the next 10 button is clicked, the term becomes aidan\ and no further results are found.
I am not doing anything to $term.
I usually use Java, but am required to use PHP for this uni assignment!
Any help would be greatly appreciated.
It could be your PHP that escapes your data, check out http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc and / or http://php.net/manual/en/function.addslashes.php these should help you to identify the porblem
Try looking after addslashes() et stripslashes()
http://php.net/manual/en/function.addslashes.php
Regarding your issue, I think you should try to add something like this :
$search = stripslashes($_POST['term']);
If you use double quotes, you don't have to break your string when using a variable. You can also use various options, such as those mentioned already or htmlentities() or urlencode(). I would use the later, just cuz. So you would end up with:
$term = urlencode($term);
echo "<input type='hidden' name='term' value=\"$term\">";
You need to htmlspecialchars() every single bit of data you output to your page. A set-up like yours is the reason that so many XSS vulnerabilities exist around the world, and you should not contribute to them.
echo "<input type='hidden' name='term' value='" . htmlspecialchars($term) . "'>";
Once you have that, you will need no obscure addslashes/quote escaping/whatever anymore.
To make that easier throughout your code, define
function h($s) { htmlspecialchars($s); }
echo "<input type='hidden' name='term' value='" . h($term) . "'>";
The function you are looking for is htmlspecialchars(). However to make it work, you must use quotation marks to wrap the parameter.
Plus, if there are slashes involved, the stripslashes() function may be needed.
So:
$term = htmlspecialchars( stripslashes( $term ) );
echo '<input type="text" name="term" value="' . $term . '" >';
Always use GET method for the search, not POST.
Either turn magic quotes off or strip slashes manually
Use htmllspecialchars with ENT_QUOTES parameter to encode form's field value.
Consider to print out HTML as is, not using PHP echo, to get rid of all this quotes craze
Most important part. If you quote your term for the database search, don't use quoted variable in your form.
so
if (isset($_GET['term'])) {
if (get_magic_quotes_gpc()) $_GET['term'] = stripslashes($_GET['term']);
//$term=mysql_real_escape_string($_GET['term']);
//perform search here.
//
$term = htmlspecialchars($_GET['term'],ENT_QUOTES); //from $_GET again
?>
<input type="hidden" name="term" value="<?php echo $term?>">
<?
}
I think the easiest way is not to put $term as a hidden field at all. For pagination, you can keep memory of the searched term in the session.
Related
Is it possible to add a value to a dynamically created input field?
Im trying something like this: echo "<input value="$row['test']">" but that gives me a syntax error. It has to be in my php file since im calling it via ajax and want to keep my html and php seperate.
Im getting content via ajax and I need to set many field names as there are records in the database.
You can do it like this:
echo '<input value="' . $row['test'] . '">';
Alternatively escape the " (not recommended if not needed, because it is hardly readable):
echo "<input value=\"" . $row['test'] . "\">";
Otherwise you’re mixing quotation marks, which is a syntax error. The . is to combine strings with variables (in this case).
You can also Use:
<input value="<?php echo htmlspecialchars($row['test']); ?>" >
OR
echo "<input name='test' value=".$row['test'].">";
OR
echo "<input name='fred' value='{$row['test']}'>";
Reference
When using certain php values within a quoted string, such as the array syntax in the question, you should either escape from the quotes or encapsulate the variable in curly braces. Also, as the string was quoted with double quotes you should use single quotes around attributes and values.
echo "<input name='fred' value='{$row['test']}'>";
<input type="text" name="post_title" class="form-control" value="<?php
if(isset($post_title))echo $post_title;
?>">
If you want to add it into the HTML
I have to store some Wikipedia URLs into a MariaDB database.
It happens that some URLs contain quotes, like this one:
https://en.wikipedia.org/wiki/%22Heroes%22
so I use urlencode() to store them as "en.wikipedia.org%2Fwiki%2F%22Heroes%22".
If I urldecode() the URL, to show it inside an <input type="text"> field without all the % (they scare unskilled users), the quotes break the input value.
I found this workaround to show the result in a more comfortable way:
$url = 'en.wikipedia.org%2Fwiki%2F%22Heroes%22'; // it comes in this way from the DB
$tmp = str_replace('%22','"', $url);
$url_input = urldecode($tmp);
echo "<input type=\"text\" value=\"$url_input\" />";
The value of $url_input works smoothly as a <a href anchor, and the query coming from the form is then filtered with FILTER_SANITIZE_URL and urlencode() to store it in the DB.
Is there a better way to do this?
Just use htmlspecialchars() instead of str_replace()
$url = 'en.wikipedia.org%2Fwiki%2F%22Heroes%22'; // it comes in this way from the DB
//$tmp = str_replace('%22','"', $url);
$url_input = htmlspecialchars(urldecode($url));
echo "<input type=\"text\" value=\"$url_input\" />";
I think it will work better than this
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\';" />';
suddenly my site show new warning -
The relevant code:
printf ("<input type='text' name='C_Comment' value='" . $myComment . "' >");
The warning I get:
Warning: printf() function.printf: Too few arguments
probably because $myComment is null.
I know I Can fix it if I first test if the value is null, and only then conctenate it. but is there a simpler way?
Why did not I get this warning before?
Thanks,
Atara
EDIT: sorry, wrong title. The problem was that $myComment was not NULL, it contained special character.
No, you get that warning because you don't give enough arguments to printf; probably $myComment contained printf placeholders like %s.
Use echo instead if you don't want to use printf's formatting. You can also rewrite your printf call:
printf ("<input type='text' name='C_Comment' value='%s'>",
$myComment);
Make sure you've escaped special chars in $myComment (see htmlspecialchars).
Instead of using printf just use echo:
echo "<input type='text' name='C_Comment' value='" . $myComment . "' >";
printf is a function used for formatting a string with given values. You have only supplied one argument to the function, so it is throwing that error in your face.
If you simply wish to print the text on the page, use echo (or just remove the f and use print) with the current string. Or you can do this:
printf("<input type='text' name='C_Comment' value='%s' />", $my_comment);
Here's the PHP.net Docs page for printf(), and you can also view related functions in the See Also section.
Add this before the prinf call if you have a default value (which is not empty):
$myComment = ($myComment == null) ? 'yourdefaultvalue' : $myComment;
Of course, an echo would do fine also (and than an empty value is no issue anymore):
<input type="text" name="C_Comment" value="<?=myComment?>" />
What I have is this:
function add_email_form () {
echo "<form class=\"email-me-form\" id=\"initialize\" action=\"<?php echo $_SERVER[PHP_SELF] ?>\" method=\"post\" name=\"contact_me\">\n";
}
How do I make this syntactically correct?
Don't use double quotes unless you need to. Use single quotes, '. That way, you don't have to escape anything except control characters like the \n, and in that case, do drop to double quotes. So the above would be:
echo '<form class="email-me-form" id="intialize" action="'.$_SERVER['PHP_SELF'].'"
method="post" name="contact_me">'."\n";
(newline added to I don't cause a horizontal scrollbar)
You don't need to do htmlspecialchars() looks like what you want.
You don't need to (and in fact, cannot) call "<?php echo?>" inside a PHP statement. Only when you're outside of PHP does that work. In this case, just concatenate with ..
And as stated in the comments, you should quote array keys when they're strings, as otherwise PHP will throw a warning and could potentially be confused.
Something like so:
echo "<form class=\"email-me-form\" id=\"initialize\" action=\"",
htmlspecialchars($_SERVER['PHP_SELF']),
"\" method=\"post\" name=\"contact_me\">\n";
function add_email_form () {
echo "<form class=\"email-me-form\" id=\"initialize\" action=\"" . $_SERVER[PHP_SELF] . "\" method=\"post\" name=\"contact_me\">\n";
}