This question already has answers here:
PHP - Check if the page run on Mobile or Desktop browser [duplicate]
(6 answers)
Closed 7 years ago.
I want to make a website and I messed something up. I want to make two versions, one for desktops and one for mobile, but do not know how to redirect people .. I want to have two folders, mobile and web and file index.php. If they use mobile phones i want to redirect in mobile folder if they use PC redirect to web folder.
How could I do this? Thanks
Sorry for english
Case 1 : Redirecting a site to a mobile version
Say we have a normal website that we need to redirect to a mobile version if viewed from a mobile device. All the code required for mobile detection is in a single file ‘Mobile_Detect.php’, which we can include in our web pages or in the primary index file. To simplify discussion let us assume you have a website ‘example1.com’ with a single index file, and need to redirect to ‘mobile.example1.com’ if a mobile device is detected. We need to put the following in the header of the index file of ‘example1.com’.
/* Change path info depending on your file locations */
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
if($detect->isMobile()) {
header('Location: http://mobile.example1.com/');
exit;
}
Case 2: Loading different resources depending on the device
We can load or modify existing content based on the users device profile. For example we could load a different CSS for a mobile or a tablet.
$detect = new Mobile_Detect;
if($detect->isMobile() || $detect->isTablet()) {
echo "<link rel='stylesheet' href='mobile.css type='text/css' />";
} else {
echo "<link rel='stylesheet' href='style.css type='text/css' />";
}
you can also user Javascript:
<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://m.domain.com";
}
//-->
</script>
or
You can use a .htaccess redirect to transfer visitors based upon the MIME types the browser supports. For example, if the user's browser accepts mime types that include WML (Wireless Markup Language), then most likely it is a mobile device.
The code below should be placed in your .htaccess file:
RewriteEngine On
# Check for mime types commonly accepted by mobile devices
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ http://m.domain.com%{REQUEST_URI} [R,L]
If youve got 2 sites one for each device (not the best thing to do here) you can have a index.php file on the root with :
<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://your.domain.com/mobile";
} else { window.location = "http://your.domain.com/desktop"; }
//-->
</script>
Related
I was wondering if it was possible to force users to access my website from the homepage only.
For example, if the user enters the address mysite.com/subdirectory (which a valid directory) I want them to be redirected to mysite.com/index.html . From there the can navigate to /subdirectory with the hyperlinks on the homepage.
Thanks in advance!
As all you want to do is to ensure your users see some advertising, and you're currently using the standard Apache directory listing, I'd simply substitute a PHP script (as index.php in each subdirectory) that lists the files in a similar way, but inside an HTML page that you can customise with your advertising. Something along these lines, perhaps, where I've adapted this answer and wrapped it in a web page:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Download Page Example</title>
</head>
<body>
<h1>Download Page Example</h1>
<p>Here's some advertising.</p>
<ul class="file-list">
<?php
// Iterate all files in this directory
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
$filename = $fileinfo->getFilename();
// If it's not a hidden "dot file"
if (!fnmatch('.*', $filename)) {
// And put it on the list as a link, encoding the
// filename as a url path safely in the achor attribute
// and as HTML in the text.
echo '<li>' . htmlentities($filename) . '</li>';
}
}
?>
</ul>
</body>
</html>
You could use a $_SESSION variable defined in the homepage and check in other parts of the website if it is defined. If it's not redirect to your homepage.
For example, your homepage could be:
session_start();
if (!isset($_SESSION['homepage']){
$_SESSION['homepage'] = true;
}
// Your homepage code
and any other page should start with:
session_start():
if(!isset($_SESSION['homepage'] || $_SESSION['homepage'] != true){
header("Location: index.php");
}
Anyway, I can't understand why you would want to do this and I think it should be a proper way of doing what you desire without forcing the user to do this.
One method is to require a POST request to access each subpage. If the user accesses the page directly, it will be a GET request instead. On your home page, do something like this for each link:
<form method=post action="/subdirectory">
<input type=submit value="My stuff">
</form>
(You can use client-side JavaScript to re-work those buttons into links which activate the forms, if desired.)
Then on each subpage:
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
header('Location: /');
die();
}
you should be able to do this using apache's mod_rewrite
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
put this in an .htaccess file in your main directory
I done main-site and seperate mobile-site.
Main-site is Wordpress
Mobile-site is HTML pages
and I put following script for mobile auto redirect.
<script type="text/javascript">
<!--
if (screen.width <= 769) {
document.location = "http://mobile.mysite.com/";
}
//-->
</script>
But now I need Full Site link to main-site in mobile-site. By the above script, it's redirecting to same mobile-site.
I tried with cookies. I dont know, why that not working properly.
Any-one help me. Thanks.
To redirect a mobile visitor you will need to determine if their browser is a web browser on a mobile device or not. You can determine which browser the visitor is using
If you are running a Content Management System (such as WordPress or Joomla), there may be plugins already available that help with handling mobile visitors.
Because mobile phones typically have a small screen width, you can redirect visitors to your mobile site if they have a screen width of less than or equal to 800 pixels. Place Javascript window.location code in the head section of your main website code. That way when your site is visited, the javascript will see the browser width and redirect to the appropriate site.
You can use a .htaccess redirect to transfer visitors based upon the MIME types the browser supports. For example, if the user's browser accepts mime types that include WML (Wireless Markup Language), then most likely it is a mobile device. The code below should be placed in your .htaccess file.
Note:
If you're using WordPress, try the Jetpack plugin. That comes with a free mobile version that you can enable. Anybody on a phone will see the mobile version automatically.
Main site to Mobile ,
<script type="text/javascript">
<!--
if (screen.width <= 769) {
document.location = "http://mobile.mainsite.com/";
}
//-->
</script>
Mobile to Main site ,
<script type="text/javascript">
<!--
if (screen.width > 769) {
document.location = "http://mainsite.com/";
}
//-->
</script>
I've written a simple PHP script on shared hosting and wish to implement some rules in the .htaccess file so that every time my script calls, let's say, http://www.google.com/test1 it will get http://www.otherwebsite.com/test1 instead.
I've used standard URL Rewriting Rules before but didn't need this specific function.
Thank you !
If I understand your question correctly you want to redirect all of your URLs to some other domain.
Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?yourwebsite\.com$ [NC]
RewriteRule ^ http://www.otherwebsite.com%{REQUEST_URI} [R=301,L]
.htaccess can only rewrite incoming URLs with domain names that resolve to your web server. It has no control over outgoing URLs as these requests are directly going to outgoing web servers (in your example, google.com).
What you probably need is a scripting solution that redirects the user as you desire by hooking in to onclick events of all the external links. Here's a quick proof of concept with jQuery but this can be done using standard JavaScript as well.
<html>
<head>
<title>jQuery global redirector</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
<body>
google url would redirect<br />
mysite.com url won't redirect
<script>
<!--
$(function() {
$("a").click(function(e) {
var url = e.target.href;
if(!(url.startsWith("mysite.com") ||
url.startsWith("http://mysite.com"))) {
var path = $( '<a />', {href : url} ).prop( 'pathname' );
window.location.href = "http://otherwebsite.com" + path;
e.preventDefault();
}
});
});
//-->
</script>
</body>
</html>
You should probably put the script inside another file (say redirect.js) and then include this script selectively in your pages that need such redirection. And don't forget to import jQuery as well.
My CMS links to other sites for convenience and I'd like to hide the referer so that other sites don't see the directory and the query string of my CMS. I now have the CMS linking to a PHP file elswhere on my server which in turn redirects to the link via header() but the referer is still from my CMS, not from the linking PHP. Furthermore...
header("Referer: nowhere");
header("Location: $_REQUEST[urltolinkto]");
... doesn't appear to change anything. No matter what I put as referer, it's always the one from my CMS where the user actually clicked on the link.
Can the referer be changed (to the linking PHP), or do I have to use javascript or meta refresh?
The Referer header is something the browser sends to the Server. You are changing the respose from the server to the browser, so that will not work this way (unlike the Cookie header). As far as I know you have no server-side control of the browser's behavior on sending the Referer.
The browser does get to choose what referrer to send, but there are ways around it.
HTML5 added meta referrer, most modern browsers will respect it. Just add
<meta name="referrer" content="no-referrer">
to your site's head.
There's also redirection services and other hacks to hide the ref (https redirects, iframe tricks and others).
A good solution is to simply use the classic <META HTTP-EQUIV="REFRESH" CONTENT="0; URL=http://www.example.com/">.
In fact, Google Analytics has a help page specifically for this question with users who ask about web-tracking not working on redirects, here: Support.Google.com -> Redirects: Place the tag on redirecting pages. They explain the problem quite well:
If your site uses redirects, the redirecting page becomes the landing page's referrer. For example, if you've changed your site so that index.html now redirects to home.html, then index.html becomes the referrer for home.html....
For this reason, you should place the Analytics tag on the redirecting page as well as on the landing page. This way, the redirecting page will capture the actual referrer information for your reports.
So, just swap out header("Location...") with a massive series of print statements. This feels so inelegant. But it works.
Note: I'm also throwing in a canonical attribute so browsers understand the point of the redirect more clearly.
<?php
$redirect_url = 'https://www.example.com';
$google_analytics_configgtag = '12345, this is your api key';
print('<!DOCTYPE HTML><HTML><HEAD>');
print('<META HTTP-EQUIV="REFRESH" CONTENT="0; URL=' . $redirect_url . '"/>');
print('<LINK REL="CANONICAL" HREF="' . $redirect_url . '"/>');
if($google_analytics_configgtag) {
?>
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php print($google_analytics->configgtag); ?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', '<?php print($google_analytics_configgtag); ?>');
</script>
<?php
}
print('</HEAD>');
print('<BODY></BODY></HTML>');
?>
You cannot set Referer header manually but you can use location.href to set the referer header to the link used in href but it will cause reloading of the page.
You cannot really change the referer from server-side as it is provided by the browser to the server.
But you can use a service like href.li, just use
https://href.li/?http://<your-url>
Note: http:// after ? is important or it will not redirect.
How can I find out that my page is embedded as a frame to other site during page loading? I guess referrer request header can't help me here? Thanks.
You cannot check it from the server's side, but you can use javascript to detect it after the page has loaded. Compare top and self, if they're not identical, you are in a frame.
Additionally, some modern browsers respect the X-FRAME-OPTIONS header, that can have two values:
DENY – prevents the page from being rendered if it is contained in a frame
SAMEORIGIN – same as above, unless the page belongs to the same domain as the top-level frameset holder.
Users include Google's Picasa, that cannot be embedded in a frame.
Browsers that support the header, with the minimum version:
IE8 and IE9
Opera 10.50
Safari 4
Chrome 4.1.249.1042
Firefox 3.6.9 (older versions with NoScript)
Stackoverflow includes some JS to test it (master.js). This is the relevant part of it:
if(top!=self){
top.location.replace(document.location);
alert("For security reasons, framing is not allowed; click OK to remove the frames.")
}
But keep in mind that JS can be disabled.
For modern browsers, you can use CSP (Content Security Policy), which is a standard. The following header will prevent the document from loading in a frame anywhere:
Content-Security-Policy: frame-ancestors 'none'
(IE 11 needs the X- prefix, though). You can also change 'none' to the origin on which framing is allowed, such as your own site.
To cover the older browsers, this is best used together with #Maerlyn's answer.
you can prevent loading you page in an iframe with javascript
<script type="text/javascript">
if ( window.self !== window.top ) {
window.top.location.href=window.location.href;
}
</script>
this code change address of container of your page's iframe to your page address and force container to show your page.
Or you can block a specific domain if you don't mind your content in some locations but don't want it on a certain site. For example, if offendingdomain.com was embedding your content, you could do this:
<script type="text/javascript">
if(document.referrer.indexOf("offendingdomain.com") != -1) {
window.location = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0";
}
</script>
This would check the parent document's location and see if it's the offendingdomain.com that is embedding your content. This script will then send that iframe to a certain famous youtube video as punishment. In effect they just Rick-Rolled themselves.
Use javascript to check if it was loaded on iframe by placing the following script at the end of your php file and redirect to a page that displays warning or notice that your page should not be loaded using iframe.
<script type="text/javascript">
if(top.location != window.location) {
window.location = '/error_iframe.php';
}
</script>
<?php
header("Content-Security-Policy: frame-ancestors 'none'");
?>
Replace hosname to domain name
if (window.top.location.host != "hostname") {
document.body.innerHTML = "Access Denied";
}
I using this PHP code on top of the header
if($_SERVER['SERVER_NAME'] != 'yourwebsite.com'){
header('location: yourwebsite.com');
}
if someone did iframe your site it will redirect to your website