I'm nearly done with finding a way to show a .html file on certain pages only.
In this case i want test.html to be shown on http://www.example.com/categories/AnyPageThatExcistsInCategories
I figured out the following code works on /categories.
<?php if ($_SERVER['REQUEST_URI'] == '/categories/') { include 'test.html';} ?>
I only need the golden tip on how to get it also working on pages like /categories/ThisCanBeAnything and categories/ThisCanBeAnything/AndThisAlso etc etc
server config is nginx.
thank you
You could see if the request uri begins with the string '/categories/':
<?php
$request_uri = '/categories/foo';
if (strpos($request_uri, '/categories/') === 0 )
{
include 'your.html';
}
Substitute the value of $request_uri above with $_SERVER['request_uri']. Under the assumption that you have this logic in a front controller.
Further:
<?php
$request_uris = [
'/categories/foo',
'/categories/',
'/categories',
'/bar'
];
function is_category_path($request_uri) {
$match = false;
if (strpos($request_uri, '/categories/') === 0 )
{
$match = true;
}
return $match;
}
foreach ($request_uris as $request_uri) {
printf(
"%s does%s match a category path.\n",
$request_uri,
is_category_path($request_uri) ? '' : ' not'
);
}
Output:
/categories/foo does match a category path.
/categories/ does match a category path.
/categories does not match a category path.
/bar does not match a category path.
In use:
if(is_category_path($_SERVER['REQUEST_URI'])) {
include 'your.html';
exit;
}
You may want to not match the exact string '/categories/', if so you could adjust the conditional:
if(
strpos($request_uri, '/categories/') === 0
&& $request_uri !== '/categories/'
) {}
Progrock's example will work just fine, but here is another example using a regex match instead of strpos, in case you're curious!
<?php
if (preg_match("/\/categories\/.*/", $_SERVER['REQUEST_URI'])) {
include 'test.html';
}
?>
Related
I have the following files. The objective of this is to redirect to the correct news. For example:
localhost/tostadotv/esto-es-una-noticia-28.html
If I intentionally modify the url, for example:
localhost/tostadotv/esto-es-una-noticia-modificada-incorrecta-28.html
I should redirect myself to the correct news:
localhost/tostadotv/esto-es-una-noticia-28.html
However, it redirects me to this:
http://localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/localhost/tostadotv/esto-es-una-noticia-28.html
Where this error? Could you please help me thanks. Excuse my english I'm from Argentina I do not speak English
.htaccess
RewriteEngine On
RewriteRule ^.*-([0-9]+)\.html$ noticia.php?id_not=$1 [L]
noticia.php
<?php require_once("lib/connection.php"); ?>
<?php require_once("lib/functions.php"); ?>
<?php
fix_category_product_url();
?>
functions.php
function fix_category_product_url() {
$proper_url = get_proper_category_product_url(1);
if ( SITE_DOMAIN.$_SERVER['REQUEST_URI'] != $proper_url) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$proper_url);
exit();
}
}
function get_proper_category_product_url($id) {
$product_id = $_GET['id_not'];
$query = sprintf('SELECT titulo FROM noticias WHERE id_not = "%d"', mysqli_real_escape_string($GLOBALS['DB'], $product_id));
$restit = mysqli_query($GLOBALS['DB'], $query);
$noticia = mysqli_fetch_array($restit);
$proper_url = make_category_product_url($noticia['titulo'], $product_id, $id);
return $proper_url;
}
define('SITE_DOMAIN', 'localhost');
function _prepare_url_text($string) {
$NOT_acceptable_characters_regex = '#[^-a-zA-Z0-9_ ]#';
$string = iconv('UTF-8','ASCII//TRANSLIT',$string);
$string = preg_replace($NOT_acceptable_characters_regex, '', $string);
$string = trim($string);
$string = preg_replace('#[-_ ]+#', '-', $string);
return $string;
}
function make_category_product_url($product_name, $product_id, $ido) {
$clean_product_name = _prepare_url_text($product_name);
if ($ido == 0)
$url = strtolower($clean_product_name).'-'.$product_id.'.html';
else
$url = SITE_DOMAIN.'/tostadotv/'.strtolower($clean_product_name).'-'.$product_id.'.html';
return $url;
}
As said in the comments, the final solution for the asker was to add http:// to the defined SITE_DOMAIN constant.
Before
define('SITE_DOMAIN', 'localhost');
After
define('SITE_DOMAIN', 'http://localhost');
But there's more to it than just that. Let's focus on the following two functions:
function fix_category_product_url(){
$proper_url = get_proper_category_product_url(1);
if(SITE_DOMAIN.$_SERVER['REQUEST_URI'] != $proper_url){
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$proper_url);
exit();
}
}
function make_category_product_url($product_name, $product_id, $ido) {
$clean_product_name = _prepare_url_text($product_name);
if($ido == 0)
$url = strtolower($clean_product_name).'-'.$product_id.'.html';
else
$url = SITE_DOMAIN.'/tostadotv/'.strtolower($clean_product_name).'-'.$product_id.'.html';
return $url;
}
The idea here is that $proper_url actually ends up getting a value from make_category_product_url() because its result is returned by get_proper_category_product_url(). It makes sense because make_category_product_url() has more parameters and uses the other to get their values.
What's funny about this is that the else block of the second function doesn't always return a path, but rather a URL. The problem here is that such URL is given without a defined protocol, but starts with the domain name instead. This value is therefore mistaken as a path.
Now take a look at the first function: it ultimately redirects the user using header('Location: '.$proper_url);. As we discussed earlier, $proper_url is not always a path, so the protocol should be added somewhere in the code whenever a URL takes place instead of a path. That's where the actual solution comes in: adding http:// where SITE_DOMAIN is defined is one way to do this, because this constant is only used when a URL takes place. There are many other ways to do this, but this one is completely valid.
Situation is getting a logo on:
domain.com/special_dir/any_page
or
domain.com/special_dir/any_dir/
to use a link to [domain.com/special_dir/].
Everywhere else on [domain.com/] the logo must a link to [domain.com/]
This is what I have so far.
<?php
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if( $host == 'domain.com/special_dir/' ) {
echo '<div"><img src="..."></div>';
} else {
echo '<div"><img src="..."></div>';
}
?>
The logo for [domain.com/special_dir/] only works for [domain.com/special_dir/] URL, no others. I suppose the code it doing what it should, I just don't know how to make it recursive. I did search and read a lot of similar situations but none based on PHP code worked for me.
It is WordPress Multi-site setup and the "special_dir" is a regular sub-directory.
How to correct?
Thanks
Your if ($host == 'domain.com/special_dir/') statement means the special link will be printed for domain.com/special_dir/ only. It excludes everything else, including comain.com/special_dir/any_dir and domain.com/special_dir/any_page.
If think you want ...
if (substr($host,0,22) == 'domain.com/special_dir/') { ... }
This did the trick.
<?php
$url = $_SERVER["REQUEST_URI"];
if (strpos($url, "/special_dir/") === 0) {
echo '<div"><img src="..."></div>';
} else {
echo '<div"><img src="..."></div>';
}
?>
I need to execute a PHP script only is a user is redirected from another page that starts with specific name. For example: domain.com/abcXXXXXX
I've tried this but it doesn't seem to work:
if (preg_match("/abc", $_SERVER['HTTP_REFERER'])) {
}
What am I missing?
I would suggest using parse_url in conjunction with a look up table of URLs.
You can do the following:
$allowedReferals = [
'www.google.com/maps',
'www.google.co.uk/maps',
'www.google.in/maps',
];
$referer = !isset($_SERVER['HTTP_REFERER']) ? null : parse_url($_SERVER['HTTP_REFERER']);
if (!is_null($referer)) {
$host = !isset($referer['host']) ? null : $referer['host'];
$path = !isset($referer['path']) ? null : $referer['path'];
$referingDomain = $host . $path;
if (in_array($referingDomain, $allowedReferals)) {
// The referer matches one of the allowed referers in the lookup table
// Do something...
}
if (preg_match('/^maps/', $path)) {
// The referer's path begins with maps
// Do something...
}
}
Fix the regex pattern like this:
if (preg_match("/^domain\.com\/abc/", $_SERVER['HTTP_REFERER'])) {
}
Another version to check with/without www:
if (preg_match("/[w{3}\.]?domain\.com\/abc/",'www.domain.com/abcXXXXXX')) {
}
This question already has answers here:
How to get host name from this kind of URL?
(2 answers)
Closed 8 years ago.
Is there any way to accept a URL and change it's domain to .com ?
For example if a user were to submit www.example.in, I want to check if the URL is valid, and change that to www.example.com. I have built a regex checker that can check if the URL is valid, but I'm not entirely sure how to check if the given extension is valid, and then to change it to .com
EDIT : To be clear I am not actually going to these URL's. I am getting them submitted as user input in a form, and am simply storing them. These are functions I want to do to the URL before storing, that is all.
Edit 2 : An example to make this clearer -
$url = 'www.example.co.uk'
$newurl = function($url);
echo $newurl
which would yield the output
www.example.com
Are you looking for something like this on the server side to replace a list of selected TLDs to be translated to .coms?
<?php
$url = "www.example.in";
$replacement_tld = "com";
# array of all TLDs you wish to support
$valid_tlds = array("in","co.uk");
# possible TLD source lists
# http://data.iana.org/TLD/tlds-alpha-by-domain.txt
# https://wiki.mozilla.org/TLD_List
# from http://stackoverflow.com/a/10473026/723139
function endsWith($haystack, $needle)
{
$haystack = strtolower($haystack);
$needle = strtolower($needle);
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
foreach($valid_tlds as $tld){
if(endsWith($url, $tld))
{
echo substr($url, 0, -strlen($tld)) . $replacement_tld . "\n";
break;
}
}
?>
Create an empty text file using a text editor such as notepad, and save it as htaccess.txt.
301 (Permanent) Redirect: Point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "mt-example.com" domain:
# This allows you to redirect your entire website to any other domain
Redirect 301 / http://mt-example.com/
302 (Temporary) Redirect: Point an entire site to a different temporary URL. This is useful for SEO purposes when you have a temporary landing page and plan to switch back to your main landing page at a later date:
# This allows you to redirect your entire website to any other domain
Redirect 302 / http://mt-example.com/
For more details : http://kb.mediatemple.net/questions/242/How+do+I+redirect+my+site+using+a+.htaccess+file%3F
The question is not entirely clear, I'm assuming you wish to make this logic on PHP part.
Here's useful function to parse such strings:
function parseUrl ( $url )
{
$r = "^(?:(?P<scheme>\w+)://)?";
$r .= "(?:(?P<login>\w+):(?P<pass>\w+)#)?";
$r .= "(?P<host>(?:(?P<subdomain>[\w\.\-]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
$r .= "(?::(?P<port>\d+))?";
$r .= "(?P<path>[\w/]*/(?P<file>\w+(?:\.\w+)?)?)?";
$r .= "(?:\?(?P<arg>[\w=&]+))?";
$r .= "(?:#(?P<anchor>\w+))?";
$r = "!$r!";
preg_match( $r, $url, $out );
return $out;
}
You can parse URL, validate it, and then recreate from resulting array replacing anything you want.
If you want to practice regexp and create own patterns - this site will be best place to do it.
If your goal to route users from one url to another or change URI style, then you need to use mod rewrite.
Actually in this case you will end up configuring your web server, probably virtual host, because it will route only listed domains (those being parked at the server).
To validate a URL in PHP You can use filter_var() .
filter_var($url, FILTER_VALIDATE_URL))
and then to get Top Level Domain (TLD) and replace the it with .com , you can use following function :
$url="http://www.dslreports.in";
$ext="com";
function change_url($url,$ext)
{
if(filter_var($url, FILTER_VALIDATE_URL)) {
$tld = '';
$url_parts = parse_url( (string) $url );
if( is_array( $url_parts ) && isset( $url_parts[ 'host' ] ) )
{
$host_parts = explode( '.', $url_parts[ 'host' ] );
if( is_array( $host_parts ) && count( $host_parts ) > 0 )
{
$tld = array_pop( $host_parts );
}
}
$new_url= str_replace($tld,$ext,$url);
return $new_url;
}else{
return "Not a valid URl";
}
}
echo change_url($url,$ext);
Hope this helps!
I have a menu that is consistent throughout one of my directories. For example,
Main Page
Documents Page
Photos Page
I would expect to be able to include a menu like this into each page, and I'd be done. However, this time it's a bit different, because the links generated by individual pages have to be different even though the destination is the same. Take the link to the galleries.php page as an example:
From the Home page: <a href='galleries.php?id=<?=$id?>'>
From the Documents page: <a href='galleries.php?id=<?=$doc[lid]?>'>
From the Photos page: <a href='galleries.php?id=<?=$photo[lid]?>'>
From the Productss page: <a href='galleries.php??id=<?=$product[lid]?>'>
>
What I'm doing for now is to copy and paste the menu into each file, and changing the URL as needed, but this isn't a very satisfactory solution. How can I build some sort of if statement in the menu itself so the correct link is generated by the page that is including the menu?
$_SERVER['REQUEST_URI'] can give you the page you're currently on, and you can use this to determine where you should link to.
Example:
function displayGalleryId($lid) {
$uri = $_SERVER['REQUEST_URI'];
switch ($uri) {
case '/home.php':
$link = $id;
break;
case '/documents.php':
$link = $doc[$lid];
break;
// Others here...
default:
$link = 'gallery.php';
}
return $link;
}
Example Usage:
<a href='galleries.php?id=<? displayGalleryId($lid); ?> '>
You need to use $_SERVER global array..
you can use $_SERVER['SCRIPT_FILENAME'] or $_SERVER['REQUEST_URI']
it can be like
function getLink($id)
{
$uri = $_SERVER['REQUEST_URI'];
$is_page_home = (strstr($uri, 'home') === true)?true:false;
$is_page_photos= (strstr($uri, 'photos') === true)?true:false;
$is_page_document = (strstr($uri, 'document') === true)?true:false;
if( $is_page_home )
{
$urlid = $id
}
if( $is_page_photos)
{
$urlid = $doc[$id]
}
if( $is_page_document )
{
$urlid = $photo[$id]
}
return $urlId
}
$urlId = getLink($id)
<a href='galleries.php??id=<?=$urlId?>'>
to learn more about server variables http://php.net/manual/en/reserved.variables.server.php