PHP Wrap a string in double quotes - php

I'm attempting to wrap a user-inputted string in double quotes for output but I want to make sure I don't end up with double double quotes on either side of the string. For example, if a user posts
"Hello"
I don't want to turn it into
""Hello""
I can do this fairly easily using the code below, however I'm concerned that this may get slow if I'm looping through lots of strings.
$string = '"'.trim($string,'"').'"';
If anyone has a better way of doing this, that'd be great. Equally, if anybody can confirm that my way is fine, I'll be happy.
Thanks

This is exactly how I would solve this problem. It's only worth worrying about the code being slow if you have a problem with the application being slow, and you can trace it down to the trim statements.
A well known programming quote is "Premature Optimisation is the root of all evil" - see the wikipedia article linked for more on this.

Make a careful consideration of what should happen with all the cases.
(using [] as quotes for readability)
You've said what you do for ["Hello"] but what do you do for [I said "Hello", punk]? Do you still strip the user-input quotes, or do you remove them? Or maybe go one step further and substitute single quotes for double quotes...but then you'd have to consider the cases where the user input contains both single and double quotes! What about when the user puts in "grammatically wrong" text like ["Hello] (no closing quote!).
Best way to ensure you do it right is to make a test case for each edge case you can think of and make sure your proposed solution actually does what is expected.
If the actually reason for this requirement is [I am taking a user's input at some point and then re-displaying it to them at another point, and don't want to show them stupid looking data like [""data""]], you'll probably just want to only remove double quotes from the start or end of the input string, because stripping them from the middle screws with the user's intended data.
If your goal is merely to clearly distinguish between their input and text that they didn't input, consider using other means of highlighting that instead of quotation marks. So instead of [you entered "data"], you could display [you entered data] or [you entered: data] which avoid this problem altogether.

Personally, I'd suggest stripping the quotes on input. As for making it faster, if you allow quotes to be entered or stored, you're always going to be stuck with using an if/else before displaying them.
Obviously, you'd still need to perform a sanity check of the input data regardless of whatever system you end up with.

I did it this way:
function quotize(&$string)
{
if (empty($string) || is_null($string)) {
return;
}
$char = '"';
if ($string[0] != $char) {
$string = $char . $string;
}
if (substr($string, -1) != $char) {
$string .= $char;
}
return;
}

It is common practice to use quotation marks to represent a quote within a quote, if you want to let your users write:
and she said "hey ho"
, which you could turn into:
User: "and she said 'hey ho'"

Related

Is it safe to concatenate a double quoted to a single quoted string?

Are there any issues I should be aware of when doing the following:
$table_html = ' <td id="unescaped-double-quotes-yay">Some stuff</td>' . "\n";
I do not like escaping double quotes withing HTML and I can't stand using single quotes in HTML, my solution is what I have above. Am I going to run into any issues with this practice?
You MUST escape strings that comes from DB or from the user because they could easily break you concatenation if the unexpected kind of quote is present in that string (not to mention that you MUST cleanse anything that comes from the user for minimal security).
Other than that you can concatenate strings any way you like. Still, life will always be easier if you manage to use them cosistently the same way.
I have done this many times on client sites (have since found better alternatives), you are 100% fine.
Are you aware of the following representation:
$table_html = <<<HTML
<td id="unescaped-double-quotes-yay">
Some stuff, and i can use normal newlines here
</td>
HTML;
It is called "heredoc", and you must keep in mind that the final string must be equivalent to the opening one, and must be the only thing on the line (no spaces or even comments are allowed).
You must also terminate the last line with the newline, even if it is the last line in the file.
To read more about it click here

PHP Switch Statement where the string is encapsulated in double quotes

I have an issue here, and I'm looking for experienced programmers to tell me which is the preferred solution.
I have values being returned that are surrounded in quotes. "TOTAL" and "VALUE" being two examples. These should not be confused with TOTAL and VALUE -- the string is actually surrounded by double quotes.
What I noticed is that the switch statement below doesn't work because it's looking for TOTAL not "TOTAL":
switch ($statTypeName) {
case "TOTAL":
echo "<br>TOTAL";
break;
case "VALUE":
echo "<br>VALUE";
break;
}
To get this working, I had to put a single quote around the case -- '"TOTAL"'.
In my text editor (Notepad++), it is difficult to see the single quote around the double quotes.
I know this isn't a common issue, but what would be the "professional" way of solving this? The way I did it, or should I be extracting the string from the quoted string and do away with the double quotes altogether..?
Thanks!
case "\"TOTAL\"":
Escape the inner double quotes. It will work the same way and might be a little more visible to the reader
What you're running into is indeed common, and you can go about it a couple different ways. There's nothing wrong with the way you're doing it, or #KyleBanks solution (escaping the double quotes). Given php provides single and double quote string definitions, I prefer the first. But its up to your preference, or your dev team.
As far as extracting the substring within the string quotes.. it depends on what they're there for in the first place.
I would suggest using a better font in Notepad++. I personally use Consolas however here you can find heaps of other good options:
Recommended Fonts for Programming?
Other then changing font escaping quotes as was suggested is another alternative:
case "\"TOTAL\"":
You can also try to strip quotes:
switch (substr($statTypeName, 1, -1)) {...}
but i consider it as a more dangerous approach unless you start using more complicated code to strip them with checks and everything in which case it clearly becomes an overkill.
Except if your given code is not part of some kind of StatType class and is dealing internally with the representation of stat type states my answer might be missing the point a bit, but in any case here it is.
In fact you are doing something wrong here and what you are asking is to find a way to workaround the essential problem you are having. Instead, you should fix the essential problem.
Essential problem is that you are missing one layer of abstraction which will sit between the way you are representing your statType and the way you are using it.
So, your program should not care if you call your statType:
"TOTAL" or '"TOTAL"' or "Total" or "total"
What you need to care is that your statType is in certain state in one moment of program execution. How that representation of the state is implemented ( a string with quotes or a number) is detail of implementation and your switch statement should not care about it.
What happens if you decide to change your statTypeName to be without quotes for example. Than you'll have to go to every line of code that depended on it having quotes and to change it. If you would hide the implementation details in some way you would not need to change more than one line of code.
Maybe one approach to setting abstraction around statTypes? (simplified for clarity)
class StatType
{
const TOTAL = 0;
const VALUE = 1;
// etc.
}
switch ($statType->type()) {
case StatType::TOTAL:
echo "<br>TOTAL";
break;
case StatType::VALUE:
echo "<br>VALUE";
break;
}

Apostrophe issue

I have built a search engine using php and mysql.
Problem:
When I submit a word with an apostrophe in it and return the value to the text field using $_GET the apostrophe has been replaced with a backslash and all characters after the apostrophe are missing.
Example:
Submitted Words: Just can't get enough
Returned Value (Using $_GET): Just can\
Also the url comes up like this:search=just+can%27t+get+enough
As you can see the ' has been replaced with a \ and get enough is missing.
Question:
Does anybody know what causes this to happen and what is the solution to fix this problem?
The code:
http://tinypaste.com/11d62
If you're running PHP version less than 5.3.0, the slash might be added by the Magic Quotes which you can turn off in the .ini file.
From your description of "value to the text field" I speculate you have some output code like this:
Redisplay
<input value='<?=$_GET['search']?>'>
In that case the contained single quote will terminate the html attribute. And anything behind the single quote is simply garbage to the browser. In this case applying htmlspecialchars to the output helps.
(The backslash is likely due to magic_quotes or mysql_*_escape before outputting the text. I doubt the question describes a database error here.)
Update: It seems it's indeed an output problem here:
echo "<a href='searchmusic.php?search=$search&s=$next'>Next</a>";
Regardless of if you use single or double quotes you would need:
echo "<a href='searchmusic.php?search="
. htmlspecialchars(stripslashes($search))
. "&s=$next'>Next</a>";
(Notice that using stripslashes is a workaround here. You should preserve the original search text, or disable the magic_quotes rather.)
Okay I forgot something crucial. htmlspecialchars needs the ENT_QUOTES parameter - always, and in your case particularly:
// prepare for later output:
$search = $_GET['search'];
$html_search = htmlspecialchars(stripslashes($search), ENT_QUOTES);
And then use that whereever you wanted to display $search before:
echo "<a href='searchmusic.php?search=$html_search&s=$next'>Next</a>";
Single quotes are important in PHP and MySQL.
A single quote is a delimeter for a string in PHP, for example:
$str = 'my string';
If you want to include a literal quote inside a string you must tell PHP that the quote is not the end of the string. It is escaped with the backslash, for example:
$str = 'my string with a quote \' inside it';
See PHP Strings for more on this.
MySQL operates in a similar way. An example query might be:
$username = 'andyb';
$quert = "SELECT * FROM users WHERE user_name = '$username'";
The single quote delimits the string parameter. If the $username included a single quote, this would cause the query to end prematurely. Correctly escaping parameters is an important concept to be familiar with as it is one attack vector for breaking into a database - see SQL Injection for more information.
One way to handle this escaping is with mysql_real_escape_string().

Escape quote or special characters in array value

In my PHP code, I'm setting up an area for people to enter their own info to be displayed. The info is stored in an array and I want to make it as flexible as possible.
If I have something like...
$myArray[]['Text'] = 'Don't want this to fail';
or
$myArray[]['Text'] = "This has to be "easy" to do";
How would I go about escaping the apostrophe or quote within the array value?
Thanks
Edit: Since there is only a one to one relationship, I changed my array to this structure...
$linksArray['Link Name'] ='/path/to/link';
$linksArray['Link Name2'] ='/path/to/link2';
$linksArray['Link Name2'] ='/path/to/link3';
The plan is I set up a template with an include file that has these links in a format someone else (a less technical person) can maintain. They will have direct access to the PHP and I'm afraid they may put a single or double quote in the "link name" area and break the system.
Thanks again.
POSSIBLE SOLUTION:
Thanks #Tim Cooper.
Here's a sample that worked for me...
$link = "http://www.google.com";
$text = <<<TEXT
Don't you loving "googling" things
TEXT;
$linksArray[$text] = $link;
Using a heredoc might be a good solution:
$myArray[]['Text'] = <<<TEXT
Place text here without escaping " or '
TEXT;
PHP will process these strings properly upon input.
If you are constructing the strings yourself as you have shown, you can alternate between quotation styles (single and double)...as in:
$myArray[]['Text'] = "Don't want this to fail";
$myArray[]['Text'] = 'This has to be "easy" to do';
Or, if you must escape the characters, you use the \ character before the quotation.
$myArray[]['Text'] = 'Don\'t want this to fail';
$myArray[]['Text'] = "This has to be \"easy\" to do";
If you really want to make i easy, use a separate configuration file in either INI or XML style. INI is usually the easiest for people to edit manually. XML is good if you have a really nested structure.
Unless you are letting users enter direct PHP code (you probably aren't), you don't have to worry about what they enter until you go to display it. When you actually display the info they enter, you will want to sanitize it using something like htmlentities().
Edit: I realize I may be misunderstanding your question. If so, ignore this! :)
You can use the addslashes($str) function to automatically escape quotes.
You can also try htmlentities, which will encode quotes and other special values into HTML entities: http://php.net/manual/en/function.htmlentities.php

PHP 'addslashes' not behaving as expected

This has been driving be crazy, but I can't seem to find an answer. We run a technical knowledge base that will sometimes include Windows samba paths for mapping to network drives.
For example: \\servername\sharename
When we include paths that have two backslashes followed by each other, they are not escaped properly when running 'addslashes'. My expected results would be "\\\\servername\\sharename", however it returns "\\servername\\sharename". Obviously, when running 'stripslashes' later on, the double backslash prefix is only a single slash. I've also tried using a str_replace("\\", "\", $variable); however it returns "\servername\sharename" when I would expect "\\servername\sharename".
So with addslashes, it ignores the first set of double-backslashes and with str_replace it changes the double-backslashes into a single, encoded backslash.
We need to run addslashes and stripslashes for database insertion; using pg_escape_string won't work in our specific case.
This is running on PHP 5.3.1 on Apache.
EDIT: Example Code
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo addslashes($variable);
This returns: In the box labeled Folder type: \\servername\\sharename
EDIT: Example Code #2
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo str_replace('\\', '\', $variable);
This returns: In the box labeled Folder type: \servername\sharename
I'd also like to state that using a single quotes or double-quotes does not give me different results (as you would expect). Using either or both give me the same exact results.
Does anyone have any suggestions on what I can possibly do?
I think I know where is a problem. Just try to run this one:
echo addslashes('\\servername\sharename');
And this one
echo addslashes('\\\\servername\sharename');
PHP escapes double slashes even with single quotes, because it is used to escape single quote.
Ran a test on the problem you described, and the only way I could get the behavior you desired was to couple a conditional with a regex and anticipate the double slashes at the start.
$str = '\\servername\sharename';
if(substr($str,0,1) == '\\'){
//String starts with double backslashes, let's append an escape one.
//Exclaimation used for demonstration purposes.
$str = '\\'.$str;
echo addslashes(preg_replace('#\\\\\\\\#', '!',$str ));
}
This outputs:
!servername\\sharename
While this may not be an outright answer, it does work and illustrates a difference in how the escape character is treated by these two constructs. If used, the ! could easily be replaced with the desired characters using another regex.
This is not a problem with addslashes, it is a problem with the way you are assigning the string to your variable.
$variable = 'In the box labeled Folder type: \\servername\sharename';
echo $variable;
This returns: In the box labeled Folder type: \servername\sharename
This is because the double backslash is interpreted as an escaped backslash. Use this assignment instead.
$variable = 'In the box labeled Folder type: \\\\servername\\sharename';
I've determined, with more testing, that it indeed is with how PHP is handling hard-coded strings. Since hard-coded strings are not what I'm interested in (I was just using them for testing/this example), I created a form with a single text box and a submit button. addslashes would correctly escape the POST'ed data this way.
Doing even more research, I determined that the issue I was experiencing was with how PostgreSQL accepts escaped data. Upon inserting data into a PostgreSQL database, it will remove any escape characters it is given when it actually places the data in the table. Therefore, stripslashes is not required to remove escape characters when pulling the data back out.
This problem stemmed from code migration from PHP 4.1 (with Magic Quotes on) to PHP 5.3 (with Magic Quotes deprecated). In the existing system (PHP4), I don't think we were aware that Magic Quotes were on. Therefore, all POST data was being escaped already and then we were escaping that data again with addslashes before inserting. When it got inserted into PostgreSQL, it would strip one set of slashes and leave the other, therefore requiring us to stripslashes on the way out. Now, with Magic Quotes off, we escape with addslashes but are not required to use stripslashes on the way out.
It was very hard to organize and determine exactly where the problem lay, so I know this answer is a little off to my original question. I do, however, thank everyone who contributed. Having other people sound off on their ideas always helps to make you think on avenues you may not have on your own.

Categories