2015-06-10 62 views
0

我有一個使用GD Lib生成圖像的php腳本,將它保存到預定義的位置。然後輸出它。PHP保存並輸出GD Lib圖像 - 相對和絕對路徑

我的目錄結構是這樣的:

www.example.com/projects/project-1/ 

裏面的項目1目錄我有以下目錄:

- /imgs/ 
- /js/ 
- /css/ 
- /php/ 

使用GD庫的腳本是在/php/與另一config.php腳本,其中常量被定義。然後將其包含在主腳本中。

說我有兩個常量:

define('SAVE_PATH', '/projects/project-1/imgs/'); //The image will not save - this does not work 
define('OUTPUT_PATH', '/projects/project-1/imgs/'); //this works if there is an image in this location 

我然後保存圖像,像這樣:

imagejpeg($im, SAVE_PATH.$name, 100); 

我收到以下錯誤:

failed to open stream: No such file or directory in /public_html/projects/project-1/php/main.php 

是否有可能做這隻有一個常數,適用於保存和輸出?

我知道我不能有一個像絕對保存路徑:http://www.example.com/projects/project-1/imgs/

而且我知道我不能有一個像絕對輸出路徑:/public_html/projects/project-1/imgs/

那麼,什麼是最優雅的解決了這個問題?

回答

0

您的問題很可能是由於在您的SAVE_PATH中使用了絕對路徑。絕對路徑從/開始,並且相對路徑不是。這些可能會工作:

define('SAVE_PATH', '../imgs/'); //path relative to the php script, assuming the php file isn't being included from another path 
define('SAVE_PATH', '/public_html/projects/project-1/imgs/'); 

在努力使這種更加靈活,我反而做到以下幾點。設置2個常量,一個用於基本應用程序目錄,另一個用於映像文件夾的路徑。後者將使用與前者用於保存路徑的同時,並會使用它自己的輸出路徑:

//const instead of define is a little prettier, but this is a preference 
const APPLICATION_PATH = '/projects/project-1'; 
const IMAGE_PATH = '/imgs/'; 

//Save the image - Absolute path to the file location 
imagejpeg($im, APPLICATION_PATH.IMAGE_PATH.$name, 100); 

//Echo the image url - Absolute path to the file url 
echo "<img src='".IMAGE_PATH.urlencode($name)."' />"; 

現在,您只需要編輯IMAGE_PATH以更改圖像在何處居住其中將適當地影響系統目錄和網址。