I have a simple login page but i am having trouble displaying the logged in page. When the form is submitted, the same login page is displayed. I will have to click refresh or F5 before i can see the logged in page. I tried the no-cache (meta tag) but my problem is that the cookies are also gone (i couldn't store state).
By the way, my login uses redirect. The form submit calls a different page doing the validation and then redirects back to the same page but supposedly with different content (login form should not be there anymore).
I believe this is basic but unfortunately couldn't find an answer elsewhere.
Thanks.
Update:
Here are some codes:
Login page has ExtJs Form with submit:
login.getForm().getEl().dom.action='bridge.php/login';
login.getForm().getEl().dom.submit();
bridge.php is a rest client to another server:
snippet:
<?php
//echo $HTTP_SERVER_VARS['PATH_INFO'];
require_once "RESTclient.php";
require_once "http_request.php";
$rest = new RESTclient();
$http_req = new httpRequest();
//$headers = $http_req->headers();
$headers = apache_request_headers();
foreach($headers as $key => $value) {
if($key != "Cookie" && $key != "Content-Type"){
unset($headers[$key]);
}
}
//$headers["Content-Type"] = "";
$inputs = array_merge($_GET, $_POST);
//$inputs = array_merge($inputs, $_);
$url = "http://another_server/rest_service_here";
$path = $HTTP_SERVER_VARS['PATH_INFO'];
$server = $url.$path;
$rest->createRequest("$server",$http_req->method(),$inputs);
$rest->addHeaders($headers);
$rest->setBody($http_req->body());
$rest->sendRequest();
// get the headers now
$responseheaders = $rest->getResponseHeaders();
$responsecookies = $rest->getResponseCookies();
if ($responseheaders != null) {
foreach ($responseheaders as $key => $value) {
header($key.': '.$value);
}
}
if ($responsecookies != null) {
foreach ($responsecookies as $key => $value) {
$name = $value['name'];
$val = $value['value'];
setcookie($name, $val);
}
}
if($path=='/login') {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logging in</title>
<meta HTTP-EQUIV="REFRESH" content="0; url=/new_index.php">
</HEAD>
<BODY>
Redirecting to homepage...
</BODY>
</HTML>
<?php
} else {
$output = $rest->getResponse();
//$output = $output." ".$http_req->method();
// start doing something about the output.
//echo $http_req->body();
//echo $http_req->raw();
echo $output;
//var_dump($headers);
}
?>
As long as you're doing the following...
Always set/delete the login cookie before you output anything
Always re-direct after you've set the cookie. Ideally this should be to a page with a different URL (even if it's only a different query string), but failing that one that isn't cached should work fine.
As soon as you re-direct (via a header('Location: ...'); call) end script processing via exit.
..then all should be well. That said, as #Jon says post some code and we can take a look.
Related
I'm processing some data from external pages. The pages can be accessed sequentially, i.e http://localhost/info/1.html, http://localhost/info/2.html, http://localhost/info/3.html, ....
<?php
$id = 0;
$id = intval($_GET['id'])+1;
$url = 'http://localhost/info/'.$id.'.html';
if (!$html = #file_get_contents($url)) {
$url = 'http://localhost/crawler.php?id='.$id;
//header("Location: ".$url);
echo '<html><script>window.location.href = "'.$url.'";</script> </html>';
die();
}
//process data
$url = 'http://localhost/crawler.php?id='.$id;
//header("Location: ".$url);
echo '<html><script>window.location.href = "'.$url.'";</script></html>';
die();
?>
The problem is the PHP redirect stops showing error the page is not redirecting properly, and redirect using JavaScript looks like slower. Already tried using header with removing the echo.
**
Is there any way to speed up the process ?
**
I am relatively new to php but I am encountering an error that is about to drive me INSANE.
I am working on creating a webpage that lets you browse files on the server.
However, for some reason, the $_SESSION variable keeps itself set, EVEN AFTER BROWSER RESTARTS...
Please, I am begging you, tell me why this happens before I go insane.
This is my code:
<html>
<?php
session_start();
if(!isset($_GET['location'])) {
header('Location: ?location=G:');
session_unset();
}
/* THIS IS WHERE THE BUG OCCURS. THIS VARIABLE SHOULD BE EMPTY ON BROWSER OPEN!!!! ?!?!?!?! I HAVE ADDED NOTHING TO SESSION YET*/
var_dump($_SESSION);
if(!isset($_SESSION['path'])) {
$_SESSION['path'] = array();
$_SESSION['path'][0] = $_GET['location'];
}
echo '<br><br><br><br><br><br>';
//* If user presses back and isn't in home folder, return to previous folder... *//
if(isset($_GET['back']) && $_GET['back'] == true && sizeof($_SESSION['path']) > 0) {
unset($_SESSION['path'][sizeof($_SESSION['path'])-1]);
$_GET['location'] = $_SESSION['path'][sizeof($_SESSION['path'])-1];
header ('Location: ?back=false');
} else {
//*However if user hasn't pressed back make sure that session is properly updated with location *//
if($_SESSION['path'][sizeof($_SESSION['path'])-1] != $_GET['location']) {
array_push($_SESSION['path'], $_GET['location']);
}
}
//*Now build the link from the session path array*//
$full_link = '';
for($i = 0; $i < sizeof($_SESSION['path']); $i++) {
$full_link .= $_SESSION['path'][$i];
$full_link .= '/';
}
//*Get all files from link path*//
$filesbrowsed = glob($full_link . '*');
?>
<head>
<meta charset "utf8">
<title>File Browser</title>
<link href="filebrowserstyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<header>
<ul class = "navigation">
<li>Home</li>
<li>Back</li>
<li></li>
<li></li>
</ul>
</header>
<div class = 'current_files'>
<?php
//* Now display all files in current path *//
for($i = 0; $i < sizeof($filesbrowsed); $i++) {
$filename = substr($filesbrowsed[$i], strlen($full_link), strlen($filesbrowsed[$i]) - strlen($full_link));
echo '<div>' . $filename . '</div>';
}
?>
</div>
</body>
</html>
Thank you all in advance!!!
You should unset session before redirecting user to another location.
<html>
<?php
session_start();
if(!isset($_GET['location'])) {
session_unset();
session_destroy();
header('Location: ?location=G:');
}
/* THIS IS WHERE THE BUG OCCURS. THIS VARIABLE SHOULD BE EMPTY ON BROWSER OPEN!!!! ?!?!?!?! I HAVE ADDED NOTHING TO SESSION YET*/
var_dump($_SESSION);
To delete all data in the session:
$_SESSION = [];
I'm having an issue with a simple verification file, it doesn't redirect to index page after successful login.
Basically the login.php file has the html form for login, the form calls auth.php file which already has the login data and decides if your login and password is correct or not. Now it should redirect to index.php after successful login but it doesn't , instead it just cleans up the form in the login.php file and you keep trying , BUT if you refresh the page ( after successful login ) you get auto redirected to index page.
Fixed! changed the code to something even simpler than that.
if($logindata[$_POST["username"]]==$_POST["password"])
This bit doesn't look correct; maybe you were looking for:
if($logindata[$_POST["password"]]==$_POST["password"])
Sometimes headers does not work well for some reasons, instead try to use a simple html redirect like this:
<?php
$usernames = array("user1", "user2");
$passwords = array("pass1", "pass2");
$page = "index.php";
for($i=0;$i<count($usernames);$i++){
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++) {
if ($usernames[$i] == $_POST["username"]) {
$found = 1;
}
}
if ($found == 0) {
$redirect_url = "./login.php?login_error=1"
}
if($logindata[$_POST["username"]]==$_POST["password"]) {
session_start();
$_SESSION["username"]=$_POST["username"];
$redirect_url = "./index.php"
}
else {
$redirect_url = "./login.php?login_error=2"
}
echo "<center><br><br><br><p>You will be redirected in about 2 seconds. If not, click this link: <a href='$redirect_url'>Back</a></p></center>";
?>
<html>
<head>
<meta http-equiv="refresh" content="2;url='<?php echo "$redirect_url"; ?>'/>
<title>Redirecting...</title>
</head>
</html>
<?php
exit;
?>
I presumed the redirect location is in the same folder of the php file. Adjust the var $redirect_url path of they aren't.
I have a holding page that redirects to another page once that page has been created.
At the moment my solution is to refresh the holding page every 5s, checking each time if the new page has been created. Problem is that the page flickers.
Is there a way to do this with a simple while loop in the header but still display the holding page html. Thanks. Current code is below.
<?php
ob_start();
$id = escapeshellarg($_GET['id']);
$id = str_replace("'", "", $id);
$url = 'http://sub.testxxx.com/'. $id . '/index.html';
$handle = #fopen($url,'r');
if(!$handle) {
header("Refresh: 5; url=http://testxxx.com/loading.php?id=".$id);
ob_flush;
} else {
sleep(5);
header("Location: http://sub.testxxx.com/".$id);
}
?>
<html>
...........
</html>
<?
ob_flush;
?>
I would split it into two parts: 1) a server side script (php) checking if the page has been created and 2) a client side script (javascript) calling the php script via ajax every n-seconds. If the php script returns true, the js redirects the client to its new destination. no need to reload the whole page - and no flickering ;)
Do you need some example code?
checkPage.php:
<?php
$id = escapeshellarg($_GET['id']);
$id = str_replace("'", "", $id);
$url = 'http://sub.testxxx.com/'. $id . '/index.html';
$handle = #fopen($url,'r');
if(!$handle) {
return true;
} else {
return false;
}
?>
Page.php:
<html>
<head></head>
<body>
<script type="text/javascript">
$.ajax({
url: 'checkPage.php?id=someId',
success: function(data) {
$(location).attr('href','http://sub.testxxx.com/someId/index.html');
}
});
</script>
</body>
</html>
After a successful login (i.e when user clicks the login button after entering the username and password), based on the user type I want to send user to a specific page. Below is my code. (Here, if usertype is 'employee', he should be taken to "data-update.php" page after clicking 'login' button.)
This is the code in the index.php page:
// This file is the home page.
// Require the configuration before any PHP code as the configuration controls error reporting:
require ('config.inc.php');
// The config file also starts the session.
// Require the database connection:
require (MYSQL);
// If it's a POST request, handle the login attempt:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include ('login.inc.php');
}
/* PAGE CONTENT STARTS HERE! */
?>
<!DOCTYPE html>
<html lang="en">
<head>
...
This is the code in the login.inc.php page:
<?php
// This is the login page for the site.
// It's included by index.php, which receives the login form data.
// Array for recording errors:
$login_errors = array();
// Validate the username:
// Validate the password:
if (empty($login_errors)) { // OK to proceed!
// Query the database:
$q = "SELECT id, type FROM users WHERE (username='$u' AND pass='" . get_password_hash($p) . "')";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // A match was made.
// Get the data:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Store the data in a session:
$_SESSION['user_id'] = $row[0];
$_SESSION['username'] = $u;
if ($row[1] == 'employee') {
reset_sms_update_session();
header("Location: http://".BASE_URL."data-update.php");
exit;
}
elseif ($row[1] == 'client'){
header("Location: http://".BASE_URL."About.html");
exit;
}
...
And this is a partial code in "data-update.php" page:
// Start the session:
session_start();
function redirect_invalid_user($check = 'user_id', $destination = 'index.php', $protocol = 'http://') {
// Check for the session item:
if (!isset($_SESSION[$check])) {
$url = $protocol . BASE_URL . $destination; // Define the URL.
header("Location: $url");
exit(); // Quit the script.
}
} // End of redirect_invalid_user() function.
//Redirect to index.php if user not logged in
redirect_invalid_user( );
/* PAGE CONTENT STARTS HERE! */
?>
<!DOCTYPE html>
...
The problem is that, in Google Chrome when user clicks the login button, he is first taken to the index.php page (where the redirection occurs) and then he has to click login button again to be taken to "data-update.php" page.
Why is this happening in Google Chrome?
(FYI: this does not happen in XAMP testing environment in my local PC.)
This does NOT happen in Firefox or IE8 (i.e. user is taken to "data-update.php" first time login button is clicked).
Please help.
I solved this by setting a permanent redirect from CPanel in my webserver for http://example.com to http://www.example.com.