2

Let's say I have this directory structure:

myApp
|____files
|
|__myFolder
|      |___script1.php
|
|__script2.php
|___myClass.php

script1.php and script2.php are identical, and all they do is instantiate myClass, put a file in the files folder, and print out an HTML anchor link to that file.

//script1.php and script2.php:

/*require myClass*/

$myClass = new myClass();
$myClass->copyFile();
$link = $myClass->retHref();
echo '<a href="'.$link.'">Click here</a>

Currently I am doing this in myClass.php, to get the absolute path and href:

//myClass.php

class myClass{

    public function copyFile()
    {
        $absPath = dirname(__FILE__).'/files/file.txt';
        //code to copy the file
    }

    public function retHref()
    {
        return $_SERVER['HTTP_REFERER'].'/files/file.txt';
    }

}

Is this the best way to go about this, or is there a better way to

a) Get a file path

and

b) Create a web link

from inside a class, when I don't know where the script will live that instantiates the class and calls its functions?

symlink
  • 11,984
  • 7
  • 29
  • 50
  • `$_SERVER['HTTP_REFERER']` is not reliable but it is very simple to use. Unfortunately there is always a chance that the client doesn't set the `Referer` header. So if the result is NOT critical, and you don't mind it if you sometimes get no link, then this approach is fine. But in any case where that link is required to be available and accurate, I would follow the suggestion in the answer from atymic. – Oloff Biermann Jul 23 '19 at 00:35

1 Answers1

2

You can use the __DIR__ constant to generate an absolute path to the files directory. In terms of creating a href link, it's a bit more complex. I used the code from this answer in the example below:

class myClass
{

    const FILE_DIRECTORY_PATH = __DIR__.'/files/file.txt';

    public function copyFile()
    {
        $pathToFile = self::FILE_DIRECTORY_PATH;
        //code to copy the file
    }

    public function retHref()
    {
        return $this->urlOrigin($_SERVER).'/files/file.txt';
    }

    private function urlOrigin($s, $use_forwarded_host = false)
    {
        $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on');
        $sp = strtolower($s['SERVER_PROTOCOL']);
        $protocol = substr($sp, 0, strpos($sp, '/')).(($ssl) ? 's' : '');
        $port = $s['SERVER_PORT'];
        $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':'.$port;
        $host = ($use_forwarded_host && isset($s['HTTP_X_FORWARDED_HOST'])) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
        $host = isset($host) ? $host : $s['SERVER_NAME'].$port;
        return $protocol.'://'.$host;
    }
}
atymic
  • 3,093
  • 1
  • 13
  • 26