I Use this part of code to print canonical tag:
<?php
if(!empty($_SERVER["REQUEST_URI"])){
$url = strtok($_SERVER["REQUEST_URI"],'?');
?>
<link rel="canonical" href="https://mywebsite.com<?=urldecode($url);?>" />
<?php
} else {
?>
<link rel="canonical" href="https://mywebsite.com" />
<?php
}
?>
But it not going to ready else condition if current URL is https://mywebsite.com. I found out why, because var_dump($_SERVER["REQUEST_URI"]); return string(1) "/". Why when I open this URL REQUEST_URI return / while there is no slash at tail?
Anyway, beside of this question, how can I solve my code to working?
In a HTTP call $_SERVER['REQUEST_URI'] can never be empty unless it is unset($_SERVER['REQUEST_URI']) or $_SERVER['REQUEST_URI] = '' by the script itself.
For a HTTP call to http://mywebsite.com, it will hold / as its value. That's what you are getting. / denotes root of the website, so when HTTP request is made to the root of the website, / is sent as path and will always be present, whether you add it or not into the URL.
I think that clarifies why you are not hitting else condition of your code ever.
Coming to your problem, if you want to append the path to the url without any query parameters, the better approach for this should be:
<link rel="canonical" href="https://mywebsite.com<?php echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); ?>">
This replaces all of your code. You may want to take a look at parse_url function of PHP.
If you don't want the trailing slash intentionally, you can make use of rtrim.
<link rel="canonical" href="https://mywebsite.com<?php echo rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'); ?>">
In case, you are passing any valid URL to parse_url and don't want trailing slash only for root, then:
<?php
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if($path == '/' || !$path) {
$path = '';
} ?>
<link rel="canonical" href="https://mywebsite.com<?php echo $path; ?>">
Related
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 need to replace all relative URL to absolute URL of a web page using only HTML DOM. It's possible?
I am also using yii2.
Example
Site:http://www.example.com
<link href="/css/site.css" rel="stylesheet">
Page
Result:
<link href="http://www.example.com/css/site.css" rel="stylesheet">
Page
set $scheme parameter to true to return an absolute url if you want to link to an controller action.
Url::to(['my_controller/action'], true);
http://www.yiiframework.com/doc-2.0/yii-helpers-baseurl.html#to()-detail
For files you can use this Html::a( $text, $url = null, $options = [] ) with below options
// A normal string. This will use the exact string as the href attribute
$url = 'images/logo.png'; // This returns href='images/logo.png'
// A string starting with a Yii2 alias
$url = '#web/images/logo.png' // This returns href='http://www.example.com/images/logo.png'
you colud use an url helper
assuming you have you css in /yii2/web/css
<?php
use yii\helpers\Url;
echo '<link href="' .Url::base() . '/css/site.css' .'" rel="stylesheet">';
assuming you have you css in /yii2/css
echo '<link href="' .Url::base() . '../css/site.css' .'" rel="stylesheet">';
Building my first PHP site and need some help.
Trying to make it so that the domain name will be used for a directory.
Since I know this is a very broad question, the following will be the example of what I have and what I need.
$domain = $_SERVER['HTTP_HOST'];
if ($domain == 'website.com' || $domain == 'www.website.com') {
$domain = 'Website';
include ('Website/variables.php') ; }
else {
$domain = 'Other';
include ('Other/variables.php') ;
}
Now, what I need it to do is be able to place the $domain inside of an
link href="css/custom.css" rel="stylesheet"
So what it should end up doing is actually using the $domain named folder like so
link href="$domain/css/custom.css" rel="stylesheet"
No matter what I try to do, I just can not get my site to read into the directory of the domain that it is in which is stopping my CSS from working.
Any help would be appreciated.
Try
echo "<link href=' " . $domain . "/css/custom.css' rel='stylesheet'>";
Also you can do as..
<link href="<?php echo $domain; ?>/css/custom.css" rel="stylesheet">
Same thing only....
I am trying to figure out how to add s after HTTP once a user checks a box in the html form.
I have in my PHP,
$url = 'http://google.com';
if(!isset($_POST['https'])) {
//something here
}
So basically, when the user checks a box with the name="https" i want to add s to $url's http making it https://google.com.
I have little knowledge on PHP and if someone can explain to me how to go about doing this, this would be really helpful! thanks.
$url = preg_replace("/^http:/i", "https:", $url);
$url = str_replace( 'http://', 'https://', $url );
One way:
$url = '%s//google.com';
$protocol = 'http:';
if(!isset($_POST['https'])) {
$protocol = 'https:';
}
$url = sprintf($url, $protocol);
I don't know on how many pages you want this to happen onward the user checks the box, but one answer is JavaScript and the base tag.
With the base tag, you can force a different origin, what your relative URL-s will be resolved against.
I you are using it ina form, and the user ticks the checkbox them sumbits the form, all other pages will be viewed from the https site, so you can use relative URL-s everywhere, just insert a different base tag when the user wants to change the site form or to http(s).
A solution that doesn't replace urls which contain other urls, for instance http://foo.com/redirect-to/http://newfoo.com
$desiredScheme = "http"; // convert to this scheme;
$parsedRedirectUri = parse_url($myCurrentUrl);
if($parsedRedirectUri['scheme'] !== $desiredScheme) {
$myCurrentUrl= substr_replace($myCurrentUrl, $desiredScheme, 0, strlen( $parsedRedirectUri['scheme'] ));
}
When you consider case-insensitive, then use str_ireplace function.
Example:
$url = str_ireplace( 'http://', 'https://', $url );
Alternatively, incase you ant to replace URL scheme in CDN files.
Example:
$url = str_ireplace( 'http:', 'https:', $url );
This... (with 'https:')
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
Becomes... ('https:' has been replaced)
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
$count = 1;
$url = str_replace("http://", "https://", $url, $count);
Note : Passing 1 directly will throw fatal error (Fatal error: Only variables can be passed by reference) so you have to pass it last parameter by reference.
Relatively new to php and looking for some help in updating links on a specific page. The page has numerous links eg. href=/link/ and I would like to code the page to identify these links (links that do not already have http or https) and prepend with a url eg. www.domain.com to each. Basically ending up with href=www.domain.com/link/. Any help would be greatly appreciated.
I think you want to parse a list of URLs and prepend "http://" to the ones that don't have it.
<?php
$links = array('http://www.redditmirror.cc/', 'phpexperts.pro', 'https://www.paypal.com/', 'www.example.com');
foreach ($links as &$link)
{
// Prepend "http://" to any link missing the HTTP protocol text.
if (preg_match('|^https*://|', $link) === 0)
{
$link = 'http://' . $link . '/';
}
}
print_r($links);
/* Output:
Array
(
[0] => http://www.redditmirror.cc/
[1] => http://phpexperts.pro/
[2] => https://www.paypal.com/
[3] => http://www.example.com/
)
*/
Maybe it suffices to just change the base URI of the document with the BASE element:
<base href="http://example.com/link/">
With this the new base URI is http://example.com/link/ instead of the URI of the document. That means, every relative URI is resolved from http://example.com/link/ instead of the document’s URI.
You could always use output buffering at the top of your page with a callback that reformats your hrefs to how you'd like them:
function callback($buffer)
{
return (str_replace(' href="/', ' href="http://domain.com/', $buffer));
}
ob_start('callback');
// rest of your page goes here
ob_end_flush();
Because you left out critical details in your first question, here is the second answer.
Doing what #Nev Stokes says may work, but it will also get more than tags. You should never use regular expressions (or, worse, strp_replace) on HTML.
Instead, use the file_get_html() library and do this:
<?php
require 'simplehtmldom/simple_html_dom.php';
ob_start();
?>
<html>
<body>
<a id="id" href="/my_file.txt">My File</a>
<a name="anchor_link" id="boo" href="mydoc2.txt">My Doc 2</a>
PHP Experts
</body>
</html>
<?php
$output = ob_get_clean();
$html = str_get_html($output);
$anchors = $html->find('a');
foreach ($anchors as &$a)
{
if (preg_match('|^https*://|', $a->href) === 0)
{
// Make sure first char is /.
if ($a->href[0] != '/')
{
$a->href = '/' . $a->href;
}
$a->href = 'http://www.domain.com' . $a->href;
}
}
echo $html->save();
Output:
<html>
<body>
<a id="id" href="http://www.domain.com/my_file.txt">My File</a>
<a name="anchor_link" id="boo" href="http://www.domain.com/mydoc2.txt">My Doc 2</a>
PHP Experts
</body>
</html>