Change all URLS when Moving from Development to Live - php

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.

Related

PHP - Relative path to folder?

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)

Detect virtual host or localhost/subdir from PHP?

I'm trying out a lot of PHP example projects. For most examples I need to setup a VirtualHost in the Apache config (httpd-vhosts.conf) to get them working.
But sometimes I just want to copy or test a project, without going through the hassle of making another VirtualHost.
It would be nice if everything still works too when I try http://localhost/ProjectDir/ instead of http://ProjectDir/
In Phalcon I know how to fix the root directory, by changing the config or with setBaseUri(), but this is a bit inconvenient to change every time. It would be nice if this could be done automatically somehow. (I do realize that in this way I can not use absolute URLs or links inside the HTML (starting with /) since that would mean the root folder of the Apache server then but this could be solved with an automatically configured prefix-variable).
How do other developers handle this situation, or do you really choose between a virtual host or http://localhost/ProjectDir/ ?
Is there a way for a PHP script to detect if it's running in a
virtual host or in a subdir of localhost?
UPDATE
Found out I could use $_SERVER['SERVER_NAME'] to determine if it's 'localhost' or something else. Not very elegant, but it's a sufficient solution, I guess.
Within html views:
I like to use absolute paths from the document root for ease. (Relative paths are flexible but can get complicated.)
<img src="/images/foo.jpg">
Of course if I want to move the project into a sub directory, the path above will need to be adjusted. (We could use the html base tag, but that can have side effects.):
<img src="/subdir/images/foo.jpg">
We could use a variable in our views that we prefix to links and asset paths:
<?php
$base = '/subdir'; // Set somewhere.
?>
<img src="<?php echo $base ?>/images/foo.jpg">
To set the $base variable automatically, I sometimes assign it to Symfony/Component/HttpFoundation/Request::getBasePath(). (There are some other useful utility methods in that component.) Or use something similar from another framework/library/component.
Assigning a value in one place in a central configuration isn't that much of a hardship. I find prefixing paths within the views more of a pain.
In one of my development environments, I use a symlink from the directory root to the project directories directory root:
/var/www -> /sites/example.com/pub
And swap it as and when needed. You can avoid writing multiple virtual host configs that way and skip the other steps mentioned above.
However, configurable prefixes can be useful in other ways:
$base_cdn = 'http://cdn.example.com';
$base_nav = '/subdir';
$base_static = '//static.example.com/foo';
assuming the entry is index.php
function getVirtualHostPath(): string
{
$temp = str_replace("index.php", "", $_SERVER["SCRIPT_NAME"]);
return substr($temp, 1);
}
// "https://domain.example/subdir/api/v2/store/inventory" => "subdir/"
// "https://domain.example/api/v2/store/inventory" => ""
// "https://domain.example/subdir/api/v2/store/inventory" => "subdir/"
// "https://127.0.0.1/api/v2/store/inventory" => ""
Explanation:
dump $_SERVER super global in production (that uses virtual hosts) and filter out all keys that does not contain "subdir".
filter out all keys that are not present in CGI 1.1 specification
copy the same keys from development environment without virtual host.
$_SERVER["SCRIPT_NAME"] contains "/subdir/index.php" in prod and "/index.php" in dev. Removing "index.php" will return the virtual host path.

readfile from a partial url or something like that

