views:

377

answers:

4

Hi there,

Been struggling with replacing a backslash by another symbol such as '.-.' just to indicate the position of backslashes as I could not send a string such as 'C\xampp\etc.' through url as GET variable so I thought I'd first replace the backslashes in that string by another symbol, then send through url, and then replace them back to backslashes in the PHP file that handles it. Though would there be a better way to send such strings through url? Because when I try a script such as:

$tmp_name = preg_replace("\", ".-.", $_FILES['uploadfile']['tmp_name']);

It turns out into a php error as \ is also used as delimiter..

Could anyone help me out on this?

Thanks in advanced!

Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?

A: 

The regex used in preg_replace should be enclosed in a pair of delimiter and also Try using \\\ instead of \ as:

$tmp_name = preg_replace("{\\\}", ".-.", $_FILES['uploadfile']['tmp_name']);

EDIT:

To reverse the substitution you can do:

$str = preg_replace('{\.-\.}',"\\",$str);

You need to escape the . to match a literal dot.

codaddict
Awesome! That totally solved my problem, thanks a lot!
Skyfe
Update: how would I reverse this?
Skyfe
@Skyfe: Updated the answer.
codaddict
That really worked, thanks hypes again.
Skyfe
+3  A: 

use urlencode()/urldecode().

echo urlencode('C:\xampp\etc'); // C%3A%5Cxampp%5Cetc

BTW: This sounds like a huge security flaw (sending absolute paths by request)


PS: preg_replace() is for regular expressions. Try str_replace() next time.

Philippe Gerber
+1 The correct answer, IMHO.
middaparka
A: 

If you're not using a regular expression (which you're not), you should use str_replace instead:

$tmp_name = str_replace('\\', '.-.', $_FILES['...']);

Note that you have to escape the \ with another \ (otherwise it'd escape the following ').

As for the delimiter error - regular expressions need to be enclosed in delimeters, for example /foo/ (/ is the delimiter, foo is the pattern). But, again, there's no need for you to use or worry about regexps

Chris Smith
+1  A: 

Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?

That's easy. PHP:

$url = 'http://example.com/?array=' . urlencode(serialize($array)); // html
$array = unserialize($_GET['array']); // server side

Or Javascript:

url = "http://example.com/?array=" + encodeURIComponent(JSON.stringify(array)); // client
$array = json_decode($_GET['array']); // server

(for Javascript you'll have to look up whether encodeURIComponent is correct, and you need the official JSON library as well)

Bart van Heukelom