PHP Saving and outputting GD Lib image - relative and absolute paths

468 views Asked by At

I have a php script which generates an image using GD Lib, saves it to a predefined location. And then should output it.

My directory structure is like this:

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

Inside the project-1 directory I have these directories:

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

The script using GD Lib is in /php/ with another config.php script where the constants are defined. This is then included in the main script.

Say I have two constants:

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

I then save the image like so:

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

I get the following error:

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

Is it possible to do this with just one constant that works for both saving and outputting?

I know I can't have an absolute save path like: http://www.example.com/projects/project-1/imgs/

And I know I can't have an absolute output path like: /public_html/projects/project-1/imgs/

So what is the most elegant solution to this problem?

1

There are 1 answers

0
Jerbot On

Your issue is likely due to using absolute pathing in your SAVE_PATH. An absolute path begins with /, and a relative path does not. These will probably work:

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/');

BUT

In efforts to make this more versatile, I would instead do the following. Set 2 constants, one for the base application directory, and one for the path to the image folder. The latter will be usable in conjunction with the former for the save path, and will be usable on its own as the output path:

//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)."' />";

You now only need to edit IMAGE_PATH to make changes to where the images reside which will appropriately affect both the system directory and the web url.