美元($)login密码string视为variables

花了一些时间解决一个PHP / MySQL Web应用程序连接到数据库时遇到问题的问题。 数据库可以从shell和phpMyAdmin以完全相同的凭据访问,它没有任何意义。

原来密码有一个$符号:

$_DB["password"] = "mypas$word"; 

发送的密码是“mypas”,显然是错误的。

处理这个问题的最好方法是什么? 我以$ \

 $_DB["password"] = "mypas\$word"; 

它的工作。

我通常使用$string = 'test'作为string,这可能是我之前避免运行的。

这是正确的行为? 如果这个密码存储在一个数据库中,而PHP将其拉出,会发生同样的问题吗? 我在这里想念什么

 $_DB['password'] = 'mypas$word'; 

单引号string不被处理,并按“原样”进行。 你应该总是使用单引号string,除非你特别需要$variables或转义序列(\ n,\ r等)replace。 这是更快,更不容易出错。

PHP将variables$word插入到stringmypas$word ,正如使用双引号描述的string常量一样。 由于$word可能是未定义的,所以得到的插入string是mypas

解决方法是使用单引号。 单引号string文字不会经历可变插值。

只要把它放在一个单引号的string中:

 $_DB['password'] = 'mypas$word'; 

双引号string将插入variables,但单引号string不会。 所以这将解决你的问题。

使用单引号

 $_DB["password"] = 'mypas$word'; 

另一个回答所有工作,直到password中embedded单引号。

失败:

$_DB['password'] = 'my'pas$word';

备择scheme:

如果你没有其他的转义字符,你可以使用\$来转义\$ ,例如

$_DB['password'] = "my'pas\$word;"

或者,可以更简单地逃避单引号,例如

$_DB['password'] = 'my\'pas$word;'

只使用单引号'而不是',它不会尝试把$ word作为一个variables。

 $_DB['password'] = 'mypas$word'; 

带双引号的string引号被解释为variables。 单引号的string按字面解释。

 $a = "one"; $b = "$a"; echo $b . "\n"; $b = '$a'; echo $b . "\n"; 

这应该会产生:

 one $a 

我只是遇到这个问题,并find这个线程之前修复它。 我确信所有使用单引号的解决scheme都是完美的。 我select了只是连接通行证,这也正常工作,因为我不知道单引号解决scheme…. IE

 $db_password = "SamWise" . "$" . "GangiTYloYG";