Home Backend Development PHP Tutorial PHP获取当前相对于域名目录的方法_php技巧

PHP获取当前相对于域名目录的方法_php技巧

May 16, 2016 pm 08:12 PM
php Table of contents

本文实例讲述了PHP获取当前相对于域名目录的方法。分享给大家供大家参考。具体如下:

http://127.0.0.1/dev/classd/index.php/download
比如这个地址,我想得到红色区域的地址用于生成站内的链接,名为 baseurl。

用 $_SERVER['SCRIPT_NAME'] 就可以了, $_SERVER['SCRIPT_NAME'] 是当前正在访问的PHP文件的相对路径,只要如下稍作处理:

从$_SERVER['SCRIPT_NAME']中获取目录部分,并且替换dirname函数可能出现的反斜杠问题  

复制代码 代码如下:
$baseUrl = str_replace('\\','/',dirname($_SERVER['SCRIPT_NAME']));

保证为空时能返回可以使用的正常值 

复制代码 代码如下:
$baseUrl = empty($baseUrl) ? '/' : '/'.trim($baseUrl,'/').'/';

这样就可以正常获取到 /dev/classd/ 这部分的目录地址了。

顺便看了一下 Zend Framework 的 baseUrl() 函数,结果一看那么一大堆代码就没再继续看了,我就想不通同样的功能他用了一大堆一大堆的代码,从$_SERVER里获取了一堆,然后中间经过两三个类,四五个方法才最终被我们直接调用,除了中间有三行是获取当前的PHP文件以外,其它都是没用和无谓的处理,ZF本身运行的已经够慢的了,这是什么一个意思呢。感兴趣的朋友可以研究一下。

希望本文所述对大家的php程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

CakePHP Date and Time

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

CakePHP Project Configuration

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

CakePHP File upload

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

CakePHP Routing

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

Discuss CakePHP

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP Quick Guide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

How To Set Up Visual Studio Code (VS Code) for PHP Development

See all articles