dougan1330 2012-04-03 22:39
浏览 48
已采纳

其中的绝对路径包含localhost

all.

My question is in regards to a problem I'm encountering when trying to add a universal php template for my DOCTYPE section. My DOCTYPE include (aptly entitled doctype.php) lies within the /template directory, and also includes calls pointing to my CSS and JS files that I want to be accessible to all pages.

So the problem is encountered when I try to write the absolute path to these files (the CSS and JS files). Currently, I am trying:

<script type="text/javascript" src="<?php echo $_SERVER['DOCUMENT_ROOT'] . '/file/extension/to/javascript/file.js'; ?>"></script>

and

<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['DOCUMENT_ROOT'] . 'file/extension/to/css/file.css'; ?>"

I am running the application through WAMP on my localhost. Taking a look a look at the source code, it appears as though the links are pointing to the appropriate files (c:/wamp/www/examplesite/path/to/file/file.ext), and all should be well. BUT it is not...

The JavaScript is not accessible and the Stylesheet is not functioning. I'm at a loss for what to do.

I've also tried: -writing the absolute path without the use of PHP -creating PHP variables to hold the document root and then concatenating the appropriate directory path to access the files.

Any suggestions? And how will this change when I upload the directory structure to my online server vs. my current localhost?

  • 写回答

4条回答 默认 最新

  • douwo1862 2012-04-03 23:11
    关注

    You might want to try $_SERVER['HTTP_REFERER'] instead. It gives you the path you are looking for.

    On my local machine, which uses WAMP, I used <?php print_r($_SERVER); ?> to see what values it gives.

    Also, there may be some typos in the snippets. For example, you don't need the leading / in the first example you gave.

    For example:

    <script type="text/javascript" src="<?php echo $_SERVER['HTTP_REFERER'] . 'file/extension/to/javascript/file.js'; ?>"></script>
    <link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['HTTP_REFERER'] . 'file/extension/to/css/file.css'; ?>"></link>
    

    Or since HTTP_REFERER can't be trusted in some case, you may want to create a function that builds the base part of the absolute path.

    <?php
    function getAddress() {
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
        $filenamepattern = '/'.basename(__FILE__).'/';
        return $protocol.'://'.$_SERVER['HTTP_HOST'].preg_replace($filenamepattern,"",$_SERVER['REQUEST_URI']);
     } 
    ?>
    

    Then call it like so:

    <script type="text/javascript" src="<?php echo getAddress() . 'file/extension/to/javascript/file.js'; ?>"></script>
    <link rel="stylesheet" type="text/css" href="<?php echo getAddress() . 'file/extension/to/css/file.css'; ?>"></link>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?