Home » Php » php – Trying to write a file to a different directory using fopen()

php – Trying to write a file to a different directory using fopen()

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m trying to write a file from one directory to another. For example, http://www.xxxxxxx.com/admin/upload.php to 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?

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

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()

?>

Answer:

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. But you should never hardcode an absolute path – calculate it instead.

So, this should open articles/thefile.php from admin/upload.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.

Answer:

You can always access what is the local path representation of http://www.yourdomain.com/ with $_SERVER[‘DOCUMENT_ROOT’].

<?php
$f = fopen( $_SERVER['DOCUMENT_ROOT'] . '/posts/filename.php' );
?>