How to map file path from different folder location easily?

被刻印的时光 ゝ 提交于 2019-12-11 16:15:27

问题


how to map the path to the file easily?

public_html/api/function.php
<?php

function writetologfile($content)
{

    $filename = 'logfile/testing_randomstring.txt';

    if (!$handle = fopen($filename, 'a')) 
    {
        echo "Cannot open file ($filename)";
        exit;
    }
    fclose($handle);    
}

?>

the actual path of the text file is in public_html/r/admin/logfile/testing_randomstring.txt

so if I run the script at public_html/folder1/folder2/addlog.php, it won't be able to find the path to the testing_randomstring.txt

addlog.php
<?php

include("../../api/function.php");

writetologfile('hahaha');

?>

How I can able to easily point to this text file path, no matter where my php calling script is from.

I tried to change $filename = 'logfile/testing_randomstring.txt'; inside writetologfile function by enforcing it to absolute fix path, something like $filename='/r/admin/logfile/testing_randomstring.txt', but it is not working


回答1:


Instead of using a relative path, you could specify an absolute path. Assuming public_html is in your home directory, try this:

$filename = '/public_html/r/admin/logfile/testing_randomstring.txt';
fopen(getenv('HOME') . $filename, 'a');

This uses getenv to read the contents of the environment variable $HOME.



来源:https://stackoverflow.com/questions/1577257/how-to-map-file-path-from-different-folder-location-easily

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!