Synetech
Synetech

Reputation: 9925

Do (back-slashes in) paths need to be escaped?

It is not uncommon to have to put a path to a file or directory in a string in a program or script’s code. This isn’t usually a problem with paths on *nix systems since they use forward slashes which usually does not need to be escaped in most languages, but Windows uses back slashes for paths which usually do need to be escaped in most languages.

With C(++), you usually do have to escape the slashes of a path in a string because most compilers will emit a warning if you don’t, but I have seen other code, particularly PHP scripts, which do not escape them. For example, I have seen countless examples of configuration files containing lines similar to this:

static $storageDir = 'C:\webgrind\tmp';

Ostensibly you must escape such paths, and I did consider that maybe they were written by people who were not actually using Windows and simply extrapolating configuration data from Linux to Windows without actually testing it, but if that were the case, then the code should fail, yet it seems that it often works.

So do you have to escape paths in strings in code? I’m asking mostly about PHP because that’s where I’ve personally seen this happen the most, but I’m open to other/universal answers as well.

Upvotes: 1

Views: 4679

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157828

Speaking of paths particularly, forward slashes will do as well

'C:/webgrind/tmp'

Upvotes: 2

mario
mario

Reputation: 145482

Single quoted strings in PHP do not need the double escaping. Unlike double quoted strings where a lowercase letter behind a singular backslash could spell trouble.

However in single quoted strings, the backslash still can escape itself.

'abc\\abc' == 'abc\abc'

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798486

Single quotes inhibit all escape sequences other than \\ and \', so there is no need to escape backslashes within them unless it appears as the final character in the string literal.

Upvotes: 1

Related Questions