Escape string with PHP and HTML - php

I have these two lines that I would like to escape the $type variable:
$functionName = str_replace('-', '_', $type);
$output .= '<div class="tab-pane" id="'. $type .'">';
I tried escaping like below but its confusing me and not sure whether thats right:
$output .= '<div class="tab-pane" id="\'. $type .'\">';

Example 1: Variable between single quotes
If you use single quotes everything between them will always be treated as part of the string.
$output .= '<div class="tab-pane" id="' . $type . '">";
Example 2: Variable between double quotes (option 1)
If you have a variable that you want to pass in a string you can just put it in there if you use double quotes and de variable is nog 'touching' the other words. It should always have spaces.
$output .= "<p>i would like to $your_text_here with you.</p>";
Example 3: Escaping quotes in a string
Escaping characters in a string can be done by using a \ (backslash) before the character you want to escape.
$output .= "<div class=\"tab-pane\" id=\"example-id\">";
Example 4: Variable between double quotes without spaces next to it
You can place your variable between {} braces if you use double quotes (option 2)
$output .= "<div class=\"tab-pane\" id=\"{$type}\">";
This question was however already answered in Mixing PHP variable with string literal

Your first block is doing string replacements, but then you use the ORIGINAL string, not the replaced one:
$output .= '<div class="tab-pane" id="' . $functionName . '">';
would be more correct. On the second one, you're escaping the ' quotes, which means that you never terminate the string, meaning that the . $type . portion is treated as plaintext within the string, not a PHP concatenation operation. Try
$output .= '<div class="tab-pane" id="' . $type . '">';
instead. note the LACK of backslash escapes.
And of course, you could use a HEREDOC, eliminating any need to escape quotes entirely:
$output .= <<<EOL
<div class="tab-pane" id="{$functioName}">
EOL;

In this case, you don't need to escape at all. You only escape within the same type of quotes. You don't escape double inside single or single inside double.
So with 'o'reilly' you would escape like 'o\'reily'. But with "o'reilly" you'd just keep it as "o'reilly". But with "He said "hello"" you'd escape "He said \"hello\"". Yet, with 'He said "hello"' you would not escape at all.
But if your $type variable can contain double quotes, you will need to consider that to prevent your HTML from being broken in that case. How you would handle the quotes inside the variable $type would be by replacing the " with its HTML entity equivalent:
$output .= '<div class="tab-pane" id="' . str_replace('"', '"', $type) . '">';
Or use htmlentities() which will do the same replace as well as others.
Note, its the double quotes inside the variable you would want to handle, not to escape the single quotes outside. Because presumably the issue is that if the variable contained double quotes it would break your HTML since you are using double quotes around the value for id:
i.e. id="contents_of_type_variable"
If you had id="contents"_of_type_variable" your HTML would be broken.
So you change that to id="contents"_of_type_variable"
If you're trying to escape something else, it is due to a misunderstanding.

Related

Inserting variable into img url with echo

$playername = $_GET["playername"];
echo '<img src="https://cravatar.eu/head/SecretAgent5555"/>';
I need what SecretAgent5555 is to be $playername, plz help/
This will do what you need...
echo '<img src="https://cravatar.eu/head/' . $playername . '"/>';
This uses the PHP . string concatenation feature to 'insert' $playername into the img src tag.
You can also use string interpolation by using double quotes, but it requires you to escape the double quotes within, like this.
echo "<img src=\"https://cravatar.eu/head/$playername\"/>";
Because you have opened the string being echoed with the double quotes, to put a double quote within, you need to escape them. This is the \" part within the string.

PHP OB_START which double quotes

i'm using php on_start and ob_get_contents to echo html and store in a variable. However when I json encode and check the output it doesn't output the entire string. Could anyone help point out what I'm doing wrong
ob_start();
echo'<img src=\"images/editphotohover.png\"/>\"';
$photo = ob_get_contents();
ob_end_clean();
I get only get the ending anchor tag
in the json encode output
There is no need to escape double quotes here
echo'<a href=\"javascri...
just write this:
echo'<a href="javascri...
Double quotes are kept while in single quotes!
Additionally, note that escaping within single quotes has no effect:
"\t" renders as a TABULATOR character
'\t' renders as \t
The PHP documentation states this:
To specify a literal single quote, escape it with a backslash (\).
To specify a literal backslash before a single quote, or at the end of the string, double it (\\).
Note that attempting to escape any other character will print the backslash too.
Therefore, how about this code:
echo'<a href="javascript:pixlr.edit(
{ image: \'http://mywebite.com/uploads/$photo\',
title: \'' . $photoFileNameProper . '\',
service: \'express\',
exit:\'http://mywebsite.com/home\',
method: \'get\',
locktarget: \'true\',
target: \'http://mywebsite.com/plixr.php\',
locktitle: \'true\'
});"
id = "uploadedPhoto"
title = "click to enhance photo">
<img src="images/editphotohover.png"/>
</a>'
;

Rendered PHP Variable outside of the img src element, need escaping advice

