【问题标题】:PHP Saving and outputting GD Lib image - relative and absolute pathsPHP保存和输出GD Lib图像 - 相对和绝对路径
【发布时间】:2015-08-26 04:59:18
【问题描述】:

我有一个 php 脚本,它使用 GD Lib 生成图像,并将其保存到预定义的位置。然后应该输出它。

我的目录结构是这样的:

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

在 project-1 目录中,我有这些目录:

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

使用 GD Lib 的脚本位于 /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/

那么解决这个问题最优雅的方法是什么?

【问题讨论】:

    标签: php gd relative-path filepath absolute-path


    【解决方案1】:

    您的问题可能是由于在您的 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 即可更改图像所在的位置,这将适当地影响系统目录和 Web url。

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 2013-07-14
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      相关资源
      最近更新 更多