Sign in to follow this  

PHP 'include' a relative file?

This topic is 1961 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm new to PHP and web development in general.

In a PHP file, I have this:
[code]$jg_globalVariables = array();
$jg_globalVariables['common_folder'] = '../../jg-common';
$jg_globalVariables['subsite_folder'] = '../../jg-subsite';

function jg_GetGlobalVar($key)
{
global $jg_globalVariables;
return (isset($jg_globalVariables[$key])) ? $jg_globalVariables[$key] : '';
}[/code]

Then lower down, I do this:
[code]include jg_GetGlobalVar('common_folder') . '/variables.php';
include jg_GetGlobalVar('subsite_folder') . '/variables.php';[/code]

The PHP file with that code is located at:
[i][b]mywebsite.com/wp-content/themes/jamintheme/functions.php[/b][/i]

The files I'm trying to include are located at:
[i][b]mywebsite.com/wp-content/jg-common/variables.php[/b][/i]
and
[i][b]mywebsite.com/wp-content/jg-subsite/variables.php[/b][/i]

The error message I'm getting is:
[color=#008000][i]Warning: include([b]../../jg-common/variables.php[/b]) [function.include]: failed to open stream: No such file or directory in [b]/home/host-user/public_html/mywebsite.com/wp-content/themes/jamintheme/functions.php[/b] on line [b]11[/b][/i][/color]

What am I doing wrong?

I thought if I use '.' or '..' to start off the path, it's relative to the current directory.

Share this post


Link to post
Share on other sites
it is relative to the current working directory, you're using wordpress (atleast it looks that way from the folder names) so the working directory might be the web root, wp-admin , wp-content, or a bunch of other places (i don't think files in the theme folder are ever accessed directly though). (functions.php is included atleast from the root index.php and from wp-admin)
thus the correct path to include is probably 'wp-content/jg-common/variables.php or jg-common/variables.php . or maybe ../jg-common/variables.php'

./ gives you the current working directory , ../ the parent of the current working directory and using nothing gives you the folder of the current file. (This makes it rather easy to have functions.php include files that share its folder, but a real mess to have it include files from its parent folders using relative paths as you can never be quite sure where functions.php is included from)

a few workarounds:

1) store the absolute path to your shared include folder in wp-config and use that to make your includes. (you can include files that aren't in your web root (and it can be a good idea to keep scripts that the user shouldn't access directly outside the webservers folders to avoid accidentially sending them unprocessed to the user in case of a server misconfiguration.
2) use: include get_theme_root() . $pathvariable . '/filename.php'; Edited by SimonForsman

Share this post


Link to post
Share on other sites
Thanks, I didn't understand that the relativity wasn't resolved before it was copy+pasted.

Yea, I'm using WordPress. It seems that this would be a good option:
[code]include( content_url('/jg-common/variables.php') );[/code]

However, this line somehow messes up everything. Nothing gets outputted, not even basic HTML. The entire page is just white, and viewing the generated source shows emptiness - no HTML or anything else - zero lines of code.
Removing that line still generates the code, until the first usage of an unidentified PHP function, and then it stops.

This seems to work though:
[code]include( get_stylesheet_directory() . '/../../jg-common/variables.php' );[/code]

Share this post


Link to post
Share on other sites
Another question is, why ins't my PHP executing in the CSS file?
[CODE]
.LogoBar
{
background: url('<?php echo jg_GetLogoBarBackground(); ?>') left top repeat-x;
width: 100%;
height: 100px;
background-color: yellow;
}
[/CODE]

Does PHP not parse .css files or something?

Does my CSS file has to have hard-coded paths?

Share this post


Link to post
Share on other sites
I haven't done any server side programming in a while either, but as far as I remember cascading style sheets and JavaScript is run on the client side so you can't inject PHP statements inside of these.


Here's an interesting article :

[url="http://sperling.com/examples/pcss/"]http://sperling.com/examples/pcss/[/url]


If you don't like hard-coding values in your CSS I recommend using less.js, it generates normal CSS in the end so not only does it increase productivity, but you can keep your CSS files code tidy on the development side. And during deployment you can simply run the website once and copy the generated CSS and remove all dependencies to less.js if you don't want visitors to have to download the few kb's it's worth.

[url="http://lesscss.org/"]http://lesscss.org/[/url]

Also, it's normally uncommon to resort to such dynamic behavior in CSS. Some big companies use XML parsed CSS to define their style for various websites(That's over-kill though). You can also check out Javascript for modifying the style dynamically. Another option that comes to mind is using Ajax. I've never worked in the web industry, only made 20+ websites as part of my previous CS degree. Edited by DZee

Share this post


Link to post
Share on other sites
[quote name='Servant of the Lord' timestamp='1343867019' post='4965352']
I assumed the PHP would be done server side, and would edit the CSS file that'd then be sent to the client and executed. Does it not work that way?
[/quote]

it can work that way, you can specify in your webserver configuration how it should deal with different file extensions.
if you are using apache you can look for a line that looks like this.
AddType application/x-httpd-php .php
in the config file and just add similar lines for any other extensions you want to be parsed by the php module.

