PHP - Relative path to folder? - php

I am using an MVC codeigniter for a project I am working on. It is running on localhost just find and has a defined base_url='http://localhost/app/.
When running on the local machine, everything is working fine as expected and the images etc have a path that looks like: <link rel="stylesheet" href="http://localhost/app/assets/css/bootstrap.min.css">
The issue I am facing is when I use a VPN on my phone to look at the site. When on my local network, I type in the IP address of the server to load the website. This then causes images / css etc to still try and load from http://localhost and thus does not load them.
Is there a PHP variable that I can use that will get me the path to the folder the files are in? ie. ../../assets/bootstrap.min.css?
I tried using things like $_SERVER["DOCUMENT_ROOT"] but this gives me the full path /var/www/html/app/assets/css/ which again, isn't valid when I try to load this from another source such as my VPN.
How could I go about solving for this? Is this a path issue or something with the server I need to look into?

When you are wanting to collect files within the website you do not need to specify the url.
So if you have a domain whether it be localhost or a fqdn it doesnt matter and makes websites "portable"
Your links/images/script uri's can all be called relatively.
<a href="relative/path/to/file.html">
<img src="path/to/image.jpg">
<link rel="stylesheet" href="path/to/file.css">
<script src="path/to/file.css">
Doing this will overcome the portability issue, you will do the same in php some of the functions require the absolute path and those are documented but many allow you to use relative paths if you need a file from an adjacent directory you would use ../path/to/file etc.
Defining the path constant.
define('ROOTPATH', '/path/to/webroot');
From here I can combine my constant with the relative path wherever needed:
ROOTPATH . '/path/to/file'

I too faced the same issue. There seems to be a problem in the slash between views and html. Instead of back slash it contains forward slash. Work around: go to index.php and stop error logging by defining -1 to 0 as given below according to the environment.
Time being solution/work around:
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(0);
Error message:
Warning: include(D:\xampp\htdocs\IPT\application\views/errors\html\error_php.php)

Related

PHP path issues (localhost and server)

