简体   繁体   English

查找到public_html目录的文件路径,或使用PHP等效

[英]Find filepath to public_html directory or it's equivalent using PHP

I'm creating a .php file that will be uploaded to the root directory of a server. 我正在创建一个将上传到服务器根目录的.php文件。 I need that .php file to then figure out the path to the public_html folder or it's equivalent. 我需要.php文件然后找出public_html文件夹的路径或它是等价的。

I need to do this because I want my .php file to be able to be uploaded to the root and used on any hosting account. 我需要这样做,因为我希望我的.php文件能够上传到根目录并在任何主机帐户上使用。 Because many hosting companies use different file paths to the public_html folder or even call it something different, I'm trying to figure out how to detect it. 因为许多托管公司使用不同的文件路径到public_html文件夹甚至称之为不同的东西,我试图弄清楚如何检测它。

Preferable there is a server variable or easy test to do this. 最好有一个服务器变量或简单的测试来做到这一点。 If not, the public_html folder will always contain a particular file so maybe I could search for this particular file and get the path that way. 如果没有,public_html文件夹将始终包含一个特定的文件,所以也许我可以搜索这个特定的文件,并获得这样的路径。 I'm just worried about a filename search being heavy on memory. 我只是担心文件名搜索内存很重。

The .php file that is being executed is located inside the ROOT directory and needs to locate the public_html folder. 正在执行的.php文件位于ROOT目录内,需要找到public_html文件夹。

Like this: /home/user/file.php 像这样: /home/user/file.php

needs to detect 需要检测

/home/user/public_html/ or /home/user/var/www/ or /home/user/website.com/html/ etc. / home / user / public_html // home / user / var / www //home/user/website.com/html/等。

The challenge with this is that a server can have very many public_html's so outside of the context of a request there is no real way to find out what that is. 这样做的挑战是服务器可以拥有非常多的public_html,因此在请求的上下文之外没有真正的方法可以找出它是什么。

One thing that you might be able to do to get this information from a php script (if you know the url to get to the host) is to create a php file called docroot.php that looks like this. 你可以做的一件事就是从php脚本中获取这些信息(如果你知道要访问主机的url)就是创建一个名为docroot.php的php文件,如下所示。

<?php
    if ($_SERVER["REMOTE_ADDR"] == '127.0.0.1'){
            echo $_SERVER["DOCUMENT_ROOT"]; 
    }

Then within your file.php your would do something like 然后在你的file.php中,你会做类似的事情

$docRoot = trim(file_get_contents("http://www.mydomain.com/docroot.php"));

This makes the assumption that the server can resolve to itself via the local interface by name. 这假设服务器可以通过本地接口按名称解析为自身。

I found this website which provided me with the only good solution I have found after scouring the web... 我发现这个网站为我提供了我在网上搜索后找到的唯一一个很好的解决方案......

$root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", "", $_SERVER['SCRIPT_FILENAME']);

The way this works is by getting the full path of the file and then removing the relative path of the file from the full path. 这种方式的工作方式是获取文件的完整路径,然后从完整路径中删除文件的相对路径。

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

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