Due to some unforeseen reason, I cannot use a *.php extension for my page. And I need to put conditional redirection in the page.
I plan to use *.html, and javascript/Ajax to call a PHP which evaluates the condition
and accordingly sends back a redirection command.
The condition is being evaluated, but how can I give a redirection command from this internal PHP is not clear to me.
You can actually map all your .html files to .php using .htaccess.
If that doesn't work for you, your logic should be as follows:
PHP:
echo json_encode(array("redirect_url" => $url));
Javascript with jQuery (assuming you require AJAX to redirect):
$.getJSON("PHP/Controller/Url", function(data) {
window.location.href = data.redirect_url;
});
Javascript (if you simply serve a static html file)
<script>
window.location.href = "redirect_url";
</script>
You can use
window.location = "http://new-url"
or
window.location.href = "http://new-url"
In JS,
location.assign("http://www.google.com")
will redirect your current frame to Google.
So don't send redirect header in PHP, send "flags" in response body and use JS to redirect.
Related
I apologize for my bad english :)
I'm doing php file with ajax request. json response comes in the format of. but in some cases can be redirect. In this case I want the redirect of the page.
Could you please help me. Thank's.
Example PHP File :
<?php
$status = $_POST['status'];
if($status == 'a'){
// return json response
}else{
echo "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>";
}
?>
Example JS File :
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
});
You can issue the redirect in the usual way, by returning a 3xx response with a Location header. The browser will follow the redirect (it doesn't make the JavaScript code doing the ajax call handle it).
So for instance, if you want to issue a 301 ("permanent moved"):
header('Location: http://www.google.com',true,301);
exit;
(I didn't know the specifics of how to issue the 3xx in PHP, but found them in this answer).
Side note: I doubt www.google.com is going to work, I assume that was just an example.
Use window.location = "http://www.yoururl.com"; to issue a redirect via JS.
In your php file replace php redirection with javascript redirection like this:
<script type="text/javascript">
window.location.replace("http://www.google.com");
</script>
I'm using cURL to access a number of different pages. I want an elegant way of checking if the page has a javascript redirect. I could check for presence of a window.location in the body, but because it may be inside a .js file or using a library like jQuery, it seems like any solution wouldn't be perfect. Anyone have any ideas?
Thanks to Ikstar for pointing out phantomjs I worked out the following example:
test.js
var page = require('webpage').create();
var testUrls = [
"http://www.google.nl",
"http://www.example.com"
];
function testNextUrl()
{
var testUrl = testUrls.shift();
page.open(testUrl, function() {
var hasRedirect = page.url.indexOf(testUrl) !== 0;
console.log(testUrl + ": " + hasRedirect.toString());
if (testUrls.length) {
testNextUrl();
} else {
phantom.exit();
}
});
}
testNextUrl();
Result:
D:\Tools\phantomjs-1.7.0-windows>phantomjs test.js
http://www.google.nl: false
http://www.example.com: true
You cannot do it by only parsing the script. Only executing will show you he true flow of the page's JS.
One way to imitate the execution is to have different levels of code level which has a redirection. The top most would be under <script> tag and any redirects here would be a straight redirect. If any redirects are found inside functions then you have to track the structure of the program and make a guess.
Depending on the purpose of using Curl and actually needing the redirect on the page. It is possible to incorporate headless framework like PhantomJS (http://phantomjs.org/) to do the necessary browsing. You would be able to see whether a redirect would happen as well as track any other javascript executing on the page.
It is impossible to detect the presence of a redirect just analyzing the webpage source code.
The undecidable Halting problem can be encoded in JavaScript. The algorithm may halt, resulting in the generation of a redirect, or run forever. Since we do not know if the code will halt, it is impossible also to decide if the redirect will be executed or not.
I have an index.html file which I want to run some jQuery when it is loaded. Essentially, I want to check to see if a user is already logged in based on some session variables.
So index.html will contain some jQuery which uses $(document).ready(function(){ });
In this function I want to just fire autheticate.php which checks to see if $_SESSION['user'] is set, if it is then it will redirect to home page otherwise it will redirect to login page...
how can I post in jQuery without having a html form? I just want to post to a url...
EDIT:
Based on #jondavidjohn's answer I changed my web app so that it uses index.php to check sessions:
<?php
session_start();
if(isset($_SESSION['username'])){
//go to home page
header('Location: ...home.html');
}else{
//go to login page
header('Location: ...login.html');
}
?>
It is surely possible doing this with javascript, but it is not secure at all...
You need to be checking at the server level for $_SESSION['user'] before you even send the content to the browser...
My answer would be to do the checking / redirecting with PHP before anything gets sent to the browser, it will be less complicated and more secure...
The reason a javascript solution is insecure is that you are relying on a technology that resides and is controlled by the client to control access to protected areas.
You can use $.post(url, params), where url is a string and params is a hash with your post data.
$.post("/authenticate.php",null,function(data){
// do something based on response returned
if($data){alert("authenticated");}
else
alert("not authenticated");
});
in your php file
if(isset($_SESSION['user']))
{
echo true;
}
else
return false;
Use $.post() to post data via AJAX to a page. Doing it this way won't allow the PHP script to redirect the user, you'll have to java JavaScript redirect them.
$.post('/path/to/page.php', {userID: 5}, function(data){
// Use window.location to redirect
});
Or, you can create a "fake" <form> element, and post that.
var $form = $('<form/>').attr({
method: 'post',
action: '/path/to/page.php'
});
var $input = $('<input/>').attr({
name: 'userID',
type: 'text'
}).val('5');
$input.appendTo($form);
$form.submit();
I suggest you take #jondavidjohn's advice, and have PHP redirect the user before the page is sent to the browser. That's much more secure.
Why bother with the AJAX request? Since you're building the page with PHP, just have PHP embed some variables in a JavaScript block:
<script type="text/javascript">
var is_logged_in = <?php echo $_SESSION['logged_in'] ? 'true' : 'false' ?>;
</script>
This'd save you an HTTP round-trip to retrieve data you already had available.
My code structure is like this:
some php code here...
html
head
script
some ajax code here
/script
after running the ajax code, I want to redirect/refresh the page. How can I do it?
Thanks,
Try window.location.reload() in the ajax request success callback.
you can do it with JavaScript; place in AJax callback function:
window.location.reload(); //for refresh
window.location = "http://www.google.com/"; //redirect
Use JavaScript:http://www.tizag.com/javascriptT/javascriptredirect.php
Using window.location="URL" you can send the client to "URL".
But keep in mind that this will not work for people with JavaScript disabled (but so will you AJAX-code).
The best thing to do is to follow the ajax with a javascript redirect using document.location.href='page.html' as you're already relying on running some code in the browser.
Well it depends on what JavaScript version the browser has, but the latest versions should support:
window.location.reload(false);
Have that run on the callback from your AJAX routine.
I would like to create a basic URL rewrite using frames.
I don't have access to .htaccess to do mod_rewrite.
Is there a way using PHP, jQuery, JavaScript etc. to detect which URL has been clicked on and then open URL in new frame?
Ex: user clicks on /index.php?12345 it will open in framed window /pages/12345/index.html and if they click on /index.php?54321 URL will open in framed window /pages/54321/index.html
I don't think I really understand what you mean. Usually url rewrite works like this:
User clicks on http://example.com/content/example
Which is the rewritten to http://example.com/index.php?cat=content&page=example
You can somewhat fake this effect by making your links into http://example.com/index.php/content/example the webserver will still request the page index.php, in which you can then read the part after index.php (but before a query string) with
$_SERVER['PATH_INFO']
and then parse that to get what you need.
PHP.net on $_SERVER['PATH_INFO']
Contains any client-provided pathname
information trailing the actual script
filename but preceding the query
string, if available. For instance, if
the current script was accessed via
the URL
http://www.example.com/php/path_info.php/some/stuff?foo=bar,
then $_SERVER['PATH_INFO'] would
contain /some/stuff.
A PHP solution would be something along these lines:
if (!empty($_REQUEST)) {
$page = array_pop($_REQUEST);
if (is_numeric($page)) {
header("Location: pages/$page/index.html");
exit;
}
}
If I've really understand what you want, I think it's easy.
When the user clicks it calls a JQuery function which sends the content of the link to PHP with AJAX. After that, PHP analyses the link, gets the content of the page (with include()) and sends that to JQuery via JSON.
Such jquery might help,
jQuery(function($){
//this prevents all link elments' default behaviour
//when you click they won't navigate the page
$("a").click(function(){
//you get the links href
var actual_url = $(this).attr("href");
var new_url = "";
//[write your code here for converting actual url to new one]
//and open the new url in the frame you want
window.parent.yourFrameName.location = new_url;
//necessary for preventing default behaviour
return false;
});
});
Sinan.
Best solution is to use jquery to check if link was visited and then change link's target to _blank.
You could use plugin from this site:
link text and then execute such code:
$('a').visited(function () {
$(this).attr('target','_blank');
});
I think it is what are you looking for.