single quote within double quote - php

i read string documentation on PHP and found out that Single quoted strings will display things almost completely "as it is." Variables and most escape sequences will not be interpreted except \' and \\
I wanted to display a hyperlink whose address should be http://localhost/kk/insert.php/?id="4"
i tried the following code
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=".$id."'>edit</a>";
But it's displaying http://localhost/kk/insert.php/?id=4 (there are no double quotes surrounding 4)
However, i accomplished the result by using
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
My question is that single quotes does interpret \" escape character. So why the first code is not displaying double quotes (that are placed inside single quotes). What am i missing?

You shouldn't have quotes around the integer. Your url should be
http://localhost/kk/insert.php/?id=4
which is accomplished using the following code:
$id = 4;
echo 'edit';

You're dealing with TWO languages there. PHP is doing the echo, and the " quotes are parsed/removed by PHP. Then there's the ' quotes, which are used in the HTML to delimit the href attribute.
With your escaped second version:
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
^--php ^--html ^^--escaped for PHP
Normally that " before $display_result would TERMINATE the PHP string you've been echoing. But since it's been escaped (\"), the escape tells PHP to treat that quote as plaintext, and NOT as a quote. So the PHP string continues, and when this code actually executes and is output from your server, the browser will actually see:
<a href='http://localhost/kk/insert.php/?id="XXX"'>edit</a>

The interpretting difference between single quote and double quote you found is this:
$a = 4;
echo '$a' . "$a"; // $a4
// '$a' just prints `$a`
// "$a" prints `4`, it's interpretted
// alternatively "\$a" prints `$a`
As for the escaping. If your string delimiter is a single quote then you don't need to escape double quotes, and vice versa.
$a = "don't";
// vs
$a = 'don\'t';
$a = '"quote"';
// vs
$a = "\"quote\"";

To do it with your first example, just do :
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=\"".$id."\"'>edit</a>";

Related

rtrim not working string with html elements

I have a problem with rtrim() function in php. I have string like this one:
$str = "<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],";
Like this, embed the string in array.
I want to remove that last comma in this string. rtrim not working.
When i remove that html elements from that string, rtrim() works perfectly. anyone help?
you have to change your string like this, then it will work, it does not work because your string is inappropriate:
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of
Collateral</a> [2017-04-01],";
echo rtrim($str,",");
output is:
Picture of Collateral [2017-04-01]
The only difference is that double quoted strings interpret embedded variables and a number of escape sequences, while single quoted strings do not. E.g.:
Reference: When should you use single or double quotes in PHP?
write your code below it works
you have write string ""(double quote) and under string you also used "" string instead of this you use ''(single quote);
<?php
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of Collateral</a> [2017-04-01],";
echo rtrim($str,",");
i believe you quoted the string wrong.
try the below:
$str = rtrim('<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],',',');
echo $str;

single quotes and double quotes in php?

Double quotes--->"$a" interpretes variables.
single quotes--->'$a' does not.Alright till now
MyQuestion:
what if I use "'$a'"?
Note:want to know behind the scene details.
Detailed Explanation:
I faced a major problem because of this when I used it in a foreach loop:
The following example gave me incorrect option value. For example, value it renders is UX if original is UX developer
echo "<option value=".$item['m_designation'].">".$item['m_designation']."</option>";
this example gave me correct option value. For example,value it renders is UX developer if original is UX developer
echo '<option value="'.$item['m_designation'].'"> '.$item['m_designation'].' </option>';
Hope I am clear.
Update:
I got the desired result but I don't know the logic behind it. I have tried it and done it successfully, but I wanted to know what's happening behind the scene. I think people have misread my question.
The use of ' and " for strings only changes when they are the outer container of the entire string - a different quote inside that is just treated as a plain character with no special meaning, therefore "'$var'" uses the rules of " (parsing variables), whereas '"$var"' would literally output "$var" as it uses the rules of ' (no parsing of variables).
Summary:
When you do "''" or "\"\"" the quotes inside the string are not parsed by PHP and treated as literal characters, the contents of such quotes will have the same behaviour in or out of those quotes.
You'll have a string that uses double quotes as delimiters and has single quotes as data. The delimiters are the ones that matter for determining how a string will be handled.
$a = 'test';
echo '$a';// prints $a
echo "$a";// prints test
echo "'$a'"//prints 'test'
double quotes checks the php variable and echo the string with php variable value
example echo "wow $a 123"; //prints wow test 123
single quotes print whatever in the single quotes
example echo 'foo $a 123';//prints foo $a 123
Your 'faulty' (first) string was missing the single quotes ':
echo "<option value='".$item['m_designation']."'>".$item['m_designation']."</option>";
^ ^
Your problem is that you confuse the quotes in your HTML with the quotes in the PHP.
$a = 1;
$b = '"$a"';
echo $b;
# => "$a"
$a = 1;
$b = "\"$a\"";
echo $b;
# => "1"
I'd advise you to simply never use string literals, as (especially in PHP) there are a lot of unexpected and weird edge-cases to them. Best is to force an interpreter (which also only works with double quotes:
$a = 1;
$b = "\"{$a}\"";
$c = "{$a+2}";
echo $b;
# => "1"
echo $c;
# => 3
It seems your question is more directed toward the output PHP produces for HTML formatting. Simply, single quotes in PHP represent the literal value:
$a = 1;
$b = '$a';
echo $b;
//$a
$a = 1;
$b = "$a";
echo $b;
//1
$a = 1;
$b = "'$a'";
echo $b;
//'1'
If you want to output HTML, you can use heredoc syntax. This is useful when outputting more than one line containing variables:
$name = "Bob";
$age = 59;
echo <<<EOT
My name is "$name".
I am $age years old.
EOT;
//My name is "Bob"
//I am 59 years old.

