Escaping strings

In my code I read items from a table and populate a form with x number of items using checkbox inputs. When the submit button is selected it submits the items_selected[] array with the items that were checked.

This all works. My problem is when the items read and displayed in the form contain a single quote. The array only returns the string up to the quote in the string. I’m assuming I’ll have the same problem with any of the characters that need to be “escaped” but I can’t seem to figure out how to do it.

Any help would be appreciated.

Below is a somewhat stripped down version of the code

<form action="" method="post">
	<?php foreach ($items as $item): ?>
		<label class="cbcontainer">
			<?php echo "<input type='checkbox' name='items_selected[]' value='{$item['item_name']}' >" 
			. ' <b>' . $item['item_name'] . ')'; ?>
			<span class="cbcheckmark"></span>
		</label>
	<?php endforeach ?>
	<?php if($formSubmitBtn === false): ?>
		<div style="margin: 0px 210px 20px; text-align:left;">
			<button type="submit" name="updateVotesBtn" class="btn btn-primary">Submit</button>
		</div>
		<?php $formSubmitBtn = true; ?>		
	<?php endif ?>
</form>

<?php

/*
If the form was populated with

This is an entry
This is entry can't be passed properly
This is another entry

 The items post array looks like the following:
Array
(
    [items_selected] => Array
        (
            [0] => This is an entry
            [1] => This is entry can --***** HERE'S the problem ***
            [2] => This is another entry
        )

    [updateVotesBtn] => 
)
*/

Hello @oldgoat99, or if it is acceptable: Gordon,

have you tried using the backslash to escape the quotes?

<form action="" method="post">
	<?php foreach ($items as $item): ?>
		<label class="cbcontainer">
			<?php echo "<input type=\"checkbox\" name=\"items_selected[]\" value=\"{" . $item['item_name'] ."}\" >" 
			. ' <b>' . $item['item_name'] . ')'; ?>
			<span class="cbcheckmark"></span>
		</label>
	<?php endforeach ?>
	<?php if($formSubmitBtn === false): ?>
		<div style="margin: 0px 210px 20px; text-align:left;">
			<button type="submit" name="updateVotesBtn" class="btn btn-primary">Submit</button>
		</div>
		<?php $formSubmitBtn = true; ?>		
	<?php endif ?>
</form>

i suspect that you have a problem with this line:

<?php echo "<input type='checkbox' name='items_selected[]' value='{$item['item_name']}' >"

i assume that you want the output from $item[‘item_name’], thus:

<?php echo "<input type=\"checkbox\" name=\"items_selected[]\" value=\"{" . $item['item_name'] ."}\" >"

Maybe this solves your problem?

<?php echo "<input type='checkbox' name='items_selected[]' value='{$item['item_name']}' >" 
. ' <b>' . $item['item_name'] . ')'; ?>

I’d suggest changing this line to

<input type='checkbox' name='items_selected[]' value='<?= $item['item_name'] ?>'>
<b><?= $item['item_name'] ?></b>

Echoing HTML will pretty much always make your life miserable.

Ok, progress.:grinning:
The following seems to work until The text in the line changes from

This is entry can’t be passed properly
to
This entry “cannot” be passed properly

Then it’s broke again. Is there not some function that handles escaped characters in a string string properly? The problem is there will be users entering random stuff from the keyboard and they should be able to enter text and have it come back and be displayed as it was entered.

I have one table that has the “string” entries made by a user and it seems it would be highly unusual to put restrictions on <,>,",’,etc. Those entries are put in the table without any modification. That table is read and output to the screen and then the checked items are sent to the post to be put in another table.
So just handling the single quote is only part of the problem.

Your items should have an id (auto-increment integer column if defined in database) and you should use the id as the value attribute for your checkboxes. You must validate all external data before using it, and an integer is easier to validate and if storing the submitted values, you should store the id, not the name.

To prevent html/css/javascrpt in dynamic values from being rendered and breaking your web page, apply htmlentities() to the value when you output it onto a web page. This will also help prevent cross site scripting.

1 Like

Ah, this sounds like what I’m looking for. I’ll have to do some digging and see what I can find out.

Thanks.

I assumed that you wanted to keep your code as is except escaping quotes (from the post title.) I agree with Jim about echo html code with escape codes. Escaping makes code very difficult to follow, thus, errors are easily overlooked. Try it this way if if you want to do so:

<form action="" method="post">
	<?php foreach ($items as $item): ?>
		<label class="cbcontainer">
			<input type="checkbox" name="items_selected[]" value="{<?php echo htmlentities($item['item_name'], ENT_QUOTES, "UTF-8"); ?>}" /> 
			<b><?php echo htmlentities($item['item_name'], ENT_QUOTES, "UTF-8"); ?></b>
			<span class="cbcheckmark"></span>
		</label>
	<?php endforeach ?>
	<?php if($formSubmitBtn === false): ?>
		<div style="margin: 0px 210px 20px; text-align:left;">
			<button type="submit" name="updateVotesBtn" class="btn btn-primary">Submit</button>
		</div>
		<?php $formSubmitBtn = true; ?>		
	<?php endif ?>
</form>

https://www.php.net/manual/en/function.htmlentities.php

