Prevent empty string on query if viewing root - php

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

Related

I want to redirect website visitor from "expl.com/... "to "expl.com/index.php/..."

This is my domain http://cdtr.cf it lands on index.php
Where I wrote some code which pulls the URL from URL box and trim its suffix to identify visitor's identity.
The Problem is when someone opening http://cdtr.cf/.... it shows error 404 page not found
while just http://cdtr.cd/ is working fine. All I need is When someone visit with http://cdtr.cf/.... they must be redirected to index.php and their request should be processed like http://cdtr.cf/index.php/.....
I want to keep the suffix anyhow for some purpose :-http://cdtr.cf/suffix.
It will be great if all this happen without any visible change in URL box.
Thanks in advance.
$link= (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=== 'on'? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $link; //It is working fine on localhost but not when i put it live
This code will give you the rest of the url as per your requirement
<?php
$link = $_SERVER['REQUEST_URI'];
echo $link = ltrim($link, '/');
//if you want you can trim last / too using $link = rtrim($link, '/');
?>
If you want to get middle stuff like this yoursite.com/stuffs/removedthis
then you have to use below code
<?php
$link = $_SERVER['HTTP_HOST'];
$link .= $_SERVER['REQUEST_URI'];
$link = explode('/', $link);
echo $a = $link[1];
?>
Second example:
$link = "example.com/stuff/removethis/....blah";
$link = explode('/', $link);
echo $a = $link[1];

changing a given url to return only the domain

I'm getting a url from a form, this way:
$input_website = isset($_POST['website']) ? check_plain($_POST['website']) : 'None';
I need to get back a naked domain name(for some API integration), for example: http://www.example.com will return as example.com
and www.example.com will return example.com etc.
I have this code now, that returns the correct url for the first case http://www.example.com but returns nothing for www.example.com or even example.com:
function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
}
return false;
}
Can you please advice on the matter?
As per discussion with you:
$url = 'www.noamddd.com';
$arrUrl = explode("/", $url);
echo $arrUrl[0];
Old Answer:
Make a function with the following code block and get the domain names.
Try this
more about parse_url
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
print $parse['host']; //google.com
Also you can do this in another way:
echo $domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));//google.com
If you just have the URL (and not want the current domain name like frayne-konok suggests) and want to extract the server name, you can use a regular expression like this:
$serverName = preg_replace('|.*?://(.*?)/.*|', '$1', $url);
I ended up doing something a bit different - checking if there is http and if not, i'm adding it using this function:
function addHttp($website) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $website;
}
and only then i'm sending it to my other function that return the domain.
For sure not the best way, but it works.

Check URL for valid format by pattern

I have social bookmarking website and in this website users can submit link from others website (using booklet or bookmark button in bookmark bar, or by adding URLs in direct method).
The users have problem with some URLs when they add links with bookmark button in their browsers. The problem occurs with URLs that contain "&" character. Most of the users who work with Safari on Mac or Windows can not add such link with bookmark button.
Issue is that all URLs with "&" end up with $isLink = preg_match($pattern, $url); // Returns false (see the code below).
I removed part of my code (see comments in the snippet), and that fixed the problem.
But I do not want to remove this code. How can I fix the problem without removing it?
$url = htmlspecialchars(sanitize($_POST['url'], 3));
$url = str_replace('&', '&', $url);
$url = html_entity_decode($url);
if (strpos($url,'http')!==0) {
$url = "http://$url";
}
// check if URL is valid format
$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?#)?([\d\w]([-\d\w]{0,253}[\d\w])?\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.,\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.,\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.,\/\d\w]|%[a-fA-f\d]{2,2})*)?$/';
// vvv I REMOVED FROM HERE vvv
$isLink = preg_match($pattern, $url); // Returns true if a link
// ^^^ UNTIL HERE ^^^
if($url == "http://" || $url == "") {
if(Submit_Require_A_URL == false) {
$linkres->valid = true;
} else {
$linkres->valid = false;
}
$linkres->url_title = "";
} elseif ($isLink == false) {
$linkres->valid = false;
}
Website bookmark button code is:
javascript:q=(document.location.href);void(open('http://website.com/submit.php?url='+escape(q),'_self','resizable,location,menubar,toolbar,scrollbars,status'));
Why are you not using the PHP function "filter_var()" to check the url:
$url = $_POST['url'];
$isLink = filter_var($url, FILTER_VALIDATE_URL);

Get current page title without loop

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.

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

Categories