Personally i'd recommend using a separate extension for php generated css files though (.php-css shouldn't be used by anything so that should work) and leave plain css files alone (its unnecessary to pass css files through the php module if they don't contain any php code)

also, remember that file extensions are a windows thing, apache uses a plugin to assign mime-types to files based on their name and can use multiple "extensions" on a single file for different mapping purposes (index.en.php and index.php.en are treated the exact same way by apache, and if you allow users to upload files that you havn't configured mime types for you need to be careful because a file such as image.php.psd will be parsed by the php module if accessed directly (so if you let users upload files you have to either check them properly or prevent direct access to them).

apache also lets you use regular expressions to assign the mimetypes so it is perfectly possible to tell apache that all files with names starting with A, B or C followed by a 2 digit number are php scripts. Edited by SimonForsman

Share this post


Link to post
Share on other sites
Thanks Simon, that sounds great. I'm encountering an error when I try that, however (remember: I'm a complete newbie at anything web-related).

Using cPanel (what my webhost has installed), under "Advanced" I have "Apache Handlers" and "MIME Types" (among other things).

"Apache Handlers" only has this information:
[b]cgi-script[/b] -> [b].cgi .pl .plx .ppl .perl[/b]
[b]server-parsed[/b] -> [b].shtml[/b]

I haven't added anything to that yet.

"MIME types" has a huge number (several hundred) of entries similar to this:
[b]application/x-httpd-php [/b]->[b] php php3 php4 php5 php6
application/x-httpd-php-source [/b]->[b] phps[/b]

So I added my own using the extension you suggested: (a ctrl+find for 'php-css' showed it wasn't being used)
[b]application/x-httpd-php [/b]->[b] php-css[/b]

Since WordPress is looking for and expects a 'style.css', I renamed my old 'CSS with PHP' file to 'style.php-css',
and created a new blank 'style.css' file that looks like this:
[code]@import "style.php-css";[/code]

Then I ran my site again, and instead of my normally broken WIP website, I just got this:
[quote]
[b] Internal Server Error[/b]

The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@[i][b][color=#800000]<name of my website>[/color][/b][/i].com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.[/quote]

I have a file named [b]error_log[/b] in my root www.sitename.com folder. Aside from alot of other errors from yesterday still in the log file, a new log was added:
[i][02-Aug-2012 07:49:14 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /home/blah/public_html/mysite.com/wp-content/jg-common/variables.php:7) in /home/blah/public_html/mysite.com/wp-includes/pluggable.php on line 881[/i]

I don't know if it's related or not - or even if error_log is even the 'server error log' mentioned in the 500 Internal Error message.

[s]Undoing what I previously did, the 500 Internal Server Error still persists.[/s]
The entry was still in the .htaccess folder, despite telling cPanel to remove it, so I manually removed the new mimetype and it resolved the Internal Server Error 500.
How can I get this to work without that error? Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
What I'm doing now is using this to load the stylesheet:
[CODE]
<link rel="stylesheet" type="text/css" media="all" href="<?php echo get_stylesheet_directory() . '/style.php' ?>" />
[/CODE]

Unfortunately, I don't think the file is being parsed as a stylesheet at all and is just being ignored (It's a valid CSS file, the PHP is all contained within quotes so far, so CSS should be able to parse it).

The "[i]<?php echo get_stylesheet_directory() . '/style.php' ?>[/i]" filepath is correct in the resulting PHP generated file, but following it I only get a 404 file not found.

How can I get PHP to process it and [i]then[/i] send it as a CSS file to the user visiting the site? Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
I found this link which may be of some help

[url="http://net.tutsplus.com/tutorials/php/supercharge-your-css-with-php-under-the-hood/"]http://net.tutsplus....under-the-hood/[/url]

I think you need to put <?php header("Content-type: text/css; charset: UTF-8"); ?> in your .php file.

Found a couple more links:

http://css-tricks.com/css-variables-with-php/

http://www.barelyfitz.com/projects/csscolor/ Edited by eFoDay

Share this post


Link to post
Share on other sites
Thanks for all the help guys, it's working well now.

For anyone else banging their head against this in the future, apparently the "[i]<?php header("Content-type: text/css; charset: UTF-8"); ?>[/i]" must be the very first line in the file, even before comments and empty lines ([url="http://php.net/manual/en/function.header.php"]PHP: header[/url]).

I haven't gotten the file to be a .css or .php-css file yet, I'll probably try some more at that tomorrow, but for now it's just a .php.

Another thing of note is that because I'm including it as:
[CODE]<link rel="stylesheet" type="text/css" media="all" href="path/to/my/style.php" />[/CODE]

...and it's being linked, and not PHP include()'d, all my PHP functions and variables aren't included, so I have to within the 'style.php' file call:
[code]<?php include('functions.php'); ?>[/code]
...but my functions.php depends on the WordPress function 'get_stylesheet_directory()' for resolving paths properly, and because the 'style.php' file is being linked, not included, all the WordPress functions are no longer available, so I had to definie my own 'get_stylesheet_directory()' if WordPress' isn't present:
[code]if (!function_exists('get_stylesheet_directory'))
{
function get_stylesheet_directory()
{
return dirname(__FILE__);
}
}[/code]

I really appreciate all the help, gentlemen. It's working perfectly now and it would've taken me probably ten days or more of head-banging instead of just three to figure it all out, and I probably would've given up before then. Edited by Servant of the Lord

Share this post


Link to post
Share on other sites

This topic is 1961 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this