HandiworkNYC.com
HandiworkNYC.com

Reputation: 11104

Get "Home" Url with PHP

I would like to get the "home" url with PHP. NOT the current URL.

My website exists locally and on a live test server. The URL is being printed as a javascript variable and needs to work in both places (live and local).

The live "home" URL is http://pipeup.pagodabox.com and the local home is http://192.168.0.10:8888/pipeup.

So, if the home page is http://192.168.0.10:8888/pipeup/, if I'm on any subpage, like http://192.168.0.10:8888/pipeup/page.php or http://192.168.0.10:8888/pipeup/about/our-team.php, I would like a variable that returns "http://192.168.0.10:8888/pipeup/" or "http://pipeup.pagodabox.com" depending on if I'm viewing it live or local.

Right now I'm using:

<?php echo 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI']; ?>

But that doesn't work when I'm on a subpage.

How do I get the Home URL with PHP? I would like the solution to also work correctly with a localhost server or local IP address.

Upvotes: 0

Views: 2677

Answers (2)

Cameeob2003
Cameeob2003

Reputation: 482

$directory = "/";

function url($directory = null) {
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    return $protocol . "://" . $_SERVER['HTTP_HOST'] . $directory;
}

define("BASE_URL", url($directory));

I currently use the above from my index.php in an MVC design application. It allows you to set the directory to whatever you want ("/" for your home directory if in the first file presented). Then I just call BASE_URL from any subsequent files in the application. Don't know if it will help you but has not failed me yet!

Upvotes: 1

user1646111
user1646111

Reputation:

I used below code in my application, I hope it help you also.

Note: if you just want to get home, why not just use http://example.com ? this code below provides you current URL

/*
http://www.webcheatsheet.com/PHP/get_current_page_url.php
PHP: How to Get the Current Page URL
    Print   Bookmark and Share

Sometimes, you might want to get the current page URL that is shown in the browser URL window. For example if you want to let your visitors submit a blog post to Digg you need to get that same exact URL. There are plenty of other reasons as well. Here is how you can do that.

Add the following code to a page:
*/
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 //return preg_replace("/\.php.*/", ".php", $pageURL);
 $_SESSION['thisurl'] = $pageURL;
 return $pageURL;
}

Upvotes: 1

Related Questions