I'm following a php video tutorial (it's not online sorry) from Lynda.com and used the following code, but I got the following error
Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.
could this be a problem with my code. i.e. the fact that the code has two redirect_to in the first 10 or 15 lines, or is it talking about something else?
<?php require_once("../../includes/initialize.php"); ?>
<? if(!$session->is_logged_in()){
redirect_to("login.php"); } ?>
<?php
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
if($_GET['clear'] == 'true') {
file_put_contents($logfile, '');
//add the first log entry
log_action('Logs Cleared', "by User ID {$session->user_id}");
//redirect to this same page so that the URL won't
//have "clear=true" anymore
redirect_to('logfile.php');
}
?>
<?php include_layout_templates('admin_header.php');?>
« Back<br/>
<br/>
<h2>Log File</h2>
<p>Clear log file</p>
<?php
if (file_exists($logfile) && is_readable($logfile) &&
$handle = fopen($logfile, 'r')) {//read
echo "<ul class=\"logentries\">";
while(!feof($handle)) {
$entry = fgets($handle);
if(trim($entry) != "") {
echo "<li>{$entry}</li>";
}
}
echo "</ul>";
fclose($handle);
} else {
echo "Could not read from {$logfile}.";
}
?>
//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} loggined in.");
redirect_to("index.php");
} else {
//username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else {//Form has not been submitted.
$username = "";
$password = "";
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Staff Login</h2>
<?php echo output_message($message); ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="<?php
echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="<?php
echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="login" />
</td>
</tr>
</table>
</form>
<?php include_layout_template('admin_footer.php'); ?>
You have an endless loop of redirecting.
"login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. etc.
You should probably make the redirect happen only when the current page is not "login.php"; i.e. remove that logic from this page.
<? if(!$session->is_logged_in()){
redirect_to("login.php"); } ?>
Therein lies your problem I think. You're checking on your login page, to see if someone is logged in or not. If they're not, you'll redirect to your login page, starting a new request, and it'll perform the check again.
Login page asks, is the user logged in? No! Redirect them to the login page
Login page asks, Is the user logged in? No! Redirect them to the login page
Login page asks, Is the user logged in? No! Redirect them to the login page
ad-infinitum
People shouldn't have to be logged in to use the login page, so remove the check to see if someone's logged in before they use said page.
Check if your login page redirects if you're not logged in.
Make sure there is no output before you redirect
Make sure you exit after you have done the redirect. In your code example you will end up with some whitespace before you call the redirect function as a result of that empty line between your require and if check. If I was you, I wouldn't jump in and out of php as much as you do when there is no need to. All the way down to your first link, I see only php, but yet you have 3 <?php and one <? (which is also a bad idea. I'd stick with using only <?php).
Related
Is there any solution like unset $msg or something, that, when I reload the page, the $msg stops?
here is my code:
index.php:
<form class="ligar" action="log.php" method="post">
<p class="lig"><input name="username" type="text" placeholder="Username"></p>
<p class="lig"><input name="password" type="password" placeholder="Password"></p>
<p class="lig"><input name="Entrar" type="submit" value="log"></p>
<p class="error"><?php if(isset($_GET['msg']))
echo $_GET['msg'];
?>
</p>
</form>
log.php:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='john' AND $password=='abc') {
header("Location:/detalhes.php");
} elseif ($username!='john' OR $password!='abc'){
$msg = "Wrong, try again.";
header("Location:http://localhost/index.php?msg=$msg");
}
?>
Something like this should do the job: (untested)
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='john' AND $password=='abc') {
header("Location:/detalhes.php");
} elseif ($username!='john' OR $password!='abc'){
$_SESSION['msg'] = "Wrong, try again.";
header("Location:http://localhost/index.php");
}
?>
log.php
<?
session_start();
<?php if(isset($_SESSION['msg']))
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
If I understand correctly, if first time you enter the wrong credentials, the log.php code redirects the page to
http://localhost/index.php?msg=Wrong,%20try%20again.
So if you reload the page via browser, obviosly the uri remains the same, so you still get the error message in the $_GET['msg'] variable.
EDIT I don't think there's a solution to that using only HTML+PHP.
You can convert the form post to an AJAX request and show/hide the error code via javascript, so you don'
t need to change the uri.
The web is full of easy examples on how to implement an AJAX login form.
EDIT Well, as #Stefano L said, you can use session cookies so you don't need to use any javascript at all.
I have an Index page with login form, a verification page called Login and content.
Index is fairly simple: if logged in, redirect to Content, otherwise display login form and POST to Login page
index.php:
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header('Location: content.php');
} else {
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> PHP Login </title>
</head>
<body>
<center>
<form method="POST" action="login.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="usr"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pswd"></td>
</tr>
<tr>
<td><input type="submit" name="login" value="Login"></td>
<td><input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
<?php } ?>
Then we have Login verification: compare the POST vars with coded variables, if all is good, set Session variables and redirect to content.
login.php:
<?php
session_start();
if($_POST['usr']=='user' && $_POST['pswd']=='password'){
$_SESSION['usr'] = 'user';
$_SESSION['pswd'] = 'password';
header('Location: content.php');
} else {
echo "post: ";
print_r ($_POST);
//header('Location: index.php');
}
?>
Then we have the Content page, check that the Session is set and display content, otherwise PRINT_R
content.php:
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
The process works, up to the Content page. I keep getting a blank SESSION array, and when I try going to Index, it pretends I never logged in. what am I missing?!
Edit: in The code above, content.php is trying to check if the session is set. If it is NOT set it will show me a blank array (for debugging purposes, but normally I want it to go back to index, since the user is not properly connected),
if it IS set, it will echo "you are logged in". It is also including a page called 'logoff.html' as that page has a button to destroy the session.
Even without the IF statement, simply running a print_r ($_SESSION); returns a blank array. This means there is no problem in the IF statement, but something that happens before it.
Solution: I didn't know about this before, but some hosting sites require some PHP set up, before they can store PHP sessions. I went to the knowledge base of my hosting service and searched for "session", and found an explanation on how to set up the php.ini file to save my sessions in the correct path.
Make sure sessions are configured properly. For example, is the session save handler set correctly? If using files, does it have permission to access the specified folder? If memcache, is that set up properly?
This would be the main reason for session variables to not be saved.
change this
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
i think in your code when session not set then it will print so change it with
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd']))
{
// session is set
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
}
else
{
/// session is not set
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
I'm trying to make a login page with session() function and I had some problem with the code, but I don't know why.
What I want to do after that is in my admin page I want it to say "welcome (the username that inserted in the form)", but I dont know how.
I tried with session() but its shows me:
PHPSESSID
What should I do?
This is the code
<?php
$sid = $_POST["username"];
session_start();
include("../inc/passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
$_SESSION["logged"]=$_POST["username"];
} else {
echo 'Incorrect username/password. Please, try again.';
};
};
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not
header('Location: index.php'); //// if user is logged show a message
} else { //// if not logged show login form
echo '<table align="center" border="0">
<h3 style="color: #555" align="center" class="">بالرجاء تسجيل الدخول للمتابعة</h3>
<form action="login.php" method="post"><input type="hidden" name="ac" value="log">
<tr><td>الاســـــــم</td><td>:</td><td><input type="text" name="username" size="20"> </td></tr>
<tr><td>كلمة السر</td><td>:</td><td><input type="password" name="password" size="20"> </td></tr>
<tr><td> </td><td> </td><td><input class="buttons" type="submit" value="تسجيل الدخول"></td></tr>
</form>
</table>';
};
?>
Just for knowledge:
Most important things to be remember.
Always start session after php tag starts.
e.g.
<?php
session_start();
If you start it like:
<?php
$sid = $_POST["username"];
session_start();
It will through error message : headers already sent etc
I would recommend taking a look at the piece of code:
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
$_SESSION["logged"]=$_POST["username"];
}
You need to make sure the $_SESSION["logged"] is actually set. Perhaps try performing an echo on it. If it is empty, it would be the logic not evaluating to true.
Also make sure you do a session_start() on your index.php page.
it wont work using session with the welcome thing
try by using mysql
like
when the admin puts it name and password
his name is putted in a table in mysql
and in the index for the admin page
you query the table
like
$username = $_POST['username'];
mysql_query(SELECT username FROM admins where username='$username');
Please i need your help with my script. I'm trying to post comments to news items on sections on my website only for users who are logged in. If they are not, they are shown a link to Login or Register, and the "Post A Comment" inputbox does not display.
Then when they login the form should display.
The form does not display, when they are not logged in, but it does not also show the form when they are logged in.
Please where could the broblem be.. Thank you for your time and patience. I apppreciate it.
<?php
if (!isset($_SESSION['username'])) {
echo "Login OR <a href=\"register.php\">Register</ a> to make a comment" ;
}
exit();
?>
<?php
if (isset($_POST['submit'])) {
//process form
}
?>
Post A Comment <br/>
<form action="<?php echo $_SERVER ['PHP_SELF']; ?>" method="post">
<textarea type="text" name = "comment_body" title='Post A Comment' class='OpenInput_Text' ></ textarea><br/>
<input type="submit" name="submit" value="Post Comment">
</form>
</div>
</div>
You will need to start your sessions.
Replace
<?php
if (!isset($_SESSION['username'])) {
With
<?php
session_start();
if (!isset($_SESSION['username'])) {
.. It's because you are exiting the script in with an
exit();
I think you want to push it one line up, to end the script if the user is not logged in.
Move the exit() inside if (!isset($_SESSION['username'])) { ... } instead of after it.
I am using PHP to build a very basic login script. However, the else from the ifelse statement shows by default before the user has even clicked log in.
Before the user has even tried to login they are greeted with this:
Warning: Cannot modify header information - headers already sent by (output started at /home/madhous3/public_html/dev/admin/index.php:12) in /home/madhous3/public_html/dev/admin/login.php on line 13
Sorry, please try again.
How do I stop this? However, if the user enters the details correctly, they are directed to the right page.
Code
index.php
<?php
include("login.php");
?>
<h1>Admin Area Login</h1>
<form method="post" action="login.php">
Username<input type="text" name="username" />
Password<input type="text" name="password" />
<input type="submit" name="log_in" value="Log In" />
</form>
login.php
<?php
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
}else{
header("location:index.php");
echo "Sorry, please try again.";
}
?>
Try removing the include("login.php") from index.php.
Instead, you should redirect back to index.php from your login.php with a flag specifying that the user entered the wrong information (if they failed the login).
index.php
<?php
if(isset($_REQUEST['fail'])) {
echo 'Login failed.';
}
?>
<h1>Admin Area Login</h1>
<form method="post" action="login.php">
Username<input type="text" name="username" />
Password<input type="text" name="password" />
<input type="submit" name="log_in" value="Log In" />
</form>
login.php
<?php
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
} else {
header("location:index.php?fail=1");
}
?>
OK, so what's happening is that in index.php you're including login.php at the start. At that time it imports everything from login.php. Since you're including it, the script is going to run.
At the load of the page index.php, the script on login.php starts. It defines those variables $username_inputted & $password_inputted as null, since the POST hasn't happened yet. Then the if block checks, finds null variables, then the else block fires since the variables aren't equal to the expected login info because they're null.
Therefore the echo fires and is displayed on the screen before anything is POSTed.
Nav_nav's solution should work well, since the only time the 'bad login' echo will be displayed is if someone entered something into the input fields, I just wanted to give you a rundown of the algorithm's reason for messing up.
try this
if (!empty($_POST['username']) && !empty($_POST['password'])) {
//define input vars
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
}else{
header("location:index.php");
echo "Sorry, please try again.";
}
}
First get rid of the header('location:login.php'). You can't send a header if you've already started sending any HTML to the browser. And if it did work, you'd get an endless loop of reloads.
Then:
You could check for $_POST ['submit'] and if it doesnt exist then don't show them the try again message.