Home > Mobile >  php write file path from two different location
php write file path from two different location

Time:03-02

I have a php class used to manage write/read/delete files. The constructor receives the path (string) of the file. Basically something like:

class customFile{
    public function __construct($path){
        $this->path=$path;
    }

    public function write($content){
        //use fopen and fwrite to write content
    }
    public function read(){
        //use fopen and fgets to read content
    }
    public function delete(){
        //use unlink to delete the file
    }
}

Also I have this directory tree

├─ root/
│  ├─ helpers/
│  │  ├─ customFile.php
│  ├─ dir1/
│  │  ├─ function1.php
│  ├─ tempDir/
│  ├─ function2.php
│  ├─ useCustomFileFunction.php

Is very important to say that useCustomFileFunction.php is in charge of writing the files in the tempDir, so that function create a customFile object with a path like this "./tempDir/" someName (for example "./tempDir/writtenFile.txt).

both function1.php and function2.php call useCustomFileFunction with some file name (to write some files) but when the function is called from function1.php the result is (incorrect):

├─ root/
│  ├─ helpers/
│  │  ├─ customFile.php
│  ├─ dir1/
│  │  ├─ function1.php
│  │  ├─ tempDir/
│  │  │  ├─ writtenFile.txt
│  ├─ tempDir/
│  ├─ function2.php
│  ├─ useCustomFileFunction.php

and when is called from function2.php, the result is (correct):

├─ root/
│  ├─ helpers/
│  │  ├─ customFile.php
│  ├─ dir1/
│  │  ├─ function1.php
│  ├─ tempDir/
│  │  ├─ writtenFile.txt
│  ├─ function2.php
│  ├─ useCustomFileFunction.php

So the question is: Is there a way to tell fwrite, that the path begin from the class/that call fwrite? (customFile1.php or useCustomFileFunction.php instead of function1.php and function2.php)

CodePudding user response:

function1.php should use customFile class with ../tempDir path.It's a better way to use the __FILE__ or __DIR__ for addressing.

So let's struct the project this way:

├─ root/
│  ├─ config/
│  │  ├─ config.php
│  ├─ helpers/
│  │  ├─ customFile.php
│  ├─ dir1/
│  │  ├─ function1.php
│  ├─ tempDir/
│  ├─ function2.php
│  ├─ useCustomFileFunction.php

And we can have this code in config.php file:

<?php

define("TEMP_DIR" , dirname(__DIR__) . "/tempDir/");

And we include the config.php in function1.php this way:

require(__DIR__ . "/../config/config.php");

And this way in function2.php:

require("config/config.php");

Now you can use the TEMP_DIR Constant to address the tempDir folder.

CodePudding user response:

You can find the absolute path to the temp folder using

$temp_path = sys_get_temp_dir();

Then have your file writers use this absolute path.

  • Related