PHP 包含路径

PHP include path

我找到了一个解决方法,但它并不令我满意,因为我不知道为什么会出现这个问题。

在我的网站上,我使用了两个脚本:ScriptA.php 和 ScriptB.php。在 ScriptA.php 我使用

$font = 'img/cert/f1.ttf'; // path to font

在 ScriptB.php 中这会产生一个错误:

PHP Warning:  imagettfbbox(): Could not find/open font in /var/www/vhosts/br-digitalsolutions.eu/httpdocs/partner/scriptB.php

所以我必须使用完整的路径:

$font = '/var/www/vhosts/br-digitalsolutions.eu/httpdocs/partner/img/cert/f1.ttf'; // path to font

使用函数dirname()和魔法常量__DIR__(或者__FILE__,如果你正在使用早于 5.3 的 PHP 版本):

$font = __DIR__.'/img/cert/f1.ttf';

同时检查 this answer (and the comments) on a similar question

如果你这样写你的字体:

$font = "{$_SERVER["DOCUMENT_ROOT"]}/partner/img/cert/f1.ttf";

您应该能够清除该错误。那相当于 /var/www/vhosts/br-digitalsolutions.eu/httpdocs/partner/img/cert/f1.ttf.

$_SERVER["DOCUMENT_ROOT"] 已经指向 /var/www/vhosts/br-digitalsolutions.eu,因此以这种方式指定路径变得更加容易且不易出错。

希望对您有所帮助:)