Get current page title without loop - php

I have a small script which should get the meta title of the current page the script is added into. The problem is, that its working fine on several test pages, but not into my CMS. It loops until death there and I cant reach any page on my server until I restart apache completely and by taking the script off.
May someone take a look at it? This would be really awesome since I used google for hours and sure, I found X threads and pages, but never a solution for this special loop-effect.
<?php
function curPageURL() {
$pageURL = 'http';
$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 $pageURL;
}
?>
<?php
if (!isset($_GET['ignore']))
{
$url = curPageURL();
$data = implode("", file("$url?ignore=this"));
preg_match ("/<title>([^`]*?)<\/title>/", $data, $match);
$urltitle = $match[1];
}
?>
<?echo $urltitle;?>

The $_SERVER["REQUEST_URI"] can also include GET params like this:
mysite.com?param1=1&param2=2
Then you try to append a string ?ignore=this so you get
mysite.com?param1=1&param2=2?ignore=this
which is translated by PHP into variables like
param1 = '1'
param2 = '2?ignore=this'
You must check for ? symbol in the $url variable

I'm using this function to get the current page url :
function currentURL() {
$protocol = stripos($_SERVER['SERVER_PROTOCOL'], 'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['SERVER_NAME'];
$port = $_SERVER["SERVER_PORT"];
$query = $_SERVER['REQUEST_URI'];
return $protocol.'://'.$host.($port != 80 ? ':'.$port : '').$query;
}
But your problem comes from here :
if (!isset($_GET['ignore']))
{
$url = curPageURL();
$data = implode("", file("$url?ignore=this"));
/* ... */
}
This will work with "test pages", but you CMS propably use url-rewriting, which can cause the lost of your $_GET['ignore'] variable : if you've already other GET variable for example.
You should have a look into your .htaccess files, or read your CMS documentation to know what can change you url.
Anyway, it seems you're building some unstable code, and this only to get the page title. I'm pretty sure you've got another way to get it easily with your CMS.

Related

Getting full URL with PHP on Windows doesn't work

I am trying to build a language switch for a site of mine, but, as the hosting MUST BE a Windows IIS with PHP, I am not able to get the full URL of the page viewed by the visitor.
Say I am on domain.com/page.php?id=23, what I get using the old fashioned
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
is an empty string.
So I have tried a solution found here on stackoverflow to get the full URL
function getFullUrl() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER['HTTP_X_REWRITE_URL'];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER['HTTP_X_REWRITE_URL'];//$_SERVER["REQUEST_URI"] blank
}
return $pageURL;
}
but still nothing. I get something like: domain.com/page.php? in some cases and doman.com/? in others.
Is there a definitive way to get the full url in that scenario?
Thank you very much.
EDIT
It seems that the thing cannot be done on that server. I solved using a client side work around written in js+jQuery (I used purl plugin)....horrible :) Here it is:
$('.lang').each(function(){
$(this).click(function(e){
e.preventDefault();
var lingua = $(this).find('a').data('lang');
var url = window.location.href;
var urlParts = purl(url);
if (url.indexOf("?") >= 0)
{
var queryString = urlParts.attr('query').split('&');
var langIndex = queryString.indexOf('lang');
if(langIndex > -1)
{
queryString.splice(langIndex,1);
var newUrl = urlParts.attr('protocol')+urlParts.attr('host')+urlParts.attr('path')
window.location = newUrl + '&lang='+lingua;
}
else window.location = url + '&lang='+lingua;
}
else
window.location = url + '?lang='+lingua;
});
});
It seems to work, even if I don't get why if "lang" is already in the query string, the script doesn't recognize it and continues adding &lang every time I click on the links. Sure, it works anyway, but it is horrible to watch a URL like &lang=en&lang=fr&lang=pl&lang=de
This line returns empty
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
because it should be this:
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
You need quotes for the keys....see here in the manual.

Update a paremeter in a url instead of adding a new one

having a bit of trouble. Basically I have created some pagination. The problem is each time I click on a page number url it just adds the parameter to the url even if it already exists.
so for instance I land on the page. My url is now example.com/page?pagenum=1, I click the second page so my url is now example.com/page?pagenum=1&pagenum=2. Now it all works fine but as you can imagine is going to get a bit messy so would rather it update the parameter that's already in the URL. I'm currently using the following to get the current page URL:
<?php
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 $pageURL;
}
?>
and then the Link is something like:
<a href='<?php echo curPageURL(); ?>&pagenum=<?php echo "1"; ?>'> 1 </a>
Update
I have other paremeters in the URL I need to keep, I only need to update 'pagenum'
The problem exists because REQUEST_URI contains both the path and query string, and you're appending a new query string to that every page turn. To extract the path, you could use this code, taken from this answer:
$path = strtok($_SERVER["REQUEST_URI"], '?');
You can then copy existing query string fields, but remove pagenum:
$fields = $_GET;
unset($fields['pagenum']); // remove any existing pagenum value
$path .= '?' . http_build_query($fields); // re-append the query string
You could then use more or less your existing link code:
<a href='<?php echo $path; ?>&pagenum=<?php echo "1"; ?>'> 1 </a>
You can use http_build_query like so:
$all_params = $_GET;
$all_params["page"] = "2";
$link = "page.php?" . http_build_query($all_params); // "page.php?page=2&foo=bar"

