How would this argument be properly escaped in PHP? - 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

Related

PHP /MySQL update form from within results

I've got a search function written in PHP/MySQL which works fine. What I want to happen is that when a user produces a search they can click a button which will submit the $id from the output to a table in my database.
I've copied my code below, the error is within the php echo in the form, it just displays the plain text of the php code.
Everything else works fine, I've tested this by setting value to "" and entering the id myself and then it works. I want it though to be a hidden input in future where the id automatically comes through from the search result. Multiple searches can be returned on the same page and this form is underneath each individual search result.
<?php
$conn = mysqli_connect("localhost","root","","users");
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM users WHERE main LIKE '%".$search."%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$id = $row ['id'];
$main = $row ['main'];
$postcode = $row ['postcode'];
$available = $row ['available'];
$email = $row ['email'];
$output .='<div><br><b>Player ID: </b>'.$id.'<br><b>Main:
</b>'.$main.'<br><b>Postcode: </b>'.$postcode.'<br><b>Available:
</b>'.$available.'<br>
<br>
<form action="request_player.php" action="post">
<input type="text" name="id" value="<?php echo $id ?>">
<input type="submit" value="Request Player">
</form>
</div>';
}
}
}
echo $output;
?>
<br> Back to your account
The issue Jay Blanchard highlighted and which you took a bit lightly - perhaps b/c you fear the distraction from your current problem - is actually pretty related to the issue you highlight in your question.
This btw. is nothing uncommon. In this little script you deal with at three languages: HTML, SQL and PHP. And all these are intermixed. It can happen that things jumble.
There are methods to prevent these little mistakes. What Jay highlighted was about how to encode a SQL query correctly.
The other problem is to encode a HTML string correctly. Let me highlight the part:
$output = '... <input type="text" name="id" value="<?php echo $id ?>"> ...';
In this PHP string you write "<?php echo $id ?>" verbatim, that means, this will echo'ed out then.
What you most likely meant was to write it this way:
$output = '... <input type="text" name="id" value="' . $id . '"> ...';
So this seems easy to fix. However, it's important that whether it is SQL or HTML, you need to properly encode the values if you want to use them as SQL or HTML. In the HTML case, you must ensure that the ID is properly encoded as a HTML attribute value. In PHP there is a handy function for that:
$output = '... <input type="text" name="id" value="' . htmlspecialchars($id) . '"> ...';
Or as the ID is numeric:
$output = '... <input type="text" name="id" value="' . intval($id) . '"> ...';
works similarly well.
You need to treat all user-data, that is all input - which includes what you get back from the database (!) - needs to be treated when you pass it into a different language, be it HTML, SQL or Javascript.
For the SQL Jay has linked you a good resource, for the HTML I don't have a good one at hand but it requires your own thoughtfulness and the will to learn about what you do (write) there. So sharpen your senses and imagine for each operation what happens there and how this all belongs together.
One way to keep things more apart and therefore help to concentrate on the job is to first collect all the data you want to output and then process these variables in a template for the output. That would prevent you to create large strings only to echo them later. PHP echoes automatically and a benefit of PHP is that you can use it easily for templating.
Another way is to first process the form input - again into your own variable structure - which is the programs input part and run first. Then follows the processing of the input data, in your case running and processing the database query. And after that you care about the presentation. That way you have common steps you can become more fluent in.
I hope this is understandable. It's full of further obstacles, but it pays to divide and conquer these programming problems. It will also help you to write more while you need to write less for that.
And btw., you don't need to switch to PDO, you can stick with Mysqli.
The reason it is happening is because you have put <?php echo $id ?> inside a string. You want to do the same thing you did elsewhere in your example: value="' . $id . '" It can quickly get confusing when you have single and double quotes happening together. You might be best off learning how to use PHPs multiline strings.
Also, <?= $id ?> is a useful shorthand for <?php echo $id ?> (although you don't want to use either here)

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

Insert words with newline character from function input to Javascript

I have a condition below.
pop function in button input has line 1 followed by newline Line2.
When I click on button to javascript it pops error " Unexpected token ILLEGAL " in Console.
Value inside pop() of button is generated dynamically. I get this error only if I have a new line char in the input text.
<script type='text/javascript'>
function pop(valu)
{
alert("here"+valu);
document.getElementById('box').innnerHTML = valu;
}
</script>
<button onclick="pop('Line 1
Line 2')"> Click </button>
<textarea id='box'></textarea>
Backend is PHP.
Is there any way to achieve this on foreground ? or should I make any changes of inserting values to DB ?
I directly store the values in DB with newline character.
Solution is use to nl2br function in PHP side
nl2br($yournewlinestring);
function of PHP to convert newline to enter a new line for \n
But before storing convert your html line breaks in php like this
$_POST['xyz'] = preg_replace('/(?:\r\n|[\r\n])/', PHP_EOL, $_POST['xyz'] );
If you want the newline characters, just do something like:
<?php $pop_variable = str_replace("\n", '\n', $pop_variable); ?>
<button onclick='pop("<?php echo htmlentities($pop_variable, ENT_QUOTES) ?>")' />
Remember to also run htmlentities to escape the quotes.
I do think this is doing too much in HTML, though. It might be more beneficial to store this in a PHP array and then json_encode() it. That way you don't have to do the above or take into account what happens when a " or ' is in the $pop_variable and might also be expandable if you wanted to add more buttons (of course, this depends on your use case).
Example:
<script>
function pop(valu) {
// Should do some error checking to ensure pop_var is set
document.getElementById('box').innnerHTML = pop_var[valu];
}
var pop_var = <?php echo json_encode(['button1' => "Line 1\nLine2", 'button1' => "Another Line 1\nAnother line with ' single quotes..."]);
</script>
<button onclick="pop('button1')">Click</button>
<button onclick="pop('button2')">Click</button>
<textarea id='box'></textarea>

Passing a Value from PHP to Javascript Variable

I've seen numerous posts on how to do this either saying to use rawurlencode in the php and decodeURIComponent in javascript or just use json_encode. Neither work for me. Hoping someone can see what I'm doing wrong:
I have an html button like this:
<button id="editbutton" onClick='edit(this, "<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>", "<?php echo $result_cameras[$i]["camera_type"]; ?>", "<?php echo rawurlencode($result_cameras[$i]["camera_name"]); ?>")'>Edit</button>
I pass that into the javascript edit button:
var edit = function(t, to, cameratype, cameraname, cameraquality, camerahash, camerastatus, emailnotice, camerasensitivity, axisuser, axispass, axisip, axisport)
{
if (mydiv.find("form").length) {
mydiv.show();
} else {
// fields
var $myform = $("<form id='EditCameraForm' name='' method='post' action='" + to + "'></form>");
var $myfieldset = $("<fieldset><legend>Edit camera settings</legend></fieldset>");
var $myinput = $('<input/>').attr('type','hidden').attr('name','camera_type').val(cameratype);
var $mylabel = $("<label for='CameraName'>Camera name: </label>");
var $myinput2 = js('<input/>').attr('size','25').attr('name','camera_name').attr('id','CameraName').val(decodeURIComponent(cameraname));
$myform.append($myinput, $mylabel, $myinput2);
...
}
...
}
I've tried using rawurlencode/decodeURIComponent as above and when I hit the edit button if the camera name is called: a"a (just testing the quotes) I get a"a. Backslashes such as a\b just returns some weird characters back.
If I try:
<?php echo json_encode($result_cameras[$i]["camera_name"]); ?>
and don't put anything in the javascript code I get this error:
missing ) after argument list
edit(this, "/dashboard", "WEBCAM", ""a"a"", "0", "3dd10c49784e2207de1e1932958bfb...
Where it is pointing to the ""a"a"".
Any suggestions?
You are in effect outputting a javascript string literal, so using htmlentities is not the correct thing to do. What you need instead is addslashes:
<?php echo addslashes($_SERVER['REQUEST_URI']); ?>
Edit: It goes without saying that you also need to do this for the other two strings you are echoing.
The reason this is correct is that the escape sequences for Javascript string literals are compatible with what addslashes does, if you ignore the fact that addslashes also escapes the "null" character. However, there's no way that character will be part of your URL so there is a perfect match between what addslashes does and what Javascript expects from its string literals.
For completeness I should mention that an appropriate usage of htmlentities is to process text that is being sent as part of HTML content; even then, htmlspecialchars (which performs a small subset of the work of htmlentities) is almost always the better fit.
rawurlencode() is for converting a string to an URL argument
htmlentities() is for converting a string to an HTML content
If you'd like to convert a string to a Javascript string it should be :
function f_str_2js($x) {
return str_replace( array("\n","\r","\t","'",'"') , array('\n','\r','\t',"\\'",'\"') , $x)
}
the above answers are correct, but you should consider to add your data to a php array or object, than jsonencode and add it to a date-attribute date-camera='{... than do eventbinding by using jQuery .on(.
This way you can access the data via $(this).data('camera'). It will be easy to extend you app without adding more and more parameters to the onclick-function.
for more information see:
http://api.jquery.com/jQuery.data/
http://api.jquery.com/on/

Can't generate Javascript from data with parentheses

I'm using a PHP/MySQL connection to add a search suggestions feature to my site. It's all working except for one piece. My data all contains parentheses in the values, so when I'm trying to pass the returned data to the input field my onclick function fails! code is as follows:
while ($result = $query->fetch_object()) {
echo '</li><li onclick="fill(\''.$result->name.'\');">'.$result->name.'</li>';
}
The list populates from the returned search results, but the query returned looks like this:
</li><li onclick="fill('Boire Field, Nashua, NH, US (KASH)');">
Boire Field, Nashua, NH, US (KASH)</li>
Firebug gives me the following:
unterminated string literal
fill('Boire Field, Nashua, NH, US (KASH)
The ) in the result is prematurely ending the string. How can I escape this out so it will properly call the function?
As the Brad Suggests.. The best way is JSON_ENCODE
while ($result = $query->fetch_object()) {
echo '</li><li onclick="fill(\''.json_encode($result->name).'\');">'.$result->name.'</li>';
}

Categories