简体   繁体   English

如何防止从另一个客户端包含数据库 config.php?

[英]How to prevent including database config.php from another client?

We have this config.php file:我们有这个 config.php 文件:

<?php
$host = "host";
$dbname = "db";
$user = "user";
$pass = "pass";
        try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch(PDOException $e) {
        die("Error");
        }
?>

And this structure而这个结构

/www/
    index.php
    config.php

The index file is accessable via www.example.com/index.php , but the config.php file too (via www.example.com/config.php ).索引文件可通过www.example.com/index.php访问,但 config.php 文件也可访问(通过www.example.com/config.php )。

Can others just include www.example.com/config.php in there php files and execute code with my $conn ?其他人可以在 php 文件中包含www.example.com/config.php并使用我的$conn执行代码吗? How to prevent this?如何防止这种情况?

It's true that if you leave files in the web root, the web server will execute them when a matching request URI comes through.确实,如果您将文件留在 web 根目录中,则 web 服务器将在匹配的请求 URI 到达时执行它们。

However, do understand that the source code is not (normally) viewable by clients.但是,请了解源代码(通常)不被客户查看。 For example, when someone makes a request for /index.php , they don't see the PHP source code.例如,当有人请求/index.php时,他们看不到 PHP 源代码。 They only see its output.他们只看到它的 output。 Likewise, if someone were to make a request for /config.php , given the example code your question they should get nothing but an empty response.同样,如果有人要请求/config.php ,给定示例代码您的问题,他们应该得到的只是一个空响应。 So, to answer your question...所以,回答你的问题...

Can others just include www.example.com/config.php in there php files and execute code with my $conn?其他人可以在 php 文件中包含 www.example.com/config.php 并使用我的 $conn 执行代码吗?

No, they cannot.不,他们不能。

To execute code, they need to be running code on your server.要执行代码,它们需要在您的服务器上运行代码。

Now, it's still a good practice to get your config.php and any other includes out of the web root.现在,从 web 根目录中获取config.php和任何其他包含仍然是一个好习惯。 The reason for that is to prevent exposure of code in the event PHP gets disabled on your web server.这样做的原因是为了防止在 PHP 在 web 服务器上被禁用的情况下暴露代码。 It's not too uncommon to try to upgrade your web server or something, break the config, accidentally disable PHP on a live server, and now everyone can see all your source code.尝试升级您的 web 服务器或其他东西,破坏配置,在实时服务器上意外禁用 PHP 并不少见,现在每个人都可以看到您的所有源代码。 If that source code isn't in the web root, there's nothing they can request.如果该源代码不在 web 根目录中,则他们无法请求任何内容。

Additionally, there are often more open permissions on files within your web root.此外,web 根目录中的文件通常有更多的打开权限。 So, it's just a good practice to keep things out of there when you can... but not directly for the reason you were concerned about.因此,在可能的情况下将事情排除在外只是一个好习惯……但不是直接出于您担心的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM