2012-03-23 5 views
5

あるディレクトリから別のディレクトリにファイルを書き込もうとしています。たとえば、http://www.xxxxxxx.com/admin/upload.phphttp://www.xxxxxxx.com/posts/filename.phpfopen()を使用して別のディレクトリにファイルを書き込もうとしています

HTTPパスを使用してファイルを書き込むことはできません。ローカルパスはどのように使用しますか?

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

答えて

8

ファイルシステムのファイルへの絶対パスまたは相対パスを使用する必要があります。

<?php 

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

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

?> 
+0

ありがとうございました。 – user1142872

+0

@ user1142872これは答えとしてマークする必要があります。 –

3

あなたは相対パスを使用して、このファイルの親ディレクトリ内のディレクトリからファイルを開くことができます。

たとえば、/foo/xから/foo/yへの相対パスは、../xです。おそらく分かっているように、二重の点は「上のディレクトリ」を意味します。したがって、/foo/../foo/bar/foo/barと同じです。相対パスはプロセスの現在のディレクトリに依存する可能性があるので、一般的に絶対パスを使用する方が安全です。 しかし、あなたは決して絶対パスをハードコードする - 代わりにそれを計算してください。

だから、これは管理者/ 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"); 

あなたは本当にpathsに慣れる必要があります。

+0

詳細情報をありがとう! – user1142872

+0

いつでも! [質問を閉じる](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)を忘れないでください。 – jpic

2

あなたは常に$ _SERVER [「DOCUMENT_ROOT」]とhttp://www.yourdomain.com/のローカルパス表現が何であるかをアクセスすることができます。

<?php 
$f = fopen($_SERVER['DOCUMENT_ROOT'] . '/posts/filename.php'); 
?> 
関連する問題