Thanks, I’ll try that today.

let us know how it goes. I understand what you are saying in the original post and i see it in action. You have single quotes being read by php as code. Hence, the concept of concatenating the code with a string. Better yet, we output the code within html and since it i output from a db, then we have to clean the output. Especially because you are including essentially untrustworthy data directly into an html attribute. This is dangerous, so you need to sanitize the output.

I finally got back to working on my project after a several day priority interrupt.

That last bit of code you posted worked. It seems to be working. I had a few problems when adding back in other gode I had stripped out but got it resolved in a couple hours.

As far as injecting untrustworthy code goes, there are no inputs on this screen; only checkbox inputs with the info obtained from the db. Then when the checkboxes are submitted the db update takes place in another protected file and it has the data protected from injection (i think).:thinking:

Thank you!!

1 Like

I’m happy that you made it work :slight_smile: Good job, Gordon.

htmlentities: protecting output is just good practice simply because any existing weakness could be exploited by a different weakness. Crossing Ts and dotting Is.

I hope that you have a pleasant evening.
Let us know if something isn’t working as expected.

Good you got this working. I came late to the picture. Will suggest you look at the method below. It eliminates multiple php tags.

<?php
    echo '<form action="" method="post">';
    foreach ($items as $item) {
	    echo '<label class="cbcontainer">
			<input type="checkbox" name=' .$items_selected[]. 'value=' .$item["item_name"]. '> . <b>' .$item["item_name"]. '</b><span class="cbcheckmark"> </span></label>';
    }

    if($formSubmitBtn === false) {
	    echo '<div style="margin: 0px 210px 20px; text-align:left;"><button type="submit" name="updateVotesBtn" class="btn btn-primary">Submit</button></div>';

	    $formSubmitBtn = true;
	    echo '</form>';
    }
?>

Note that I replaced a bracket with </br> as there is no open bracket.
Note that I don’t understand why you have $formSubmitBtn = true
Will the form be submitted once the page is loaded? If yes, you did not include the recipient file.
A good method to echo out the content of a table is to use the associative array with the while loop method.
Also, you need to have a separate css file for your styles. Do not include any css sytle in an html or php file. It slows down page rendering. get use this now. This is the new practise

just a note about concatenation: concatenation is simple and easy to use but it can become a bad habit very quickly when you try to move into security related code. It is better to separate html from PHP and vice versa. <?php code; ?> separates the two languages.

Concatenation as a nasty security risk: hash_hmac('sha3-256', $Key . $tt . $page);

I find it best to avoid concatenation practices in order to avoid making a critical error with anything security related.

John,
Regarding string concatenation. After researching from your comment I now know there are other ways to concatenate strings that are better than “$str1 . $str2 . $str3” by using sprintf() or {}s. sprintf()? Who knew you could just write php in “c”? Anyway I don’t see any way to put stuff together in the way it needs to be presented in the case of a checkbox array without concatenating. I’m sure there’s probably a way.

Olu,
I may go back and look at my code in a couple weeks and see if I can change it to look like what you suggested. That looks like what I think the code should look like. I did make a few changes per your suggestions. I do have a css file and moved to style over to it.

The only thing I can say is that in my past life I was a self taught programmer and have experience in many languages. My only experience with php has been with getting a php email app working on my otherwise strictly HTML sites. Without a doubt php has been the mos difficult language for me to wrap my head around and especially having to deal with all the ways bad actors can mess with php sites.

For now I’m going to go to another part of the project and I’m pretty sure I’d be tearing my hair out (if I had any) over the next problem and you will be hearing from me.

For now this is what I have
This part of the project was to have a user be able to log in and make their voting choices and then when they came back later and logged in, those choices would be displayed and they could change their votes if they wanted. Getting the info to be displayed in the checkbox array properly was giving me fits.

Again, thank you guys so much,

Gordon

Video of the code working…

The code if anyone is interested…

Hello Gordon, i wasn’t referring to your code and the use of concatenation. In fact, my first example for you was done with concatenation. I was saying that using <?php echo $x; ?> makes it easier to see the PHP within the html but it also creates problems where we often forget to terminate the statement. For example, in your linked text file you are missing a terminator:

<input type="checkbox" name="dances_selected[]" <?php echo $isChecked ?>

should be:

<input type="checkbox" name="dances_selected[]" <?php echo $isChecked; ?>

I just want to clarify that concatenation can be a danger when your dealing with certain aspects of PHP. I suggest to avoid concatenating everything just because we have the power to do so. Concatenation may seem like a better idea but it may be a bad idea in certain circumstances. Just be wary.

nice video :slight_smile:

There is nothing wrong with leaving the simi-colon off in this instance.
Per the Manual:

The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.

https://www.php.net/manual/en/language.basic-syntax.instruction-separation.php

1 Like

yes, i forgot about this, Benanamen. I’ve always found PHP to be sloppy and careless, like not having to declare variable data types, not having to terminate, able to use short tags, mixing C, C++, Perl, Java and ASP code. I used to hate PHP years ago. Not many options other than Python. Anyway, thanks for reminding me.

Ok, I see what you mean.
:+1:

Sponsor our Newsletter | Privacy Policy | Terms of Service