Hey guys, I have the following code:
foreach($collection as $img)
{
$image_id = $img['imageid'];
$thumbwidget = wp_get_attachment_image_src($image_id, 'full');
$gallery .= '<a class="fav-image-a" href="http://www.bangstyle.com/haircut-detail/?uid='.$uid.'&img_id='.$image_id.'&ucolid='.$user_id.'&catid='.$col_id.'&theater">';
$gallery .= '<img src="';
$gallery .= thumbGen($thumbwidget[0],259,320,'valing=top');
$gallery .= '">';
$gallery .= '</a>';
}
I think I may have the wrong order of escaping. The rendered variable is not staying within the img src when rendered. I assume it has to do with my escaping somewhere.
The live url can be seen at http://bangstyle.com/test-widget/
You can see what's happening. The rendered elements are on top.
Why the extra quotes inside? What you are producing is this:
<img src="'THUMBWIDGETURL_IS_INSERTED_HERE'">
What you probably want is this:
<img src="THUMBWIDGETURL_IS_INSERTED_HERE">
To do that just remove the extra \':
$gallery .= '<img src="'.$thumbwidgeturl.'">';
Rules to be aware of:
In PHP, both single quotes and double quotes can be used to produce string literals.
Each should be used in a pair and that pair constitutes one string literal. So, in your example you have two string literals and a variable being combined (concatenated) with the dot (.) operator.
Inside single quotes, single quotes need to be escaped, and inside double quotes, double quotes need to be escape. The other type of quotes in each can be used freely without escaping.
Strings inside single quotes are taken as they are, while strings inside double quotes are interpreted for variables.
More information in the PHP docs on Strings.
How about this:
$gallery .= "<img src=\"" . $thumbwidgeturl . "\">";
or even:
$gallery .= '<img src="' . $thumbwidgeturl . '">';

Quotes problem when passing value to Javascript

I am using like
$myPage .= '<td><a href=\'javascript:editProduct('
.$row['id']
.',"'
.$row['name']
.'")\'>Edit</a></td>';
where $row['name'] has quotes in its value. it breaks. how do i solve the issue both from php side and js side...
$row['name'] is value from DB. and it will have value like pradeep's and pradeep"s also
i used like
$myPage .= '<td><a href=\'javascript:editProduct('.addslashes($row['id']).',"'.addslashes($row['name']).'")\'>Edit</a></td>';
it solves the issue of double quotes. but when i have single quotes in value the javascrit link looks like
javascript:editProduct(28,"pradeep\
it actually breaks..
And how do i strip down the slashes added by addslashes in javascript..
UPDATE - FINAL CODE
$myPage .= '<td><a href=\'javascript:editProduct('.$row['id'].',"'.htmlentities($row['name'],ENT_QUOTES).'")\'>Edit</a></td>';
and js looks like
function editProduct(id,name){
alert(name);
}
can any one solve my issues
Try:
$myPage .= "<td><a href='javascript:editProduct({$row['id']},\""
. htmlentities( $row['name'] )
. "\")'>Edit</a></td>";
htmlentities default behaviour is to convert double quotes and leave single quotes alone, if you require converting single and double quotes, then call it like this:
htmlentities( $row[ 'name' ], ENT_QUOTES )
Also, using { .. } in "..." strings is the correct way to substitute variables.
The PHP string
'<a href=\'javascript:editProduct('.$row['id'].',"'.$row['name'].'")\'>';
outputs (assuming some values)
<td><a href='javascript:editProduct(123,"abc")'></td>
Presumably it breaks if $row['name'] contains a " quote. You could replace such quotes with a \" in the string before you output it using str_replace('"', '\"', $row['name'])

PHP new line problem

simple problem baffling me...
i have a function:
function spitHTML() {
$html = '
<div>This is my title</div>\n
<div>This is a second div</div>';
return $html
}
echo $spitHTML();
Why is this actually spitting out the \n's?
Backslashes used in single quote strings do not work as escape characters (besides for the single quote itself).
$string1 = "\n"; // this is a newline
$string2 = '\n'; // this is a backslash followed by the letter n
$string3 = '\''; // this is a single quote
$string3 = "\""; // this is a double quote
So why use single quotes at all? The answer is simple: If you want to print, for example, HTML code, in which naturally there are a lot of double quotes, wrapping the string in single quotes is much more readable:
$html = '<div class="heading" style="align: center" id="content">';
This is far better than
$html = "<div class=\"heading\" style=\"align: center\" id=\"content\">";
Besides that, since PHP doesn't have to parse the single quote strings for variables and/or escaped characters, it processes these strings a bit faster.
Personally, I always use single quotes and attach newline characters from double quotes. This then looks like
$text = 'This is a standard text with non-processed $vars followed by a newline' . "\n";
But that's just a matter of taste :o)
Because you're using single quotes - change to double quotes and it will behave as you expect.
See the documentation for Single quoted strings.
Change ' to " :) (After that, all special chars and variable be noticed)
$html = "
<div>This is my title</div>\n
<div>This is a second div</div>";

Categories