Redirecting someone - javascript

I want to redirect someone to index.php, how do i do this? But not the "meta" method, because it needs to be in header, and i can not have it there.

window.location.href = 'http://your-new-url.com';
or
window.location.pathname = 'index.php';
if you need to use a relative pathname.

Do not use JavaScript for this. If the user has JavaScript disabled (or most likely is browsing with a browser without support for JavaScript), the redirection will not work.
From your PHP code, you can send an HTTP header to direct your user to the page of your choice. Use the header() function to do this.
header('Location: index.php');
exit; // Important, stops execution of PHP page
If PHP complains that it cannot send the header because data has already been sent to the browser, simply go to the top of your script and enable output buffering by using ob_start():
ob_start();
With output buffering enabled, you can send headers anywhere in your code since data is only sent at the end of your script.
PHP Documentation: header()
PHP Documentation: ob_start()

Use window.location

<script type="text/javascript">
window.location.href = "http://www.yoursite.com/index.php"
</script>

Related

Redirect Using JavaScript and PHP

I am using below code for redirect users.
<?php
$redirect_to = "https://google.com";
$redirect = "https://yahoo.com";
echo "<script>location.href = '".$redirect_to."';</script>";
header("Location: $redirect");
exit();
?>
I prefer to use javascript redirect, but in somecase when user have not javascript enabled in his browser, I am using PHP redirect as backup redirect but sometime I am getting header already sent error on php redirect code and sometime I am not getting that error.
if I use exit() after redirect by javascript, I will not able to
redirect user if he have javascript disabled in his browser.
my question is there any way to stop php code if javascript redirect was success? I am not getting idea what I have to do for handle my situation.
Let me know if any expert can help me to solve puzzle.
Thanks!
Well, you are a web developer using PHP and Javascript.
One thing to remember, PHP code always runs first on the server. It's a server-side language, so no matter how you arrange your lines of code, your php code will finish running. Then, the client source code (HTML, CSS, JavaScript) is sent to the browser and executed on it (Client-side).
And next, the job of redirecting is always on the client side, the server doesn't actually redirect people to another site. What actually happens is that your php source code generates a redirect command that sends the browser for a redirect.
Another thing, in php, any work related to the header() function needs to be executed before any content is generated. That is, it must run at the top, before any method echo, exit, print,... or content block.
When deploying a php application, if you already use header("Location: ....") then it makes no sense to use javascript directives, as the browser will prioritize handling the redirect in the header first! !
The source code should really be:
<?php
$redirect = "https://yahoo.com";
header("Location: $redirect");
?>
Another way if you still prefer using javascript redirects and are compatible with javascript disabled, that is to use the tag meta[http-equiv="refresh"]. Refer to the following example:
<?php
$redirect_to = "https://google.com";
?>
<meta http-equiv="refresh" content="5;URL='<?php echo $redirect_to; ?>'" />
<script>location.href = "<?php echo $redirect_to; ?>";</script>
The number 5 appears in the content of the meta specifying the countdown (seconds) the browser will redirect when the page has finished loading. When the page cannot execute javascript, after 5 seconds the page will redirect.

block direct access to file but allow access through jquerys load function

