php 尝试使用 fopen() 将文件写入不同的目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9837337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to write a file to a different directory using fopen()
提问by user1142872
I'm trying to write a file from one directory to another. For example, http://www.xxxxxxx.com/admin/upload.phpto http://www.xxxxxxx.com/posts/filename.php
我正在尝试将文件从一个目录写入另一个目录。例如http://www.xxxxxxx.com/admin/upload.php到http://www.xxxxxxx.com/posts/filename.php
I've read that I cannot write a file by using the HTTP path, how do I use a local path?
我读到我无法使用 HTTP 路径写入文件,如何使用本地路径?
$ourFileName = "http://www.xxxxxxxx.com/articles/".$thefile.".php";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
回答by diolemo
You should use the absolute or relative path to the file on the file system.
您应该使用文件系统上文件的绝对或相对路径。
<?php
$absolute_path = '/full/path/to/filename.php';
$relative_path = '../posts/filename.php';
// use one of $absolute_path or $relative_path in fopen()
?>
回答by jpic
You can open a file from a directory inside the parent directory of this file using a relative path.
您可以使用相对路径从该文件的父目录内的目录中打开文件。
For example, the relative path to /foo/x
from /foo/y
is ../x
. As you probably figured out, the double dots mean "directory above". So, /foo/../foo/bar
is the same as /foo/bar
. It is safer to use absolute paths in general, as the relative path may depend on the process current directory. Butyou should neverhardcode an absolute path - calculate it instead.
例如,到/foo/x
from的相对路径/foo/y
是../x
。您可能已经知道,双点表示“上面的目录”。所以,/foo/../foo/bar
和 一样/foo/bar
。通常使用绝对路径更安全,因为相对路径可能取决于进程当前目录。但是您永远不应该对绝对路径进行硬编码 - 而是计算它。
So, this should open articles/thefile.php from admin/upload.php:
所以,这应该从 admin/upload.php 打开文章/thefile.php:
// path to admin/
$this_dir = dirname(__FILE__);
// admin's parent dir path can be represented by admin/..
$parent_dir = realpath($this_dir . '/..');
// concatenate the target path from the parent dir path
$target_path = $parent_dir . '/articles/' . $theFile . '.php';
// open the file
$ourFileHandle = fopen($target_path, 'w') or die("can't open file");
You should really get familiar with paths.
你应该真正熟悉路径。
回答by Andreas Hagen
You can always access what is the local path representation of http://www.yourdomain.com/with $_SERVER['DOCUMENT_ROOT'].
您始终可以使用 $_SERVER['DOCUMENT_ROOT']访问 http://www.yourdomain.com/的本地路径表示。
<?php
$f = fopen( $_SERVER['DOCUMENT_ROOT'] . '/posts/filename.php' );
?>