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?
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: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:
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.