I'm following a PHP tutorial, and came accross this line of code
redirect_to("manage_content.php?subject={$current_subject["id"]}");
I was surprised to see this works without the need to escape the quotes around "id" inside the brackets.
But I don't understand why. Does anyone know?
When you wrap a variable in curly braces {}, the PHP parser knows anything inside that is a variable and won't parse it like the rest of the string!
This only works with strings in double-quotes - single-quoted strings are taken at face value, so this has to be escaped:
$str = 'My cool string! {$array[\'key\']}';
While your example doesn't.
Because of this, it's best practice to put static strings in single quotes - it's a micro-optimization, but it's technically a bit faster since the PHP parser doesn't have to work its way through the string!
Related
I am new to Laravel and I am having this question.
I tried out this line of code and it works fine: return redirect("/cards/{$note->id}");
But when ever I try to use the single quotes, it does not work: return redirect('/cards/{$note->id}');
How can I solve this problem ?
What you are doing first is called variable interpolation or string interpolation. You can read more about it here, on PHP docs and here, on Wiki.
It's a feature in PHP that allows you to pass a string and have variables/placeholders inside interpreted.
In your second example you are using single quotes, which does not provide this feature, so you will have to break it up and add the variable manually to the string:
return redirect('/cards/' . $note->id);
If you are interested in a more elaborate explanation and the performance behind it then you can read more on this answer here by Blizz
He concludes that:
Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.
However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.
You should use "/cards/{$note->id}" or '/cards/'.$note->id
The most important feature of double-quoted strings is the fact that variable names will be expanded.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
From PHP documentation
Use it like that:
return redirect('/cards/'. $note->id);
With either single or double quotes
I'm working to integrate a plug-in into a PHP web application, and one line of the code puzzles me:
$sql = "update inventory set qtyleft='$qtyleft',price='$price',sales=sales+'$sales',qtysold=qtysold+'$qtysold' where id='$id'";
mysql_query($sql);
where $qtyleft, $price, $sales, $qtysold and $id are all variables.
I'm not very familiar with PHP, but I always thought string concatenation in PHP is done by using the . operator and it seems to me that the code above is just a long string without actually putting those variables to the SQL query. Is that the case?
In PHP, double quote (") delimited strings will evaluate variables in them.
$foo = 42;
echo "The answer for everything is $foo"; // The answer for everything is 42
This specific example is very bad because you shouldn't include variables directly in an SQL query, and shouldn't use mysql_query in new code.
See more:
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
See Variable Parsing section of the Strings manual page.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
If you use single quotes for a string, the variables will not be interpolated. If you use double quotes, they will be.
The code you mentioned will work in PHP without any issues. Please refer PHP Manual for more details.
Other issue that you might need to look forward is the function mysql_query is depreciate. Please refer here. Which gives me a feeling that the plugin you are going to is use not maintained correctly. And one more problem is, its not a good practice to pass the variable directly in the SQL query do to possible security issues
Some call it "variable interpolation". It is explained on the Variable parsing section of the manual page about strings. It helps to read the entire page and also the user comments.
The basic idea is that for strings enclosed in quotes (") and on heredoc blocks, PHP searches for variables inside the string when it needs to use it and replaces them with their values at the moment of the execution. This means the same string can render to different values in different moments of the script's execution.
This is just syntactic sugar, it doesn't change the way the code behaves and any string that contains variables inside can be rewritten using the string concatenation operator (.). Usually this syntax produces shorter source code. Sometimes the code is easier to read this way, other times it is harder because the complex expressions (array access, f.e.) need to be enclosed in curly braces ({ and }) inside the string.
Normally, when variables in PHP are enclosed in single quotes, they are treated as strings, i.e
echo '$variable';
will actually echo the word $variable onto the screen.
So why is it then that this string is parsed:
echo "'$variable'";
That code actually does echo the value of the variable. Why is that? It's still inside single quotes, so why does it still get parsed?
The string is wrapped in double quotes -- the single quotes are part of the content of the string, not part of the string's delimiter. Therefore the single quotes have no semantic meaning whatsoever.
Your question indicates that you may have a fundamental misunderstanding of strings. This is OK! Strings are surprisingly complex entities, and will only get more complex if you learn lower level languages like C. I would suggest you spend some time reading up on strings both in general as well as within PHP. A few quick google searches will honestly be better than a curated list for this task.
Because the single quotes are inside double quotes. Anything inside double quotes gets evaluated. So, your echo statement is passed a string inside double quotes.
This string is evaluated then output. It contains single quotes and a variable.
Try this instead:
<?php
$var = 10;
echo '"$var"';
?>
Because it's in double-quotes as well. The outer most layer of quotes denotes what kind of string it is.
It is simply a double quoted string that contains two single quote characters. Once they are in the double quotes, they have no meaning to the parser.
I changed the single quotes to doubles quotes after I faced th following problem:
$lang = array(
'let's do something...'
);
Now I have this problem:
$lang = array(
"tagline_h2" => "A paragraph...this is a link"
);
What should I do?
As you are having double-quotes in a double-quoted string, you have to escape the double-quotes inside the string, using a backslash :
"A paragraph...this is a link"
See Double quoted string in the manual : it states that PHP will interpret the \" sequence as a double-quote (and \n will interpreted as a newline, and there are a couple of other of those sequences)
I like to use urlencode() and urldecode() to store strings temporarily. That way I don't have to think about double-quotes, quotes, ampersands, newlines or tabs or in fact anything.
Two caveats:
The academics will point out that it performs worse, and I would respond by saying that more time is wasted thinking about it than dealing with it, since it's a PHP website and not a particle accelerator. (Or is it?)
You have to urldecode() it when you're going to show it.
PLEASE NOTE that for the problem you describe, urlencode()/urldecode() would be overkill. I only mentioned this for future reference, but in your particular case, the escaping is far more appropriate as described in the accepted solution.
Even better, if you know that you are going to be dealing with quotes, why not use the heredoc and nowdoc syntaxes?
That way, you can do:
$lang = array(
"tagline_h2" => <<<LINK A paragraph...this is a link
LINK
);
I am trying to test some of these code here http://ha.ckers.org/xss.html on my code. To do so I need to set the codes on that page into a PHP variable, I am having trouble though.
For example this code below is incorrect just for setting it to a variable because of the "code" and 'code' the '" is what I am talking about. How can I set code from that page or below into a PHP variable for testing?
$string = '<IMG SRC=\"javascript:alert('XSS');\"><b>hello</b> hiii';
You need to escape the quotes you used to declare the string with. So in your case the single quotes:
'<IMG SRC="javascript:alert(\'XSS\');"><b>hello</b> hiii'
Otherwise the string would be aborted with that unescaped quote.
Another way, maybe a bit easier (you don't have to escape the quotes, nor double-quotes) would be to use Heredoc syntax :
$string = <<<STR_1
<IMG SRC="javascript:alert('XSS');"><b>hello</b> hiii
STR_1;
Note you'll still have to escape the $ sign, if you have some, to not have varible interpolation.
Quoting the manual :
Heredoc text behaves just like a
double-quoted string, without the
double quotes. This means that quotes
in a heredoc do not need to be
escaped, but the escape codes listed
above can still be used. Variables are
expanded, but the same care must be
taken when expressing complex
variables inside a heredoc as with
strings.
Note : read the manual about that : there are some things you must know before using heredoc syntax (like the fact that the closing identifier must be alone on its line)