警告:mysql_connect():访问被拒绝 [英] Warning: mysql_connect(): Access denied

查看:39
本文介绍了警告:mysql_connect():访问被拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 php 函数可以从我电脑上的文本文件中读取我的 dbinfo:

i have this php function to read my dbinfo out of a textfile on my pc:

function loaddb(){
    $fh = fopen('dta.txt','r');
        $line = fgets($fh);
        $_SESSION['dbname']=$line;
        
        $line = fgets($fh);
        $_SESSION['dbuser']=$line;
        
        $line = fgets($fh);
        $_SESSION['dbpass']=$line;
        
        $line = fgets($fh);
        $_SESSION['server']=$line;                                  
    fclose($fh);
};

并且此代码有效.但是当它将我的代码返回到我的会话变量中时,我看到它在实际变量中添加了额外的换行符,所以我连接时的结果是

and this code works. but when it returns my code into my session var i see it has added extra line breaks in the actual variable, so the result when i connect is

警告:mysql_connect():用户root"访问被拒绝

Warning: mysql_connect(): Access denied for user 'root

'@'localhost'(使用密码:YES)在C:\Users\Jacques\Dropbox\Jacques\Web\Code.php 第 37 行无法连接:用户root"的访问被拒绝

'@'localhost' (using password: YES) in C:\Users\Jacques\Dropbox\Jacques\Web\Code.php on line 37 Could not connect: Access denied for user 'root

'@'localhost'(使用密码:YES)

'@'localhost' (using password: YES)

我该如何解决这个问题.我试过替换所有字符返回和空格,但没有帮助

how can i fix this. i have tried replacing all character return and spaces but it doesnt help

这是我的文本文件中的文本

this is the text in my textfile

数据库名称

密码

本地主机:3306

推荐答案

如果您确定字符串的每一端都有空格,您可以使用 trim()

If you're sure that the whitespaces are on each end of the string, you can use trim()

$_SESSION['dbname']= trim($line);

当你对一个可以有多个空格的字符串取消对齐时,你可以用一个简单的正则表达式来解决这个问题:

When you're dealign with a string that can have several spaces, you can solve that with a simple regular expression:

$regex = '/(\s)\s+/'; // Select a whitespace and following whitespaces
$str = preg_replace($regex, '$1', $str); // Replace with the first whitespace


重要的旁注

将数据库凭据保存在 www 文件夹中的文本文件中是一种非常糟糕的做法.如果有人碰巧找到了文件名,他可以读取您的凭据.


Important sidenote

Saving your database credentials in a text file in your www folder is a very bad practise. If someone happens to find the filename he can read your credentials.

PHP 代码在发送到客户端之前会被解析,因此客户端无法访问凭据(除非您回显它们).

PHP code however is parsed before sent to the client, thus client's can't access the credentials (unless you echo them).

config.php

<?php
define('DB_HOST', 'localhost:3306');
define('DB_NAME', 'dbname');
define('DB_USER', 'root');
define('DB_PASS', 'password');

然后,每当您需要数据库凭据时:

Then, whenever you need your database credentials:

require 'config.php';
// connect here


另一个旁注

mysql_ 函数自 PHP 5.5.0 起已弃用.您应该使用 mysqli_PDO 代替.我自己更喜欢 PDO.


Another sidenote

The mysql_ functions are deprecated as of PHP 5.5.0. You should use mysqli_ or PDO instead. I prefer PDO myself.

这篇关于警告:mysql_connect():访问被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