Is there an if statement that allows me to check whether a URL contains a particular path?
In my particular case (using wordpress), I'm trying to check wether the URL contains /store/ https://www.website.com.au/store/brand/
So there might be something after that path...
Thank you for your help!
I suggest using WordPress function like is_singular, is_tax, etc..
function get_current_url()
{
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "۸۰") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$url = get_current_url();
if (strpos($url, '/store/') !== false) {
echo 'found';
}else{
echo 'not found';
}
Here is my simpler option to use if you don't want to create a function.
if( strpos( $_SERVER["REQUEST_URI"], "/store/" ) !== false ){ /* found */ }
Use strpos() function. it basically finds the position of the first occurrence of a substring in a given string. If the substring is not found, it returns false:
// input url string
$url = 'https://www.website.com.au/store/brand/';
$path_to_check_for = '/store/';
// check if /store/ is the url string
if ( strpos($url, $path_to_check_for) !== false ) {
// Url contains the desired path string
// your remaining code to do something in case path string is there
} else {
// Url does not contain the desired path string
// your remaining code to do something in case path string is not there
}
Related
I'm trying to use a snippet in wordpress (using a snippet plugin) to check the current url, if correct, then check if a particular cookie is set. If the cookie isn't set, redirect to previous url. No matter what I've tried, it's like it skips checking if the cookie set and continues to redirect regardless.
function get_current_url()
{
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "۸۰") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$url = get_current_url();
$no_c_redirect = 'https://example.com/content/file.html';
if (strpos($url, '/secured-registration/') !== false) {
if (isset($_COOKIE["thename"]) && $_COOKIE["_r_ck"] == "thevalue") {
} else {
header('Location: '.$no_c_redirect);
}
}
I have discovered the root of the problem to be a caching issue, not a code issue. I’ve managed to use page caching rules to solve this and it’s now working as it should.
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
I found this code on the internetz, it checks the current page url;
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;
}
So now I can do something like this;
elseif (curPageURL() == "http://www.example.com/pageexample") {
<meta tags here>
}
Great. But I would also like to use this for pagination pages. Those URLs look like this:
http://www.example.com/pageexample?start=30&groep=0
http://www.example.com/pageexample?start=60&groep=0
http://www.example.com/pageexample?start=90&groep=0
[....]
http://www.example.com/pageexample?start=270&groep=0
I could use a if statement for every of those links.. but I would much rather like to use one. Is it possible to add a wildcard or something? Like this I guess (notice the *)
elseif (curPageURL() == "http://www.example.com/pageexample" OR curPageURL() == "http://www.example.com/pageexample?start=*&groep=0") {
edit: I would like to do this for all those URLs because I want to give them the same meta description, <title> and <link rel="canonical". I could do this manually by doing an if-statement for every page (10+ atm) but I figured there was a better way.
Why not just use the parse_url() function? From the manual page:
<?php
$url = 'http://username:password#hostname/path?arg=value#anchor';
print_r(parse_url($url));
?>
// The above would print
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
For your particular case, you could then just check against the host and path variables.
Sounds a lot like regex problem:
if (preg_match("#^http://www.example.com/pageexample(\?start=[^&]*&groep=0)?#", curPageURL())) {
// it matches
}
The expression [^&]* acts like your *.; to match non-empty items, use[^&]+`. It matches these:
http://www.example.com/pageexample
http://www.example.com/pageexample?start=30&groep=0
Update
It's not entirely clear why you need to compare against the full canonical URL, unless you have multiple domains point to the same code base.
You should use a string comparison function
if (strstr(curPageURL(), 'http://www.example.com/')) !== FALSE) {
// curPageURL() contains http://www.example.com/
}
or
if (preg_match('/^http\:\/\/www\.example\.com\//', curPageURL()) {
// curPageURL() starts with http://www.example.com/
}
There's lots of ways to do it
You could wrap this
elseif (curPageURL() == "http://www.example.com/pageexample" OR curPageURL() == "http://www.example.com/pageexample?start=*&groep=0") {
in a while loop that adds 30 to a variable where you have your wild card on each iteration.
did you try regex?
if (preg_match('/http:\/\/www\.example\.com\/pageexample\?start=[0-9]+&groep\=0/i', "http://www.example.com/pageexample?start=34&groep=0")) {
echo "A match was found.";
else {
echo "A match was not found.";
}
If you don't use the query_string element from the $_SERVER array all your paginated URLs will return the same URL: http://www.example.com/pageexample, you can check with
echo $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] ;
vs
echo $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].'?'.$_SERVER["QUERY_STRING"] ;
You'll see that in the first case you don't receive GET parameters
If I have url like this: www.example.com/product/yellow-bed is it possible to retrieve product name from url?
For example, if url would be like www.example.com?page=product&product_name=yellow_bed I would use:
$product = $_GET['page'];
$product_name = $_GET['product_name'];
But how to get it from www.example.com/product/yellow-bed ?
Get the URI by "$_SERVER["REQUEST_URI"]". Convert the string into an array with explode:
$uri = 'www.google.com/product/yellow-bed' //uri = $_SERVER["REQUEST_URI"]
$uriArray = explode('/', $uri);
$product = $urlArray[1];
$product_name = $urlArray[2];
0 = www.google.com, 1 = product, 2 = yellow-bed
PHP manual: array explode ( string $delimiter , string $string [, int $limit ] ).
Some php frameworks (like CodeIgniter) has already this function implemented.
Never the less you can have a look here: http://erunways.com/simple-php-get-uri-or-segment-element/ , and that should solve your problem.
You could fetch the complete URI with $_SERVER['QUERY_STRING'] and then split it apart. Or you work with an .htaccess and internally rewrite the url.
Try $_SERVER[ 'PATH_INFO' ] or $_SERVER[ 'REQUEST_URI' ].
You should have a look at $_SERVER['REQUEST_URI']. This will be /product/yellow-bed in your example.
You can then use strrpos(), explode() orpreg_match()` (or other string manipulation functions) to extract what you want.
you can use the following function to retrive current 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;
}
?>
now you can take url and parse its elements using parse_url : http://php.net/manual/en/function.parse-url.php
I moved a WordPress installation to a new folder on a Windows/IIS server. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format:
http:://www.example.com/OLD_FOLDER/index.php/post-title/
I can't figure out how to grab the /post-title/ part of the URL.
$_SERVER["REQUEST_URI"] - which everyone seems to recommend - is returning an empty string. $_SERVER["PHP_SELF"] is just returning index.php. Why is this, and how can I fix it?
Maybe, because you are under IIS,
$_SERVER['PATH_INFO']
is what you want, based on the URLs you used to explain.
For Apache, you'd use $_SERVER['REQUEST_URI'].
$pageURL = (#$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
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;
For Apache:
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
You can also use HTTP_HOST instead of SERVER_NAME as Herman commented. See this related question for a full discussion. In short, you are probably OK with using either. Here is the 'host' version:
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
For the Paranoid / Why it Matters
Typically, I set ServerName in the VirtualHost because I want that to be the canonical form of the website. The $_SERVER['HTTP_HOST'] is set based on the request headers. If the server responds to any/all domain names at that IP address, a user could spoof the header, or worse, someone could point a DNS record to your IP address, and then your server / website would be serving out a website with dynamic links built on an incorrect URL. If you use the latter method you should also configure your vhost or set up an .htaccess rule to enforce the domain you want to serve out, something like:
RewriteEngine On
RewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$
RewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]
#sometimes u may need to omit this slash ^ depending on your server
Hope that helps. The real point of this answer was just to provide the first line of code for those people who ended up here when searching for a way to get the complete URL with apache :)
$_SERVER['REQUEST_URI'] doesn't work on IIS, but I did find this: http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/ which sounds promising.
Use this class to get the URL works.
class VirtualDirectory
{
var $protocol;
var $site;
var $thisfile;
var $real_directories;
var $num_of_real_directories;
var $virtual_directories = array();
var $num_of_virtual_directories = array();
var $baseURL;
var $thisURL;
function VirtualDirectory()
{
$this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
$this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];
$this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);
$this->real_directories = $this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['PHP_SELF'])));
$this->num_of_real_directories = count($this->real_directories);
$this->virtual_directories = array_diff($this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['REQUEST_URI']))),$this->real_directories);
$this->num_of_virtual_directories = count($this->virtual_directories);
$this->baseURL = $this->site . "/" . implode("/", $this->real_directories) . "/";
$this->thisURL = $this->baseURL . implode("/", $this->virtual_directories) . "/";
}
function cleanUp($array)
{
$cleaned_array = array();
foreach($array as $key => $value)
{
$qpos = strpos($value, "?");
if($qpos !== false)
{
break;
}
if($key != "" && $value != "")
{
$cleaned_array[] = $value;
}
}
return $cleaned_array;
}
}
$virdir = new VirtualDirectory();
echo $virdir->thisURL;
Add:
function my_url(){
$url = (!empty($_SERVER['HTTPS'])) ?
"https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
"http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
echo $url;
}
Then just call the my_url function.
I use the following function to get the current, full URL. This should work on IIS and Apache.
function get_current_url() {
$protocol = 'http';
if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {
$protocol .= 's';
$protocol_port = $_SERVER['SERVER_PORT'];
} else {
$protocol_port = 80;
}
$host = $_SERVER['HTTP_HOST'];
$port = $_SERVER['SERVER_PORT'];
$request = $_SERVER['PHP_SELF'];
$query = isset($_SERVER['argv']) ? substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1) : '';
$toret = $protocol . '://' . $host . ($port == $protocol_port ? '' : ':' . $port) . $request . (empty($query) ? '' : '?' . $query);
return $toret;
}
REQUEST_URI is set by Apache, so you won't get it with IIS. Try doing a var_dump or print_r on $_SERVER and see what values exist there that you can use.
The posttitle part of the URL is after your index.php file, which is a common way of providing friendly URLs without using mod_rewrite. The posttitle is actually therefore part of the query string, so you should be able to get it using $_SERVER['QUERY_STRING']
Use the following line on the top of the PHP page where you're using $_SERVER['REQUEST_URI']. This will resolve your issue.
$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
Oh, the fun of a snippet!
if (!function_exists('base_url')) {
function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
if (isset($_SERVER['HTTP_HOST'])) {
$http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$hostname = $_SERVER['HTTP_HOST'];
$dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$core = preg_split('#/#', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
$core = $core[0];
$tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
$end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
$base_url = sprintf( $tmplt, $http, $hostname, $end );
}
else $base_url = 'http://localhost/';
if ($parse) {
$base_url = parse_url($base_url);
if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
}
return $base_url;
}
}
It has beautiful returns like:
// A URL like http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server:
echo base_url(); // Will produce something like: http://stackoverflow.com/questions/189113/
echo base_url(TRUE); // Will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); //Will produce something like: http://stackoverflow.com/questions/
// And finally:
echo base_url(NULL, NULL, TRUE);
// Will produce something like:
// array(3) {
// ["scheme"]=>
// string(4) "http"
// ["host"]=>
// string(12) "stackoverflow.com"
// ["path"]=>
// string(35) "/questions/189113/"
// }
Everyone forgot http_build_url?
http_build_url($_SERVER['REQUEST_URI']);
When no parameters are passed to http_build_url it will automatically assume the current URL. I would expect REQUEST_URI to be included as well, though it seems to be required in order to include the GET parameters.
The above example will return full URL.
I have used the following code, and I am getting the right result...
<?php
function currentPageURL() {
$curpageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$curpageURL.= "s";
}
$curpageURL.= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$curpageURL.= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else {
$curpageURL.= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $curpageURL;
}
echo currentPageURL();
?>
In my apache server, this gives me the full URL in the exact format you are looking for:
$_SERVER["SCRIPT_URI"]
Reverse Proxy Support!
Something a little more robust. Note It'll only work on 5.3 or greater.
/*
* Compatibility with multiple host headers.
* Support of "Reverse Proxy" configurations.
*
* Michael Jett <mjett#mitre.org>
*/
function base_url() {
$protocol = #$_SERVER['HTTP_X_FORWARDED_PROTO']
?: #$_SERVER['REQUEST_SCHEME']
?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
$port = #intval($_SERVER['HTTP_X_FORWARDED_PORT'])
?: #intval($_SERVER["SERVER_PORT"])
?: (($protocol === 'https') ? 443 : 80);
$host = #explode(":", $_SERVER['HTTP_HOST'])[0]
?: #$_SERVER['SERVER_NAME']
?: #$_SERVER['SERVER_ADDR'];
// Don't include port if it's 80 or 443 and the protocol matches
$port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
return sprintf('%s://%s%s/%s', $protocol, $host, $port, #trim(reset(explode("?", $_SERVER['REQUEST_URI'])), '/'));
}