How do you guys handle the path of files to work either localhost and server without changing the variables?
For example, I have this:
$path = realpath($_SERVER["DOCUMENT_ROOT"]);
returns C:\xampp\htdocs
This would probably work on a online server, but doesn't work on a localhost, because I need to set the folder name of my project.
So, in my 100 files (for example) I would have to change to whenever I want to work in localhost:
$path = realpath($_SERVER["DOCUMENT_ROOT"]) . "/myproject/";
So I thought about a variable with a certain condition which would understand if it's localhost or server.
$path = (strpos(realpath($_SERVER["DOCUMENT_ROOT"]), "xampp") == false ? realpath($_SERVER["DOCUMENT_ROOT"]) : realpath($_SERVER["DOCUMENT_ROOT"]) . '/myproject');
And all I had to do:
<link href="<?php echo $path . '/css/bootstrap/bootstrap.css';?>" rel="stylesheet" type="text/css"/>
The above code does not work (at least in localhost, I haven't tried in a real server), because I get the following errors on console:
Not allowed to load local resource:
file:///C:/xampp/htdocs/myproject/css/bootstrap/bootstrap.css
Which I understand, so I have tried to change my $path variable to:
$path = (strpos(realpath($_SERVER["DOCUMENT_ROOT"]), "xampp") == false ? realpath($_SERVER["DOCUMENT_ROOT"]) : 'http://localhost/myproject');
And I get in the console:
Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\myproject\backend\orders.php on line 6
Is there any better way?
The most straightforward approach is to just create a local site with the same folder structure than your live site. I suspect you're doing it that way only because you aren't aware of Apache virtual hosts.
In any case, it's always practical to abstract paths as much as possible and constants are always a good choice. I typically define two:
WEB_ROOT to be used in URLs (in my case it's often just /)
FS_ROOT to be used in file system paths
You can feed them with hard-coded values in a settings file or dynamically calculating them. FS_ROOT is trivial to populate: you can use __DIR__ or dirname(__FILE__) for very old PHP versions.
Surprisingly, $_SERVER["DOCUMENT_ROOT"] does not provide accurate info in all hosting services.
Edit #1: I've appreciated a little base misconception in some of your comments so I'll try to shed some light on it.
Finding stuff on the Internet is not the same as finding stuff in your hard disc. The former makes use of URLs:
http://example.com/blog/latest-news?page=3
The latter makes use of file system paths:
/home/alice/pictures/kitten.jpg
C:\Users\Bob\Desktop\Shopping list.txt
In a web based PHP application you normally need to use both and you need to know the difference. You cannot use a URL to grab random files from a computer (not even yours) and you cannot use a file system path to grab anything from someone else's computer. This:
<link rel='stylesheet' href='C:\xampp\htdocs\myproject/css/bootstrap/bootstrap.css'/>
... is plain wrong because your linking a public resource with a file system path that will only work in your PC.
And one more thing... Most operating systems have adopted the convention to consider . and .. special directory names. That convention has been extended to URLs. But you must handle them as any other path component: it's backend/.. and not backend.. for the same reason that foo/bar is not the same as foobar.
Edit #2: Even if you don't use class auto-loading or the include_path directive, it's trivial to load your application wide settings file, either with absolute paths:
require_once(__DIR__ . '/../conf/configuration.php');
... or relative paths:
require_once('../conf/configuration.php');
IHMO, doing this once per script, in the top level PHP file, is a huge benefit over calculating all application paths every single time you use them.

Change all URLS when Moving from Development to Live

I am sure that this is a repost but I cannot find a question the same as what I want to find out. Essentially, whenever I am working offline, all URIs that I use across the site refer to offline locations eg 127.0.0.1/home.html however, when I go to upload the site, these URIs need to be changed to their equivalents eg example.com/home.html and I either need to go through all of the pages and update these references or use some php to insert the correct address at every point where an address is used. At the minute I am using something like this:
Top of every page:
<?php $offline = false; ?>
Link:
Home
But this seems like a poor way to achieve something which should be relatively simple. What is the standard way of keeping these references up to date. I considered using relative links everywhere but that proved to have problems (for example view includes don't work correctly) and I tried setting the base href to the homepage but that threw up other problems.
Any suggestions would be very much appreciated. Thanks.
$server=$_SERVER['SERVER_ADDR'];
// Local
if(strstr($server,'127.0.0'))
{
define('ROOT_PATH','http://127.0.0.1/');
}
// Server
else
{
define('ROOT_PATH','http://www.yoursite.com/');
}
Put this code in php file and include in every page.
And then:
Home
In this case you can put your files in folder too, for example:
define('ROOT_PATH','http://www.yoursite.com/mysite/');
Another way you could do it is using relative paths.
For files in the same directory you'd use ./ and for files above that directory use ../ This works for anchors in HTML and requires and includes in PHP.
As Waygood suggested, it sounds like you need to change your paths from absolute to either site root relative or relative paths. Example: 127.0.0.1/home.html would become just /home.html if using site root relative. Alternatively, if there's a reason why you must include absolute paths, you can set an environment variable on the server or a PHP constant that indicates the environment type and toggle links based on this value. Using environment variables has the added benefit of being able to keep the exact same code base on your dev and production machines and not having to resort to host or IP detection. Here's an example from zend framework's docs guide that I use:
defined('APPLICATION_ENV') || define('APPLICATION_ENV',
(getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
From: http://framework.zend.com/manual/1.12/en/zend.application.quick-start.html
A neat way that I have found to resolve this issue is to amend your HOSTS file so that it points example.com to 127.0.0.1 so that you can refer to example.com everywhere but be redirected to 127.0.0.1 until your development has finished.

Relative path in a php site on a windows server

I have a PHP enabled windows server, where i have to get a site working.
Its all well and good, the php is working, afaik. But for some reason i can not get relative paths to work in the page header.
I have this folder structure(only relevant folders):
wwwroot/Sitename/
wwwroot/Sitename/Control
wwwroot/Sitename/Images
wwwroot/Sitename/Model
wwwroot/Sitename/View
In IIS i have set the the physical path to wwwroot/Sitename/Control. This loads pages.php(which is located here) which in turn loads wwwroot/Sitename/view/header.php and footer.php.
This works perfectly, however in header.php there are some references to some javascript (and other) files located in wwwroot/Sitename/Model eg.:wwwroot/Sitename/model/js.js
(eg:
<link rel="stylesheet" type="text/css" href="../model/main.css" />
)
This file is not found by the browser when loaded. I am sure it has something to do with the fact that i have set the physical path as i have but this is needed to load pages.php.
Can anyone point me in the right direction? either why the relative path is not working or perhaps another way to set the physical path/something similar.
EDIT: clarifications in parenthesis
use ../ to go down a folder.
Try this in your header.php:
../Model
Why dont you use Absolute urls?
$SiteURL = 'http://www.your_iis_sever.com';
Then in your javascript files use
<?php echo $SiteURL;?>/path/to/js/jscript.js
infront of the links. Make sure its all correct => Check the source code when viewing the page if the paths are correct. From there its easier to navigate.

How do I refer to localhost or my domain name in calls to files?

I've been developing a website, but I develop on my local machine first. I can access this with http://localhost/whatever through my browser, and the actual files are under /var/www/. However, the file system on my web server is structured differently; my files are in the home folder.
I am also beginning to restructure such that I am putting modules in separate folders instead of everything being stuck in one directory. I am therefore looking for a way to refer to my 'base' directory in each case. Given that the structure might change in the future, I want a way to refer to files without having to change those calls after uploading to my live site.
Eg. <link rel="stylesheet" type="text/css" href="style.css">
If I call this from includes/header.php, and then I call includes/header.php from a number of different file locations, it tells me that it does not find style.css for obvious reasons: style.css is not in those folders!
In other words, the goal is some sort of relative pathing that is manageable between two places with different directory structures.
$_SERVER['DOCUMENT_ROOT']
should get the server root path, also below the 'www' folder
A solution that's sometimes used is to store the absolue URL of the root of your website to a variable, once :
$root = 'http://www.yoursite.com';
Two ways to get this :
If you are deploying your application to a quite unusual location, you could set that in your configuration file
Else, this can generally be determines from one of the items in $_SERVER.
Note: Instead of a variable, you might prefer using a constant.
And, then, in all <link>, <script>, ... tags, use that variable to have a correct absolute path :
<link href="<?php echo $root; ?>/css/style.css";
Of course, this means your style.css must remain in the css folder, always -- but it's probably going to be the case, isn't it ?
I think that this post is what you are looking for.

Problems with pointing to files on local server versus remote

I'm having a really silly issue... basically I'm working on a site on a localhost, and a remote host... I am including files by doing the following:
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
This works a treat locally. However on the remote, while its not live, the site address is (pseudo) xxx.xxx.xxx.xxx/~user and so obviously, the js folder is xxx.xxx.xxx.xxx/~user/js/ which means my /js/jquery... include isn't going to work.
Obviously you're thinking I just remove the forward slash at the start of the /js and simply do a relative src - the problem with this is that I'm using mod_rewrite with clean urls, so sometimes when the file which includes the above js src is being called from a few directories deep (or so the computer thinks) ie url.com/blah/blah/blah/ so with a relative src, its going to try url.com/blah/blah/blah/js.
I'm on a php environment and I'm just wondering what the least complex approach to all this is. ie $_SERVER['document_root'] . '/js/jquery....' is something my feeble mind tried but as you the expert probably know - its going to bring up a bunch of irrelevant unix directories and not just go to the current site root.
Any ideas?
When I'm working on various hosts with the same source code, I usually define constants for this sort of thing.
define('SITE_ROOT', '/');
or
define('SITE_ROOT', '/~user/');
Or, you could use this function. I haven't tested it extensively, but it works in the test I just performed. It returns the root relative url with a trailing slash.
function get_root_relative_dir()
{
$root_dir = $_SERVER['DOCUMENT_ROOT'];
$script_dir = dirname($_SERVER['SCRIPT_FILENAME']);
return substr($script_dir, strlen($root_dir)) . '/';
}

Categories