I'm using jQuery to display a certain page to a user through it's .load() function. I am doing this to allow user customization to the website, allowing them to fit it to their needs.
At the moment, I am trying to display the file feed.php inside of a container within main.php;
I have come across a problem where I would like to prevent direct access to the file (i.e: going directly to the path of it (./feed.php)), but still allowing it to be served through the .load() function.
If I use the .htaccess deny from all method for this, I get a 403 on that specific part of the page. I can't find any other solution to this problem; disallowing me to achieve what I want.
This is my current (simplified) script and html:
<script type="text/javascript">
$("#dock-left-container").load("feed.php"); // load feed.php into the dock-left-container div
</script>
<div class="dock-leftside" id="dock-left-container"></div> // dock-left-container div
If anyone could suggest a solution through .htaccess, php, or even a completely different way to do this, I'd be very grateful!
Thanks in advance.
Please follow below steps to achieve:
In the .load function of jquery post a security code.
In the Feed.php page place a PHP condition if the posted security_code params found and match with security_code passed in the .load then only allow to access the page otherwise restrict.
Please follow below changes in your existing code to achieve it.
JS
<?php
$_SESSION['security_code'] = randomCode();
?>
<script type="text/javascript">
$("#dock-left-container").load("feed.php", {
security_code: '<?= $_SESSION['security_code']; ?>'
}); // load feed.php into the dock-left-container div
</script>
PHP
Place php condition in the top of feed.php
if(isset($_POST['security_code']) && $_POST['security_code'] == $_SESSION['security_code']){
//Feed.php page's all the stuff will go here
}else{
echo "No direct access of this page will be allowed.";
}
feed.php:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
readfile('myfeed.xml');
} else {
header('HTTP/1.0 403 Forbidden');
}
jQuery sends a HTTP_X_REQUESTED_WITH header by default. This is not, by far, anything remotely secure since HTTP headers are easily sent/spoofed. But it will stop the occasional user trying to access the feed directly.
You can, additionaly, check the $_SERVER['HTTP_REFERER'] header (but, again, this is easily spoofed) and, ofcourse, use your normal session logic to make sure the user is logged on if that's a requirement to access the feed.
Either way: there's no way to make this 'water tight'. If your browser can (should be able to) access the feed in some way then it's simply a matter of opening the debugger, having a look at the actual request sent in the network tab and sending the exact same headers/request to get to the file from, say, Curl. Actually, you will see the response of the request (i.e. the actual feed) in the debugger as well.
Repeat after me: if my (or a user's) browser can access the feed 'from jQuery' (via an AJAX request or whatever) then the feed is accessible to that user if he's even just a little bit more persistent than giving up immediately. Only using a session will keep out 'unauthorized' users because it relies on being logged in. After having logged in the request is visible no matter what and that request can be 'forged' to be sent from any other application no matter what.

Java script redirect with header

Let me try and explain as best as I can,
I have the following code in my login.php:
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
This ensures that if a user has logged in successfully, the url will always display mysite.com/home.php on all pages, this works fine for all php redirects using href="another_page".
However this does not work for javascript redirects using window.top.location.href="another_page", this instead redirects with the full url name (eg: mysite.com/java_redirected_page) instead of mysite.com/home.php. How can I get javascript redirects to work with headers as well, just like php does.
use this - window.location.href = 'home.php'; rather than window.top.location.href = 'home.php';
JavaScript is client side interpreter, it can't change headers from your server, while PHP generates responses from your web server, like Apache or nginx.
So the answer is that you can't change the way javascript redirects.
It looks like you want to have a nice result with your url, the only thing i can think of is MVC.
Never heard of it? Read this link http://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488
Its just a nice way to seperate your Backend from your Frontend and with that your redirects would work nicely.
Sad part about is, you would have to rethink yoru whole page, which is pretty timeconsuming because you would have to restructre everything.
Hope it helps

Setting Cookie on click

I'm having an issue creating / setting a cookie on the click of a link, is there a proper way to do this? Either PHP or Javascript is fine.
<html>
<a href="2.html" id="cookie">
<div class="yes">
<p>Yes</p>
</div>
</a>
</html>
<script>
$("a#cookie").bind("click", function() {
});
</script>
<?php
setcookie( "cookie")
?>
Obviously both JS and PHP wouldn't exist in the same instance it was just to show what I have.
You can't mix JavaScript and PHP. By the time your JavaScript code loads, your PHP code would have already executed.
In your case, it may be easier for you to set cookies without using PHP.
$("a#cookie").bind("click", function() {
document.cookie="cookie=value";
});
Here is a good example of setting cookies with javascript w3schools demo And I doubt it will be possible to set cookies to other domains except the origin of the page.
With PHP it is done in the next way: 1st you send http request to the server using javascript native xhr or jquery etc. and then php script must set cookie headers and return back to client. In this case browser will automatically set cookies received in headers.

Open a PHP page with window.location in Javascript is not working

How do I open a php page from javascript function ?
window.location = "http://www.google.com";
window.location.href = "http://www.google.com";
location.href = "http://www.google.com";
None of them is working.
Even put in php.ini
allow_url_fopen = on
What is wrong at my approach?
If you have this javascript embedded within <script> tags it should work:
<script type="text/javascript">
window.location = "http://www.google.com";
</script>
However, you cannot cause a PHP script to be included within a page you are writing with thsi javascript function: It will only redirect the browser to google or whatever other page you have set in window.location. You can include a PHP script from within a PHP page using the PHP include() or require() functions:
<?php
include('file.php');
?>
window.location = "http://www.google.com";
Should work..
I think your javascript code contain some error so it is not working.
So php.ini's line allow_url_fopen has nothing to do with this. It is to allow or not a url to be given to the fopen function of PHP.
Here what you want to do is to redirect a user to another page using window.location = '/page.php'.
Unless by open you meant getting loading inside the actual page, in this case have a look at the mdn documentation about XHR. And you should be using jQuery's load function.
window.location.href = "http://www.google.com";
That will only redirect the user to Google.
But you can't load a page in a JS variable, every browser have a "cross-domain" restriction (unless the page is on the same domain as you JS file & your visitor).

Categories

Resources