简体   繁体   中英

Equivalent of asp.net's ResolveUrl in php

In my apache www dir, I have subdirectory for different personal projects I work on. Ex:

www/webApp1 www/webApp2

I access to webApp2 by http://localhost:81/webApp2 (I currently run a portable wamp, that's why I'm on port 81. It does not matter right now...)

I'm not using virtual host here, maybe I should, but I don't know much about it.

So for my webbApp2, I have the file util/files.php with the following function:

function BaseUrl ()
{
    $baseDir = dirname(dirname(__FILE__));
    $pos = strrpos($baseDir, '\\');
    if (!$pos)
    {
        $pos = strrpos($baseDir, '/');
    }
    $theDir = substr ($baseDir, $pos + 1);
    if ($theDir == 'public_html')
    {
        $theDir = '~johnny5'; //Hmmmmm...
    }
    return 'http://'.$_SERVER["HTTP_HOST"].'/'.$theDir;
}

I can call this method from any php file to "resolve" an url.

require_once("util/files.php");
$myUrl = BaseUrl ().'/someFolderAtTheRootOfWebApp2/myfile.css';
$css = $baseUrl.'/css/tab.css';

Then $css is "http://localhost:81/webApp2/someFolderAtTheRootOfWebApp2/myfile.css" . That way I can generate dynamically the links to my css or javascript files, for example.

In asp.Net, I would write string url = Page.ResolveUrl ("~/folder/file.css"); .

It does works, but I wonder if there is a more elegant way to do this. Maybe there's something built-in in php to handle that. And more important, you can see the patch with public_html to handle my userdir when I run the app under my Linux box. That's not really portable.

Any suggestions?

What exactly do you want to do? Get an absolute url for a file? If so you have to do the logic yourself - as php is not really integrated into apache is has no idea of your server structure.

Is it a good idea to use ini_set and ini_get in this case?

ini_set('include_class_path', 'http://'.$_SERVER["HTTP_HOST"]."/Project/lib/");
ini_set('include_controls_path', 'http://'.$_SERVER["HTTP_HOST"].'Project/controls/');
echo $get = ini_get('include_class_path');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM