尝试使用fopen()将文件写入不同的目录

use*_*872 7 php fopen localhost

我正在尝试将文件从一个目录写入另一个目录.例如,http://www.xxxxxxx.com/admin/upload.phphttp://www.xxxxxxx.com/posts/filename.php

我已经读过我无法使用HTTP路径编写文件,如何使用本地路径?

$ourFileName = "http://www.xxxxxxxx.com/articles/".$thefile.".php";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
Run Code Online (Sandbox Code Playgroud)

dio*_*emo 11

您应该使用文件系统上文件的绝对路径或相对路径.

<?php

$absolute_path = '/full/path/to/filename.php';
$relative_path = '../posts/filename.php';

// use one of $absolute_path or $relative_path in fopen()

?>
Run Code Online (Sandbox Code Playgroud)


jpi*_*pic 7

您可以使用相对路径从该文件的父目录内的目录中打开文件。

例如,/foo/x从到的相对路径/foo/y../x。您可能已经发现,双点表示“目录上方”。因此,/foo/../foo/bar与相同/foo/bar。通常,绝对路径更安全,因为相对路径可能取决于进程当前目录。但是,你应该从来没有硬编码的绝对路径-而应计算出。

因此,这应该从admin / upload.php中打开article / 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");
Run Code Online (Sandbox Code Playgroud)

您应该真正熟悉路径