How to trim current filename of page from URL?

I have a method, it looks like this:
private function setURL()
{
$pageURL = 'http';
if(isset($_SERVER["HTTPS"]) && $_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"];
}
if(substr($pageURL, -4) == ".php")
{
// damn. this is harder to recover from.
$len = strlen(basename(__FILE__, '.php'));
$len = strlen($pageURL) - $len;
$pageURL = substr($pageURL, 0, $len);
}
if(substr($pageURL, -1) != "/")
{
$pageURL .= "/";
}
$this->url = $pageURL;
}
If a user doesn't enter a filename, the URL returned is as expected, http://localhost/zenbb2. If the user does, however, the URL returned is wrong in some way, no matter what permutation I try to perform. For instance, this code returns http://localhost when visiting http://localhost/zenbb2/index.php, but http://localhost/zenbb2 when visiting that URL.
Edit The contents of my .htaccess file are:
Options -indexes
RewriteEngine on
Also, I mean the current URL as in, if I were visiting http://localhost/zenbb2/index.php, it would trim the index.php from the URL so I can use it in various places in my code. Ideally, in the end, I could use it like this:
$url = 'http://localhost/zenbb2';
echo "<link rel=\"{$url}/sample.css\" />"; // http://localhost/zenbb2/sample.css
You can use dirname to achieve this:
$ php -a
> $url = 'http://localhost/zenbb2/index.php';
> echo dirname($url);
http://localhost/zenbb2
Edit:
dirname always strips the last part of the string so use care to ensure you don't strip too much off but it can be useful when traversing URL or directory paths.
A better solution is to create a php file config.php then specify constants within it, after that, include the file everytime you want to use the URL. This solution is also implemented in well-known frameworks such as Codeigniter.
This approach is better, and frankly, more stable. For example, if you have a php file in a sub-directory (/zenbb2/sub/file.php) the URL directory would be zenbb2/sub, which, obviously, isn't what you're looking for, and your static files will return 404, since they don't exist there.
Try this one
$url = $_SERVER['REQUEST_URI'];
echo basename($url);
This should give index.php from http://localhost/zenbb2/index.php

Prevent empty string on query if viewing root

I use the following for getting the current URL in PHP:
$pageURL = $_SERVER["REQUEST_URI"];
return $pageURL;
This is used in my links to create e.g /login?continue=/page/i/want
However when I'm viewing the home page I will get /login?continue= how do I force it to become /login?continue=/ when viewing the home page??
I tried this:
if($pageURL == '')
$pageURL = '/';
but that didn't force the query string :/
Any ideas? Thanks
Try something like this, it will work only if the url has one "=" only:
$url = $_SERVER["REQUEST_URI"];
$arr = explode("=", $url);
if(empty($arr[1])) {
$url .="/";
}
echo $url;
Hope it helps

get a controller and method from url?

ok i have a url from $_SERVER['REQUEST_URI']
lets say it give us a url
http://localhost/controller/method
i have tried something like
explode('/',$_SERVER['REQUEST_URI'])
and it gave us like
array
0 => string '' (length=0)
1 => string 'controller' (length=10)
2 => string 'method' (length=6)
what is the best way to get the controller or method ? or removeing the 0 in the array ? ( first array ) ?
so it will be like
$controller = 'controller';
$method = 'method';
from above inputs.
maybe about list ? still no clue using list().
edit heres what ive done so far
$this->url = str_replace(config('foldertoscript'), NULL, $_SERVER['REQUEST_URI']);
$hello = explode('/',$this->url);var_dump($hello);
array_shift($hello);
list($controller,$method) = $hello;
var_dump($hello,$controller);
in a class
Thanks for looking in.
Adam Ramadhan
To remove the first element of an array, you can use array_shift().
$_SERVER['REQUEST_URI'] gives you the url without the "http://www.yoursite.com".
You can use something like this
<?php
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 $pageURL;
}
echo curPageURL();
?>
Hope this helps.
Use array_shift to remove the first array item.
http://php.net/manual/en/function.array-shift.php
Example:
$your_array = array_shift($your_array);
$controller = $your_array[0];
$method = $your_array[1];
For the same matter I use url_rewriting.
I have a rule that says ^([a-zA-Z0-0-_\/.]+)$ index.php?url=$1
(this is not a copy paste from my code, but you get the idea)
then if you say $_URL = $_REQUEST["url"];
$directive = explode("/",$_URL);
you will get what you need, as for the parameters you could say module/method/id/1/data/2
you have to take care of your parameters and it works if you use the GET method for
navigation only(as it should be used). Also makes the stuff much safer as no one can send SQL
injections via get or any "smart" directives.

Categories