I have multiple pages that are used to pull metadata for facebook, however they are linked to a page that is to be hidden from the public. The url that is to not be seen is:
test.local/university/test_name
The above link should redirect to:
test.local/content/university
Is there any way I can do this with a RewriteRule in htaccess? Or does it need to be done via a PHP redirect?
Apologies if duplicate.
Update:
This is how I resolved this problem.
$domain = $_SERVER["HTTP_HOST"];
$uri = $_SERVER["REQUEST_URI"];
$url = "http://".$domain . $uri;
$parsedURL = parse_url($url);
// search regex
$regex = "(^\/[\d]+-(.*?)/)";
// get the matched part of the url
if (strpos($_SERVER['HTTP_REFERER'], 'facebook.com') !== false) {
if (preg_match($regex, $parsedURL['path'], $matches) === 1) {
$url = $parsedURL['scheme'] . "://" . $parsedURL['host'] . "/content" . $matches[0];
header('Location: ' . $url);
}
}
Try something like this...
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^test.local/content/university$ path/to/real/page.php [NC,L]
Hope this helps.
You can use this RedirectMatch rule in your site root's .htaccess:
RedirectMatch 301 ^/(university)/[\w-]+ /content/$1
cheers for your input. I done this in via PHP in the end.
$domain = $_SERVER["HTTP_HOST"];
$uri = $_SERVER["REQUEST_URI"];
$url = "http://".$domain . $uri;
$parsedURL = parse_url($url);
// search regex
$regex = "(^\/[\d]+-(.*?)/)";
// get the matched part of the url
if (strpos($_SERVER['HTTP_REFERER'], 'facebook.com') !== false) {
if (preg_match($regex, $parsedURL['path'], $matches) === 1) {
$url = $parsedURL['scheme'] . "://" . $parsedURL['host'] . "/content" . $matches[0];
header('Location: ' . $url);
}
}
Related
I have this function.
function getCallbackUrl(){
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . 'response.php';
}
On my URL http://localhost/gateways/payu/index.php the above function displays URL like this http://localhost/gateways/payu/index.phpresponse.php. No idea why it is happening. The function seems correct to me. Maybe I am missing out something that I am not able to replace the base name from index.php to response.php. Any help would be truely appreciated. Thank you :)
Currently, your $_SERVER['REQUEST_URI'] itself has index.php, hence you are facing this issue, where response.php is concatenated instead of replacing. A quick fix is as below:
$_SERVER['REQUEST_URI'] = str_replace(basename($_SERVER['REQUEST_URI']),'response.php',$_SERVER['REQUEST_URI']);
return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
You can also use a combination of parse_url(),str_replace() and basename() to achieve this.
Parse the url and get the URI path.
Get the basename of the URI.
Replace it with the one you want to.
Join these pieces together and return the URL.
Snippet:
<?php
function getCallbackUrl($url,$replacement_file){
$url_data = parse_url($url);
$url_data['path'] = str_replace(basename($url_data['path']),$replacement_file,$url_data['path']);
$url = $url_data['scheme'] . "://" . $url_data['host'] . $url_data['path'];
if(!empty($url_data['query'])) $url .= '?' . $url_data['query'];
return $url;
}
echo getCallbackUrl('http://localhost/gateways/payu/index.php','response.php');
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
For example with the function above, it works fine if I work with the same directory, but if I make a sub directory, and work in it, it will give me the location of the sub directory also for example. I just want example.com but it gives me example.com/sub if I'm working in the folder sub. If I'm using the main directory,the function works fine. Is there an alternative to $_SERVER['HTTP_HOST']?
Or how could I fix my function/code to get the main url only? Thanks.
Use SERVER_NAME.
echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
You could use PHP's parse_url() function
function url($url) {
$result = parse_url($url);
return $result['scheme']."://".$result['host'];
}
Shortest solution:
$domain = parse_url('http://google.com', PHP_URL_HOST);
/**
* Suppose, you are browsing in your localhost
* http://localhost/myproject/index.php?id=8
*/
function getBaseUrl()
{
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
// return: http://localhost/myproject/
return $protocol.'://'.$hostName.$pathInfo['dirname']."/";
}
Use parse_url() like this:
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
}
Here is another shorter option:
function url(){
$pu = parse_url($_SERVER['REQUEST_URI']);
return $pu["scheme"] . "://" . $pu["host"];
}
Step-1
First trim the trailing backslash (/) from the URL. For example, If the URL is http://www.google.com/ then the resultant URL will be http://www.google.com
$url= trim($url, '/');
Step-2
If scheme not included in the URL, then prepend it. So for example if the URL is www.google.com then the resultant URL will be http://www.google.com
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
Step-3
Get the parts of the URL.
$urlParts = parse_url($url);
Step-4
Now remove www. from the URL
$domain = preg_replace('/^www\./', '', $urlParts['host']);
Your final domain without http and www is now stored in $domain variable.
Examples:
http://www.google.com => google.com
https://www.google.com => google.com
www.google.com => google.com
http://google.com => google.com
2 lines to solve it
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$myDomain = preg_replace('/^www\./', '', parse_url($actual_link, PHP_URL_HOST));
/* Get sub domain or main domain url
* $url is $_SERVER['SERVER_NAME']
* $index int remove subdomain if acceess from sub domain my current url is https://support.abcd.com ("support" = 7 (char))
* $subDomain string
* $issecure string https or http
* return url
* call like echo getUrl($_SERVER['SERVER_NAME'],7,"payment",true,false);
* out put https://payment.abcd.com
* second call echo getUrl($_SERVER['SERVER_NAME'],7,null,true,true);
*/
function getUrl($url,$index,$subDomain=null,$issecure=false,$www=true) {
//$url=$_SERVER['SERVER_NAME']
$protocol=($issecure==true) ? "https://" : "http://";
$url= substr($url,$index);
$www =($www==true) ? "www": "";
$url= empty($subDomain) ? $protocol.$url :
$protocol.$www.$subDomain.$url;
return $url;
}
Use this code is whork :
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
$urlParts = parse_url($url);
$url = preg_replace('/^www\./', '', $urlParts['host']);
This works fine if you want the http protocol also since it could be http or https.
$domainURL = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
Please try this:
$uri = $_SERVER['REQUEST_URI']; // $uri == example.com/sub
$exploded_uri = explode('/', $uri); //$exploded_uri == array('example.com','sub')
$domain_name = $exploded_uri[1]; //$domain_name = 'example.com'
I hope this will help you.
Tenary Operator helps keep it short and simple.
echo (isset($_SERVER['HTTPS']) ? 'http' : 'https' ). "://" . $_SERVER['SERVER_NAME'] ;
If you're using wordpress, use get_site_url:
get_site_url()
I'm trying to figure out how to check if the referral url to one of my inner pages is the homepage. This would be easy if the homepage was always www.mysite.com/index.php but what happens when it's simply www.mysite.com?
I know I could simply do
$url = $_SERVER['HTTP_REFERER'];
$pos = strrpos($url, "/");
$page = substr($url, $pos+1, (strlen($url)-$pos+1));
if (substr_count($url, 'index')) echo 'from index ';
but I don't have the index.php in my $url variable.
parse_url() can help you here.
// An array of paths that we consider to be the home page
$homePagePaths = array (
'/index.php',
'/'
);
$parts = parse_url($_SERVER['HTTP_REFERER']);
if (empty($parts['path']) || in_array($parts['path'], $homePagePaths)) echo 'from index';
N.B. This should not be relied upon for anything important. The Referer: header may be missing from the request, and can easily be spoofed. All major browsers should do what you expect them to, but hackers and webcrawlers may not.
Use this
if($_SERVER["REQUEST_URI"] == "/" || $_SERVER["REQUEST_URI"] == "/index.php")
echo "Home";
$url = parse_url($_SERVER['HTTP_REFERER']);
$url = explode('/',$url['path']);
if ($url[1]=='index.html'||empty($url[1])) echo 'from index ';
$referer = $_SERVER['HTTP_REFERER'];
$homepage = "index.php";
$ref_array = explode("/", $referer);
if(trim($ref_array[1]) == trim($homepage) || trim($ref_array[1]) == "") echo "From URL";
You should note that yoursite.com/index.php and yoursite.com/ is the same!
This would work:
if ($_SERVER['REQUEST_URI'] == '/')
This is my url:
http://localhost/framework/index.php
echo $_SERVER['REQUEST_URI'];
Would output: /framework/index.php
But If my url was:
http://localhost/framework/
The output would be:
/framework/
And If I move the file, yeah you get the idea.
How do I grab the content after folders/eventually index.php file? My idea is to have index.php as a front controller.
If I have:
http://localhost/framework/index.php/test/test
I only want the test/test part.
http://localhost/framework/test/test
I only want the test/test part.
You can automatically detect the base uri and remove it, leaving you with the test/test part.
if(!empty($_SERVER['PATH_INFO']))
{
// Uri info does not contain docroot or index
$uri = $_SERVER['PATH_INFO'];
}
else
{
if(!empty($_SERVER['REQUEST_URI']) && !empty($_SERVER['HTTP_HOST']))
{
$fullUrl = 'http://'
. ((isset($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : '')
. ((isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '');
$uri = parse_url($fullUrl, PHP_URL_PATH);
}
else if(!empty($_SERVER['PHP_SELF']))
{
$uri = $_SERVER['PHP_SELF'];
}
}
$baseUri = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/")+1);
$uri = str_replace($baseUri, '', $uri);
Edit: mAu's comment above is correct. I was under the assumption you was already using mod rewrite.
How can I add http:// to a URL if it doesn't already include a protocol (e.g. http://, https:// or ftp://)?
Example:
addhttp("google.com"); // http://google.com
addhttp("www.google.com"); // http://www.google.com
addhttp("google.com"); // http://google.com
addhttp("ftp://google.com"); // ftp://google.com
addhttp("https://google.com"); // https://google.com
addhttp("http://google.com"); // http://google.com
addhttp("rubbish"); // http://rubbish
A modified version of #nickf code:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.
At the time of writing, none of the answers used a built-in function for this:
function addScheme($url, $scheme = 'http://')
{
return parse_url($url, PHP_URL_SCHEME) === null ?
$scheme . $url : $url;
}
echo addScheme('google.com'); // "http://google.com"
echo addScheme('https://google.com'); // "https://google.com"
See also: parse_url()
Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.
if (false === strpos($url, '://')) {
$url = 'http://' . $url;
}
Note: This may be a simple and straightforward solution, but Jack's answer using parse_url is almost as simple and much more robust. You should probably use that one.
The best answer for this would be something like this:
function addhttp($url, $scheme="http://" )
{
return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}
The protocol flexible, so the same function can be used with ftp, https, etc.
Scan the string for ://. If it does not have it, prepend http:// to the string... Everything else just use the string as is.
This will work unless you have a rubbish input string.
Try this. It is not watertight1, but it might be good enough:
function addhttp($url) {
if (!preg_match("#^[hf]tt?ps?://#", $url)) {
$url = "http://" . $url;
}
return $url;
}
1. That is, prefixes like "fttps://" are treated as valid.
nickf's solution modified:
function addhttp($url) {
if (!preg_match("#^https?://#i", $url) && !preg_match("#^ftps?://#i", $url)) {
$url = "http://" . $url;
}
return $url;
}
<?php
if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
$_POST['url'] = 'http://'.$_POST['url'];
}
$url = $_POST['url'];
?>
This code will add http:// to the URL if it’s not there.