How do I escape only single quotes?

I am writing some JavaScript code that uses a string rendered with PHP. How can I escape single quotes (and only single quotes) in my PHP string?
<script type="text/javascript">
$('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>
Quite simply: echo str_replace('\'', '\\\'', $myString);
However, I'd suggest use of JSON and json_encode() function as it will be more reliable (quotes new lines for instance):
<?php $data = array('myString' => '...'); ?>
<script>
var phpData = <?php echo json_encode($data) ?>;
alert(phpData.myString);
</script>
If you want to escape characters with a \, you have addcslashes(). For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape ', ", \, and nul (the byte null), you can use addslashes():
echo addslashes($value);
str_replace("'", "\'", $mystringWithSingleQuotes);
In some cases, I just convert it into ENTITIES:
// i.e., $x= ABC\DEFGH'IJKL
$x = str_ireplace("'", "&apos;", $x);
$x = str_ireplace("\\", "&bsol;", $x);
$x = str_ireplace('"', """, $x);
On the HTML page, the visual output is the same:
ABC\DEFGH'IJKL
However, it is sanitized in source.
Use the native function htmlspecialchars. It will escape from all special character. If you want to escape from a quote specifically, use with ENT_COMPAT or ENT_QUOTES. Here is the example:
$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
The output would be like this:
Jane & 'Tarzan'<br>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'
Read more in PHP htmlspecialchars() Function
To replace only single quotes, use this simple statement:
$string = str_replace("'", "\\'", $string);
You can use the addcslashes function to get this done like so:
echo addcslashes($text, "'\\");
After a long time fighting with this problem, I think I have found a better solution.
The combination of two functions makes it possible to escape a string to use as HTML.
One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.
Solution:
mysql_real_escape_string(htmlspecialchars($string))
Solve:
a PHP line created to call a JavaScript function like
echo
'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"
I wrote the following function. It replaces the following:
Single quote ['] with a slash and a single quote [\'].
Backslash [\] with two backslashes [\\]
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\'
);
return strtr($target, $replacements);
}
You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".
/**
* With new line replacements too
*/
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\',
"\r\n" => "\\r\\n",
"\n" => "\\n"
);
return strtr($target, $replacements);
}
The neat feature about strtr is that it will prefer long replacements.
Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.
Here is how I did it. Silly, but simple.
$singlequote = "'";
$picturefile = getProductPicture($id);
echo showPicture('.$singlequote.$picturefile.$singlequote.');
I was working on outputting HTML that called JavaScript code to show a picture...
I am not sure what exactly you are doing with your data, but you could always try:
$string = str_replace("'", "%27", $string);
I use this whenever strings are sent to a database for storage.
%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.
To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.
Happy injection avoiding!

how i can print the variable as it not the value of the variable

In this code
<?php print "value of a is $a" ?>
I need to print this statement as it how?
use single quote if you don't want to print the value of variable
<? php print 'value of a is $a' ?>
You could either use single quotes or escape $a within double quotes with a \.
Either:
<?php print 'value of a is $a' ?>
Or:
<?php print "value of a is \$a" ?>
PHP performs variable parsing in double quoted strings,
You can use single quoted strings.
So depending on want you really want, you can do
print 'value of a is $a';
which literally print the string 'value of a is $a' (which does not make much sense).
Or you can use string concatenation to print the variable and it's value:
print 'value of $a is ' . $a;
which will print 'value of $a is 42' (if $a = 42;).
If you want to print $a and not the a variable's value, there are two ways:
Escape the $: print "value of a is \$a";
Use single quotes instead
Everything in single quotes, including $something and special chars (newline \n, Unicode chars \uxxxx) are treated literally.
print 'value of a is $a';
If you want to print $a and not the a variable's value, there are two ways:
1. Escape the $
<?php print "value of a is \$a"; ?>
2. Use single quotes instead
Everything in single quotes, including $something and special chars (newline \n, Unicode chars \uxxxx) are treated literally.
<?php print 'value of a is $a'; ?>
If you want to include the variable in the string you must use single quotes like so
<? php print 'value of a is $a' ?>
Hope this helps.
Append with a dot, escape double-quoted strings with a backlash, or use single quotes and obviate the need for escaping.

What's the difference between " and ' when creating strings in PHP?

Very basic, but would like to know the difference/security ramifications etc of using " vs. '.
Can someone provide an example that explains when to use each one?
There are a lot of subtle differences, you'll want to read the php documentation to get a lot of the details, but the important detail are:
Double quotes are parsed whereas single quotes are literals.
You can use variables inline with double quotes, but not with single quotes.
There are some catches though:
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers"; // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
Single quotes are slightly faster.
When a string is enclosed in double quotes, then escape sequences such as \n and variable identifiers such as $var are interpreted.
See the PHP strings manual for specific details and examples.
The biggest one is this. Inside double-quotes, you can include variables, but inside single quotes, the variable name will be literal:
$var1 = "hello";
// this will echo "hello world"
echo "$var1 world";
// this will echo $var1 world
echo '$var1 world';
Using double-quotes becomes extremely useful in a number of situations, expecially when you place {} around the variable names. Here are some examples (certainly others can give you more examples):
// array elements
echo "Element 5 is {$myArray[5]}";
echo "Element 2 subelement 3 is {$myArray[2][3]}";
//
// a dynamic key
$value = "thing";
$someValue = $myArray["some{$value}"]; // returnd $myArray[something]

Categories