I'm using https://example.com version of url for my laravel built app site.
I want
<link rel="canonical" hreflang="en-us" href="https://www.upscaleadventures.com/" /> as my canonical tag
{{url()->current()}} only gives the URL that I've setup as default. <link rel="canonical" hreflang="en-us" href="https://upscaleadventures.com/" /> version in my case.
How do I print https://www.upscaleadventures.com/ version of url in Laravel
You may set APP_URL in your .env file to https://example.com, then access it via
env("APP_URL", "somedefaultvalue");
Edit
You may consider create a helper to convert your URL
function addWwwToUrl($url) {
$bits = parse_url($url);
$newHost = substr($bits["host"],0,4) !== "www." ? "www." . $bits["host"] : $bits["host"];
$newUrl = $bits["scheme"]. "://" . $newHost . (isset($bits["port"]) ? ":" . $bits["port"] : "" ) . (isset($bits["path"]) ? $bits["path"] : "" ) . (!empty($bits["query"])? "?" . $bits["query"]: "");
return $newUrl;
}
Reference
Usage
{{ addWwwToUrl(url()->current()) }}
Related
I am trying to create a affiliate link geenrator using php. I need help to create a flipkart deep affiliate link,which can remove 'www.' and add 'dl.' if present or add 'dl.' before link. For example if input link was https://www.flipkart.com/?affid=xyz then it sends me https://dl.flipkart.com/dl/?affid=xyz . Same for the below links :-
Input link ---> Output Link
https://flipkart.com/?affid=xyz --> https://dl.flipkart.com/dl/?affid=xyz , or
https://dl.flipkart.com/?affid=xyz --> https://dl.flipkart.com/dl/?affid=xyz , or
https://dl.flipkart.com/?affid=xyz --> https://dl.flipkart.com/dl/?affid=xyz
Thanks in advance.
Use parse_url() to get the url metadata. Now, check for host and just overwrite it with dl.flipkart.com and so goes for the path as well.
Snippet:
<?php
$tests = [
'https://www.flipkart.com/?affid=xyz',
'https://flipkart.com/dl?affid=xyz',
'https://dl.flipkart.com/?affid=xyz',
'https://dl.flipkart.com/?affid=xyz',
'https://dl.flipkart.com/dl?affid=xyz',
'https://flipkart.com/whirlpool-1-5-ton-5-star-split-inverter-ac-white/p/itmf8fb8a675505d?pid=ACNFE6K2BXFY6EKX'
];
foreach($tests as $test){
echo $test," => ",getNewURL($test),PHP_EOL;
}
function getNewURL($url){
$url_parts = parse_url($url);
$url_parts['host'] = 'dl.flipkart.com';
$url_parts['path'] .= "/";
if(strpos($url_parts['path'],"/dl/") !== 0) $url_parts['path'] = '/dl/'.trim($url_parts['path'],"/");
return $url_parts['scheme'] . "://" . $url_parts['host'] . $url_parts['path'] . (empty($url_parts['query']) ? '' : '?' . $url_parts['query']);
}
I've search around on SO, but can't find an exact answer to my needs.
Generating a URL is pretty easy...
Like so:
<link rel="canonical" href="https://example.com<?php echo ($_SERVER['REQUEST_URI']); ?>" />
But, the issue with this is, the $_SERVER['REQUEST_URI']) will always fetch the current file in use, so the canonical URL could potentially change.
So it could flick between www.example.com/hello.php and www.example.com/hello/, and many other variations depending on how the user accesses your site.
How do I make it so it's always the same url? (preferably without .php)
Worked it out myself, pretty basic:
<?php
$fullurl = ($_SERVER['REQUEST_URI']);
$trimmed = trim($fullurl, ".php");
$canonical = rtrim($trimmed, '/') . '/';
?>
Then...
<link rel="canonical" href="https://example.com<?php echo $canonical ?>" />
I'm sure there's different methods, but it works for me.
This is what i do.
<?php
// get the rigth protocol
$protocol = !empty($_SERVER['HTTPS']) ? 'https' : 'http';
// simply render canonical base on the current http host ( multiple host ) + requests
echo $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
I think your scripts require a bit of sanitisation, am I right?
I mean, if your page is
https://example.com/test.php
but a malicious - but harmless - person does
https://example.com/test.php/anotherThing.php
your canonical would become
https://example.com/anotherThing.php
you wouldn't want that to happen, though, am I right? Especially if the malicious person is not harmless and does worst things with your urls...
This will remove query parameters like ?search=abc&page=32
Option 1:
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . strtok($_SERVER['REQUEST_URI'], '?');
Option 2 (does the same) :
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
Then echo
echo '<link rel="canonical" href="' . $url . '" />';
I'm working on a project where I need to scrape some content from the same site, but a subfolder, and store it. I know it's not ideal, but it's sadly the best approach for the client.
I need to change all references from relative to absolute URLs
All the references (images, css, js) are referred relatively with both:
"../../imgs/"
"/js/"
... which means they don't work in my sub-folder. I need a function that matches the regex on these references and replaces the path.
When I try this:
function getRelativeContent($url) {
$page = file_get_contents($url);
//url needs trailing /
if (substr($url, -1, 1) != "/")
$url .= "/";
$page = preg_replace('/src="(\/)?([\w_\-\/\.\?&=#%#]*)"/i','src="' . $url . '$2"', $page);
$page = preg_replace('/href="(\/)?([\w_\-\/\.\?&=#%#]*)"/i','href="' . $url . '$2"', $page);
return $page;
}
echo getRelativeContent($url);
Then these URLs doesn't work:
<link href="/cassette.axd/stylesheet/fdbdaa59cb97b35f06f65fd41cb60caa3975cc0f/forbrug-rwd_(max-width 767px)" type="text/css" rel="stylesheet" media="(max-width: 767px)">
<img src="https://www.domain.dk/~/media/2561BD6AFBD64402877E4ACED01F97FD.ashx" />
function getRelativeContent($url) {
$page = file_get_contents($url);
//url needs trailing /
if (substr($url, -1, 1) != "/")
$url .= "/";
$page = preg_replace('/src="(\/)?([\w_\-\/\.\?&=#%#]*)"/i','src="' . $url . '$2"', $page);
$page = preg_replace('/href="(\/)?([\w_\-\/\.\?&=#%#]*)"/i','href="' . $url . '$2"', $page);
return $page;
}
echo getRelativeContent($url);
I would like to get all of the base url of the site in my twig extension:
$this->service_container->get('request')->getBaseUrl()
gives me a lot but the host is missing...
another method maybe to get everything or one to get the host ?
Goal : have this :
http://my_host/request_base_url
$request = $this->getRequest();
$scheme = $request->getScheme();
$host = $request->getHttpHost();
$base = sprintf('%s://%s', $scheme, $host);
This is how im using this code to get complete base url .
public function test($request){
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() ;
}
I'm using:
$domain = $_SERVER['HTTP_HOST'];
$path = $_SERVER['SCRIPT_NAME'];
$themeurl = $domain . $path;
But this of course gives the full URL.
Instead I need the full URL minus the current file and up one directory and minus the trailing slash.
so no matter what the browser URL domain is eg localhost, https://, http://, etc that the full real (bypassing any mod rewrites) URL path of the parent directory is given without a trailing slash.
How is this done?
Safely so no XSS as I guess (from reading) using anything but 'SCRIPT_NAME' has such risk.. not sure though ofc.. just been reading a ton trying to figure this out.
examples:
if given:
https://stackoverflow.com/questions/somequestions/index.php
need:
https://stackoverflow.com/questions
without the trailing slash.
and should also work for say:
http://localhost/GetSimple/admin/load.php
to get
http://localhost/GetSimple
which is what I'm trying to do.
Thank you.
Edit:
Here's the working solution I used:
$url = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
$url .= htmlspecialchars($_SERVER['REQUEST_URI']);
$themeurl = dirname(dirname($url)) . "/theme";
it works perfectly.
Thats easy - using the function dirname twice :)
echo dirname(dirname('https://stackoverflow.com/questions/somequestions/index.php'));
Also note #Sid's comment. When you you need the full uri to the current script, with protocol and server the use something like this:
$url = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
$url .= $_SERVER['REQUEST_URI'];
echo dirname(dirname($url));
I have more simple syntax to get parent addres with port and url
lets try my code
dirname($_SERVER['PHP_SELF'])
with this code you can got a direct parent of adres
if you want to 2x roll back directory you can looping
dirname(dirname($_SERVER['PHP_SELF']))
dirname is fungtion to get parent addrest web and $_SERVER['PHP_SELF'] can showing current addres web.
thakyou Sir https://stackoverflow.com/users/171318/hek2mgl
I do not suggest using dirname()as it is for directories and not for URIs. Examples:
dirname("http://example.com/foo/index.php") returns http://example.com/foo
dirname("http://example.com/foo/") returns http://example.com
dirname("http://example.com/") returns http:
dirname("http://example.com") returns http:
So you have to be very carful which $_SERVER var you use and of course it works only for this specific problem. A much better general solution would be to use currentdir() on which basis you could use this to get the parent directory:
function parentdir($url) {
// note: parent of "/" is "/" and parent of "http://example.com" is "http://example.com/"
// remove filename and query
$url = currentdir($url);
// get parent
$len = strlen($url);
return currentdir(substr($url, 0, $len && $url[ $len - 1 ] == '/' ? -1 : $len));
}
Examples:
parentdir("http://example.com/foo/bar/index.php") returns
http://example.com/foo/
parentdir("http://example.com/foo/index.php") returns http://example.com/
parentdir("http://example.com/foo/") returns http://example.com/
parentdir("http://example.com/") returns http://example.com/
parentdir("http://example.com") returns http://example.com/
So you would have much more stable results. Maybe you could explain why you wanted to remove the trailing slash. My experience is that it produces more problems as you are not able to differentiate between a file named "/foo" and a folder with the same name without using is_dir(). But if this is important for you, you could remove the last char.
This example works with ports
function full_url($s)
{
$ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true:false;
$sp = strtolower($s['SERVER_PROTOCOL']);
$protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
$port = $s['SERVER_PORT'];
$port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
$host = isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : $s['SERVER_NAME'];
return $protocol . '://' . $host . $port . $s['REQUEST_URI'];
}
$themeurl = dirname(dirname(full_url($_SERVER))).'/theme';
echo 'Theme URL';
Source: https://stackoverflow.com/a/8891890/175071
I'm with hek2mgl. However, just in case the script isn't always specifically 2 directories below your target, you could use explode:
$parts = explode("/",ltrim($_SERVER['SCRIPT_NAME'],"/"));
echo $_SERVER['HTTP_HOST'] . "/" . $parts[0];
As hek2mgl mentioned, it's correct, and a more dynamic approach would be dirname(dirname(htmlspecialchars($_SERVER['REQUEST_URI'])));.
EDIT:
$_SERVER['REQUEST_URI'] will omit the domain name. Referring #hek2mgl's post, you can echo dirname(dirname(htmlspecialchars($url)));
Here are useful commands to get the desired path:
( For example, you are executing in http:// yoursite.com/folder1/folder2/file.php)
__FILE__ (on L.Hosting) === /home/xfiddlec/http_docs/folder1/folder2/yourfile.php
__FILE__ (on Localhost) === C:\wamp\www\folder1\folder2\yourfile.php
$_SERVER['HTTP_HOST'] === www.yoursite.com (or without WWW)
$_SERVER["PHP_SELF"] === /folder1/folder2/yourfile.php
$_SERVER["REQUEST_URI"] === /folder1/folder2/yourfile.php?var=blabla
$_SERVER["DOCUMENT_ROOT"] === /home/xfiddlec/http_docs
// BASENAME and DIRNAME (lets say,when __file__ is '/folder1/folder2/yourfile.php'
basename(__FILE__) ==== yourfile.php
dirname(__FILE__) ==== /folder1/folder2
Examples:
*HOME url ( yoursite.com )
<?php echo $_SERVER['HTTP_HOST'];?>
*file's BASE url ( yoursite.com/anyfolder/myfile.php )
<?php echo $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; ?>
*COMPLETE current url ( yoursite.com/anyfolder/myfile.php?action=blabla )
<?php echo $_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];?>
*CURRENT FOLDER's URL ( yoursite.com/anyfolder/ )
<?php echo $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']); ?>
*To get RealPath to the file (even if it is included) (change /var/public_html to your desired root)
<?php
$cur_file=str_replace('\\','/',__FILE__); //Then Remove the root path::
$cur_file=preg_replace('/(.*?)\/var\/public_html/','',$cur_file);
?>
p.s.for wordpress, there exist already pre-defined functions to get plugins or themes url.
i.e. get plugin folder ( http://yoursite.com/wp-content/plugins/pluginName/ )
<?php echo plugin_dir_url( __FILE__ );?>