Replacing backslash with another symbol in PHP

2019-02-25 03:55发布

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 advance!

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?

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-25 04:19

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.

查看更多
趁早两清
3楼-- · 2019-02-25 04:24

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

查看更多
混吃等死
4楼-- · 2019-02-25 04:32

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.

查看更多
看我几分像从前
5楼-- · 2019-02-25 04:35

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)

查看更多
登录 后发表回答