First, I know basically zero php, I usually do jsp but I have to modify a footer for a wordpress site we have.
The site currently is hosted at www.mysite.com/wordpress and has the following line:
<?php readfile('http://www.mysite.com/css-imports.jsp'); ?>
and because I am doing this on development I keep having to change it to:
<?php readfile('http://local.mysite.com/css-imports.jsp'); ?>
When I do that the wordpress url is local.mysite.com/wordpress.
How can I from php insert local.mysite.com or www.mysite.com based on the domain that is serving the page?
Thanks.
You need a base URL variable (of which I'm certain Wordpress will have one, most frameworks do). Have a look at this answer here.
Hard coding a domain in like that when it relates to your server is not a good idea, because as soon as you move your code - breaky breaky. So to use their example, you'd do something like this:
<?php readfile(get_bloginfo('wpurl') . '/css-imports.jsp'); ?>
Might need a bit of playing around with, have a look at the Wordpress Dev Docs and find something that suits you if this doesn't:
http://codex.wordpress.org/Function_Reference/get_bloginfo
http://codex.wordpress.org/Function_Reference/home_url
You could set up a simple config file that will differ between the local and production servers. All you'll need to do is make sure the local copy doesn't get included when new code is pushed to the server.
Local copy of serverconfig.php:
<?php
define('SITE_HOSTNAME','http://local.mysite.com/');
?>
Off-site copy of serverconfig.php:
<?php
define('SITE_HOSTNAME','http://www.mysite.com/');
?>
Everything else will just need to include the config file and reference the constant(s) defined in it.
<?php
require_once 'serverconfig.php';
... code ...
readfile(SITE_HOSTNAME. 'css-imports.jsp');
?>
Note: if you're just reading static files that are located on the same webserver, you should just reference the local files, readfile('/css-imports.jsp');.
I usually just end up modifying my hosts file. I work with too many disparate customer systems locally (including WordPress and Drupal) and it seems like every system I've seen has templates/themes/plugins that don't reference the framework's base url variables, or uses hard-coded absolute paths, or uses relative paths that don't jive well with my server, or just something.
When you're done developing and need to load it into production, just comment out the hosts entry.
/etc/hosts
# map mysite.com to local host for dev reasons.
www.mysite.com 127.0.0.1
I think this will do the try for me
$_SERVER[HTTP_HOST]

How to use a PHP includes across multiple directories/sub directories with relative paths

I'm having difficulty with paths in a cms system I'm attempting to build, I've basically got a folder with my header.php and footer.php files inside.
These are included in index.php and work fine. But then when I attempt to use the same includes in a file within my admin sub directory, the images and CSS are broken, obviously because the relative path is now wrong.
So my question is, how can I overcome this?
After reading some of the other questions on here and various other sources, I think absolute paths are the way forward, but I've always used relative paths, so the various concepts of using config files to specify an absolute path are confusing me.
I usually manage to work things out for myself, but it's been a long day and Im stumped!
i usualy have a file called config in my application root and in it i define a constant for base path and a few others:
define('APP_BASE_PATH', dirname(__FILE__));
define('APP_FUNCTIONS_PATH', APP_BASE_PATH . '/functions');
and i include my files like
include (APP_BASE_PATH . 'includes/another_file.php');
include (APP_FUNCTIONS_PATH . '/function_file.php');
that way i can place my aplication in whatever directory, plus i can move files around without to much worries.
also using full path makes the include faster
I prefer setting the environment variables (in Apache, using .htaccess or the .conf). This way you can move all your files freely anywhere in webroot and it will have access to those variables.
SetEnv lib /library/folder/
SetEnv public /my/web/root/
SetEnv environ DEVELOPMENT
Also you can use the variable named 'environ' mentioned in the above .htaccess snippet to include a server specific file as config file in all of your scripts and set various variables there.
require_once getenv('lib')."Configs/Config_".getenv('environ').".php";
Enjoy your freedom!
or...
include($_SERVER['DOCUMENT_ROOT'] .'/includes/header.php');
Relative and absolute paths in PHP are a bit fragile because they depend not just on the current directory of the including file, but also the current working directory.
So you need a two-part solution.
Firstly, you need a redirector. Basically, this is an include file that serves as a single-point-of-call for all other pages. Its job is to go and include the rest of your infrastructure. All your pages call this redirector and only this redirector (but you can chain them).
This redirector now does
include_once dirname(__FILE__).'/include/include.php';
This lets you change your infrastructure's include file, or location and all you have to update is one file. The dirname() call solves all the relative and absolute problems and has it look for the next step relative to itself. And by definition this only changes when you change it, so it will always work.
The second part is a custom includer so you can call content by name with a function and it goes and gets the right file. Burying this in your infrastructure directory is where is goes. It then becomes a black-box that the pages outside this area call without knowing and without needing to know how it works or where it is. That removes the need for path constants to include page fragments because you have one place doing it all for you.
I have had this similar issue and posted this query in this link in SO. The URL is : Issue with PHP include with global path.
While working on the solutions given by people and looking at various threads (including this one - which I had quoted in my solution at the bottom section of my post), I had a way! I had posted the solution as well. It may help some one who is facing a similar issue.

Absolute Relative path issues in referencing web assets - need help - php related

Hi guys I'm in a bit of a pickle here now. Well to start with I built a simple CMS in PHP with an admin panel the directory structure is like this:
root/
->admin/
->images/
It worked fine as is however the client requirements changed and they wanted that instead of having to access the admin folder as a folder within the root it be accessed as a web subdomain. so www.site.com/admin becomes admin.site.com
However this has terrible messed up and destroyed practically all the referencing I had done. Like I upload images on the CMS - however now uploading on ../images doesn't work as its now under a subdomain and I'm all messed up in trying to relatively reference images from there too. I've been trying to hack away at my config file for weeks and can't get to fix this :( - help please - on the front end the site is o.k. but my admin section is all messed up :(
I'm using PHP and MySQL.
Sounds like you've learned how toxic relative paths can be.
Possible quick fix: what happens if you copy/symlink/alias admin.domain.com/images to point at the same images folder that lives on your front-end site? I think that extra "../"es will basically be ignored.
More permanently, and in general, don't use relative paths. They will cause you nothing but pain. A couple of strategies:
1) Define some constant that points at the right location for images, css, etc:
define('IMG_DIR','/images');
define('CSS_DIR','/images');
// ... some time later
echo '<img src="' . IMG_DIR . '/myimage.jpg'"/>';
2) Much better: just maintain one constant that tells you where your application lives.
define('APP_ROOT','/myapp'); //could be chanted to just '/' if it doesn't live in some folder on the server
// ... later that day ...
echo '<img src=\"' . APP_ROOT . '/images/myimage.jpg"/>';
// ... or maybe you need to link to a logout script?
echo 'Log Out';
It's important to assume you application might need to run from the root ("/") or some directory on the server, etc.
The same goes for any filesystem operations you might do purely on the server side. Use absolute filesystem paths. If your main application has a script like "config/config.php", you could stick this at the top:
define('APP_FS_ROOT',realpath(dirname(__FILE__) . '/..'));
Assuming both the frontend and the admin are on the same file system, you will need to use absolute paths for everything in the admin. In the admin's config create a define that maps to the frontend's physical upload/image folder. For example, from the fontend you can access uploads folder with the relative path ./upload but from the admin.example.com site you will be required to use the absolute path /user/example.com/upload.
The fontend's config would look like (www.site.com/config.php):
define("UPLOAD_FOLDER", "./uploads");
define("WEB_UPLOAD_FOLDER", "/uploads");
The admin's config would look like (admin.site.com/config.php):
define("UPLOAD_FOLDER", "/user/site.com/upload");
define("WEB_UPLOAD_FOLDER", "http://www.site.com/uploads");
Then both the frontend and admin would reference the physical folder with:
$filename = UPLOAD_FOLDER . "/myupload.mp3";
And to create hyperlinks to the upload you would use this:
My Upload
Another possible solution would be to define a directory alias in apache for the directories you've moved.
Lets say your sub domain root is
/subdomains/images
<VirtualHost>
...
Alias /images "/subdomains/images"
...
</VirtualHost>
Both www.yourDomain.com/images and images.yourDomain.com would load the same files.
Or, if your using linux, a symlink could accomplish the same thing.

Categories