input field showing an URL with quotes - php

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

Related

ajax jquery passing string as a parameter in onclick event jquery

echo "<button onClick='follow(".$name.");'></button>";
I need to pass a string as a parameter in follow(user) function onClick event jquery. But it's getting called as a value.
I tried kind of everything, but in php it looks a bit of a big deal for me. Is there any other way around to get the expected result as a string from a php variable.
You echo a php variable in javascript without adding quotes thus ending with a javascript variable name instead of a string.
Just add escaped quotes like this:
echo "<button onClick='follow(\"".$name."\");'></button>";
Quotes are off and if you're passing a string you need quotes wrapping the string in the function call.
There is various ways to do it, for standard " in html properties:
echo '<button onClick="follow(\''.$name.'\')"></button>';
echo "<button onClick=\"follow('".$name."')\"></button>";
echo "<button onClick=\"follow('$name')\"></button>";
for single quotes
echo '<button onClick=\'follow("'.$name.'")\'></button>';
echo "<button onClick='follow(\"".$name."\")'></button>";
echo "<button onClick='follow(\"$name\")'></button>";
But that's presuming your users are nice, a crafty user may create a username with \n in it, then from POSTing to storing and retrieving it would most likely be rendered as a new line:
<?php
$name = "Foo\nBar";
echo '<button onClick="follow(\''.$name.'\')"></button>';
Rendering the following which would cause the page to break:
<button onClick="follow('Foo
Bar')"></button>
Or worse a username like:
$name = "Foo')\"></button>\n<button onClick=\"window.location.href = ('http://example.com";
Which would render a stored XSS:
<button onClick="follow('Foo')"></button>
<button onClick="window.location.href = ('http://example.com')"></button>
So a better solution then to directly pass it in, would be to escape it, using htmlentities and json_encode so \n is not rendered by the html.
echo '<button onClick=\'follow('.json_encode(htmlentities($name, ENT_QUOTES, 'UTF-8')).')\'></button>';
Which would render to:
<button onClick='follow("Foo')"><\/button>\n<button onClick="window.location.href = ('http:\/\/example.com")'></button>
Though you should be validating usernames on create before allowing such an attack.

Can not display double quotes when saving to database

I am saving double quotes that need to be saved in the database, then later shown on the screen.
$in = '2" to 2.33"';
$in = mysqli_real_escape_string($db, $in);
echo $in; // Shows with backslashes
$results = $db->query("UPDATE store_item_brims SET BrimSizeIn='$in' WHERE ID=2");
// Later I query the database and load to an array
// print_r of the array shows with no backslashes
// echoing into text input field does not work
When I view the data in PHPMyAdmin, it saves in the database without any visible backslashes. When I load the data to an array and print_r the array, it is shown in the array. However, when I try to echo it out in an input text field for the user to update, it only shows 2 and cuts off as soon as the first double quote is reached.
How do I fix this?
when you echo it in to a HTML input the quotes mess up the quotes the HTML input uses as deliminators so short answer:
<input type="text" value="<?php echo htmlentities($YOUR_VALUE); ?>" ...
reference: htmlentities

php echo outputs only part of a variable in a form

I'm loading a variable from a database like:
$adres = $row['adres']; //(= "Hoge Filterweg")
Then using it in a echo like:
echo input type='text' name='adres' value='{$adres}'
It displays on the form only the first part of the adress ( "Hoge"), but not the whole adress.
What could I do now?
Single quotes surrounding the inline variable like value='{$adres}' dit the trick.
thanks
You need double quotes to pass params with space.
This code should help you:
echo "<input type=\"text\" name=\"adres\" value=\"{$adres}\" />"

How would this argument be properly escaped in PHP?

My site has some PHP generated content which echoes HTML elements. Some of these elements are responsive to javascript events...for one input element, the relevant event is onmouseout, but I can't seem to escape this properly.
$sql = mysqli_query($cxn, "SELECT stuff1, stuff2, stuff100, tags FROM myTable WHERE user_id = 'myID'");
while ($row = mysqli_fetch_assoc($sql)) {
$Tagstring = $row['tags'];
//lots of code
echo "<div class='myClass1 myClass2'>
<input type='text' name='myInput' value='".$Tagstring."' onmouseout='ajaxFunction(\"myString\", this.value.trim().replace(/,\s|\s,/g, ","))'>
</div>";
//more code
}
$Tagstring is a comma-separated string of text substrings. If a user edits his/her tags, I am trying to prevent the following:
$Tagstring = 'tag1,tag2'; //from database table
//User edits to 'tag1, tag2';
//Pointless ajax call and access of server, since if user input = original $Tagstring, this will return false as I have set up the ajax call, but if user input !== $Tagstring, then ajax function proceeds
I am not new to PHP and Javascript, so I know in PHP about str_replace or exploding the user input on "," and then trimming each member of the explode array. Alternatively, I could use Javascript to split on "," and then trim the pieces in a for loop (or something similar).
Can anyone tell me how to properly escape the following argument in my echoed function call?
this.value.trim().replace(/,\s|\s,/g, ",")
I tend to echo my output opposite of the way you have done it, which I feel is easier to control. Single quotes on the outside, and double quotes on the inside.
echo '<div class="myClass1 myClass2">
<input type="text" name="myInput" value="'.$TagString.'" onmouseout="ajaxFunction("myString", this.value.trim().replace(/,\s|\s,/g, ""))">
</div>';
What is the error you are seeing?
Fixed it...it seemed to be an escaping issue. This worked :
onmouseout='ajaxFunction(\"AStringNotAVariable\", this.value.trim().replace(/,\s|\s,/g, \",\"))'
whereas
//.replace(/,\s|\s,/g, ",") and .replace(/,\s|\s,/g, ',') and .replace(/,\s|\s,/g, \',\')
led to errors such as Uncaught SyntaxError: Unexpected token ILLEGAL

Problem passing strings with PHP post

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.

Categories