Good morning, I am dealing with an existing code and I need to solve a problem:
When you write a URL without logging into the Web, you can see the page in question (except the layout), what I need is to redirect to the login to avoid this.
So you can see the page without logging in
Checking the code I have seen that it is like this:
layout.php
<body>
<?php if(isset($_SESSION["user_id"])):?>
HTML code (Logo, menu...)
<?php else:?>
<?php
View::load("login");
?>
<?php endif;?>
</body>
If I change "View::load("login");" to "header("Location: index.php"); exit();", it causes an Infinite loop and does not load anything.
I have investigated a lot in Stackoverflow and other websites but I do not find the solution. Any ideas?
UPDATE:
index-view.php
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>LegoBox</h1>
</div>
</div>
</div>
login-view.php
<?php
if(Session::getUID()!=""){
print "<script>window.location='index.php?view=home';</script>";
}
?>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<?php if(isset($_COOKIE['password_updated'])):?>
<div class="alert alert-success">
<p><i class='glyphicon glyphicon-off'></i> Se ha cambiado la contraseña exitosamente.</p>
<p>Pruebe iniciar sesion con su nueva contraseña.</p>
</div>
<?php setcookie("password_updated","",time()-18600);
endif; ?>
<div class="card">
<div class="card-header" data-background-color="lemon">
<h4 class="title">Acceder</h4>
</div>
<div class="card-content table-responsive">
<form accept-charset="UTF-8" role="form" method="post" action="index.php?view=processlogin">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Usuario" name="mail" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Contraseña" name="password" type="password" value="">
</div>
<input class="btn btn-primary btn-block" type="submit" value="Iniciar Sesion" style="background-color:#339c24">
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
processlogin-view.php
<?php
if(Session::getUID()=="") {
$user = $_POST['mail'];
$pass = sha1(md5($_POST['password']));
$base = new Database();
$con = $base->connect();
$sql = "select * from user where (email= \"".$user."\" or username= \"".$user."\") and password= \"".$pass."\" and is_active=1";
//print $sql;
$query = $con->query($sql);
$found = false;
$userid = null;
while($r = $query->fetch_array()){
$found = true ;
$userid = $r['id'];
}
if($found==true) {
// print $userid;
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
$_SESSION['user_id']=$userid;
// setcookie('userid',$userid);
// print $_SESSION['userid'];
print "Cargando ... $user";
print "<script>window.location='index.php?view=home';</script>";
}else {
print "<script>window.location='index.php?view=login';</script>";
}
}else{
print "<script>window.location='index.php?view=home';</script>";
}
?>
Related
I would like to know how to run 2 or more input files in the same form, I have to upload some documents by using php, I made separate forms and they work, but I need to all together however I dont know how. I need to put only two forms as example actually I need to put 3 but the 3rd is larger so it would be much code to read with an example putting only two I would be able to do the rest.
Note: Form 1 and Form to upload data to different tables.
Form 1
<div class="container">
<?php
if(isset($_POST['uploadBtn'])){
$fileName=$_FILES['myFile']['name'];
$fileTmpName=$_FILES['myFile']['tmp_name'];
$fileExtension=pathinfo($fileName,PATHINFO_EXTENSION);
$allowedType = array('csv');
if(!in_array($fileExtension,$allowedType)){?>
<div class="alert alert-danger">
INVALID FILE
</div>
<?php }else{
$handle = fopen($fileTmpName, 'r');
$k = 0;
$energies = array ();
while (($myData = fgetcsv($handle,1000,',')) !== FALSE) {
$k++;
if ( $k > 1 ) {
$energies[] = $myData[3];
}
}
list($e1, $e2, $e3) = $energies;
$query = "INSERT INTO metlab.resultados_impacto_junta (energy1, energy2, energy3) VALUES ($e1, $e2, $e3)";
$run = mysql_query($query);
if(!$run){
die("error in uploading file".mysql_error());
}else{ ?>
<div class="alert alert-success">
SUCCESS
</div>
<?php }
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<h3 class="text-center">
RESULTS
</h3></hr>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="file" name="myFile" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="submit" name ="uploadBtn" class="btn btn-info">
</div>
</div>
</div>
</form>
Form 2
<div class="container">
<?php
if(isset($_POST['uploadBtn'])){
$fileName=$_FILES['myFile']['name'];
$fileTmpName=$_FILES['myFile']['tmp_name'];
//RUTA DEL ARCHIVO
$fileExtension=pathinfo($fileName,PATHINFO_EXTENSION);
//FORMATOS DE ARCHIVO PERMITIDOS
$allowedType = array('csv');
if(!in_array($fileExtension,$allowedType)){?>
<div class="alert alert-danger">
INVALID FILE
</div>
<?php }else{
$handle = fopen($fileTmpName, 'r');
$k = 0;
while (($myData = fgetcsv($handle,1000,','))!== FALSE){
$k++;
if ( $k > 4 ) {
$valor_dureza = $myData[3];
$query = "INSERT INTO metlab.resultados_tension_junta (size,yield,tensile,ra,elongacion)
VALUES ('".$valor_dureza."')";
$run = mysql_query($query);
}
}
if(!$run){
die("error in uploading file".mysql_error());
}else{ ?>
<div class="alert alert-success">
SUCCESS
</div>
<?php }
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<h3 class="text-center">
RESULTS
</h3></hr>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="file" name="myFile" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="submit" name ="uploadBtn" class="btn btn-info">
</div>
</div>
</div>
</form>
I would like a form like this:
With the Fk I would know which number the 3 docs belong to.
I solved the problem myself I just changed the vars of the forms and thats all, Its a dirty and bad solution but it works for now.
Currently looking to implement functionality to edit details in MySQL database via a HTML page. The page itself shows all data in the database which matches the unique id of the user who is is logged in via a PHP session and echos that data to input boxes in a while loop.
When the user makes changes to the input text and hits the save changes link it then calls the edit endpoint which in turn calls the edit SQL function in a functions file.
I'm using an anchor tag wrapped in a button to send the id of the row that is being edited and all this sits inside a POST action form.
However the input texts are only showing as blank as if the endpoint is not receiving the text in the input field, and despite trying quite a few different methods I can't seem to get a result.
Code for Web page (not whole page but only concerned code)
<?php
$connect =mysqli_connect('localhost','root','','micaddy');
$id_query = mysqli_query($connect, "SELECT unique_id FROM users WHERE email = '{$_SESSION['login_user']}'");
$id_array = mysqli_fetch_assoc($id_query);
$uid = $id_array['unique_id'];
$result = mysqli_query($connect, "SELECT * FROM clubs WHERE user_id =
'$uid'");
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading clearfix"><h3 class="panel-title"><strong>Your Golfbag</strong><button type="button" class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#addModal">Add Club</button></h3></div>
<?php while($row=mysqli_fetch_assoc($result)):?>
  <span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong><?php echo $row['club_type'];?></strong></h3></div>
<div class="panel-body">
<form id="" method="POST" action="editClub.php">
<div class="form-group">
<label for="clubType">Club ID</label>
<input type="text" readonly="" class="form-control" id="inputClubType" value="<?php echo $row['id'];?>" name="clubIdInput">
</div>
<div class="form-group">
<label for="clubBrand">Type</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['club_type'];?>" name="clubTypeInput">
</div>
<div class="form-group">
<label for="clubBrand">Brand</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['brand'];?>" name="clubBrandInput">
</div>
<div class="form-group">
<label for="clubNum">Number or Type</label>
<input type="text" class="form-control" id="inputclubNum" value="<?php echo $row['club_number'];?>" name="clubNumInput">
</div>
<div id="deleteClub">
<button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
<button type="button" class="btn btn-info btn-lg"><?php echo "<a href='editClub.php?id=".$row['id']."'>Save Changes</a>" ?></button>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</form>
</div>
</div>
</div>
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong>Club Image</strong></h3></div>
<div class="panel-body">
<div class="form-group">
<img src="club_images/<?php echo $row['clubImg']; ?>" class="img-rounded" width="250px" height="250px" alt="Image"/>
</div>
</div>
</div>
</div>
</div>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</div>
<?php endwhile;?>
</div>
</div>
</div>
</div>
The edit endpoint:
<?php
session_start();
$error='';
require_once '../include/DB_Functions.php';
$db = new DB_Functions();
if(empty($_POST['clubBrandInput']) || empty($_POST['clubNumInput'])){
$_SESSION['message'] = "Warning: Some fields are blank! Please try again";
header("Location: golfbag.php");
} else{
if(isset($_POST['clubBrandInput']) && isset($_POST['clubTypeInput']) && isset($_POST['clubNumInput'])){
$brand = $_POST['clubBrandInput'];
$type = $_POST['clubTypeInput'];
$num = $_POST['clubNumInput'];
$id = $_GET['id'];
$club = $db->editclub($brand, $type, $num, $id);
if($club) {
header("Location: golfbag.php");
$_SESSION['message'] = "Success! Details edited.";
}else{
header("Location: golfbag.php");
echo $error;
}
}
}
?>
The function method:
public function editClub($brand, $type, $num, $id){
$stmt = $this->conn->prepare("UPDATE clubs SET brand = '$brand', club_type = '$type', club_number = '$num' WHERE id = '$id'");
$result = $stmt->execute();
$stmt->close();
if($result){
$stmt = $this->conn->prepare("SELECT * FROM clubs WHERE user_id = ?");
$stmt->bind_param("s", $uid);
$stmt->execute();
$club = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $club;
}else{
return false;
}
}
You do not have a <form> defined in this HTML.
You are also clicking an anchor link <button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
even though it is in a button.
Therefore you will only pass the id=".$row['id']." parameter to the endpoint and that will be passed in the $_GET array and not the $_POST array
I am redirecting a user to a page named "forgot_pass" in such a way
"forgot_pass.php?code='$code'&username='$hidden_username'>".
But when user clicks on link for redirection the url seems like this
http://localhost/Validation/forgot_pass.php?code=
and there is no any page displayed.
The variables passed in url have values as i have already checked it. But they are not displaying when sent in url.
Help me in solving this issue.
reset.php
<?php
ini_set("display_errors", TRUE);
require_once './include/db_connection.php';
$pass = $_POST['pass'];
$pass1 = $_POST['pass1'];
$code = $_GET['code'];
$hidden_username = $_POST['username'];
if($pass == $pass1)
{
echo 'Password Changed !';
}
else
{
echo "Passowrd must match
<a href='forgot_pass.php?code='$code'&username='$hidden_username'>Try Again</a>
";
}
forgot_pass.php
<?php
ini_set("display_errors", TRUE);
require_once './include/db_connection.php';
if(isset($_GET['code']))
{
$get_code = (isset($_GET['code'])? $_GET['code'] : null);
$get_username =(isset($_GET['username']) ? $_GET['username'] : null);
$match_code = mysqli_query($link, "select * from signup where username='$get_username'");
if(mysqli_num_rows($match_code) > 0)
{
while($row = mysqli_fetch_assoc($match_code))
{
$db_username = $row['username'];
$db_code = $row['paareset'];
}
}
if($get_username == $db_username && $get_code == $db_code)
{ ?>
<html>
<head>
<meta charset="UTF-8">
<title>Change Password</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-body">
<div class="text-center">
<h3><i class="fa fa-pencil fa-4x"></i></h3>
<h2 class="text-center">New Password?</h2>
<div class="panel-body">
<form class="form" method="post"
action= "reset_pass.php?code=<?php echo $get_code ?>"
<fieldset>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil color-blue"></i></span>
<input name="pass" placeholder="New Password" class="form-control" type="password" required="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil color-blue"></i></span>
<input name="pass1" placeholder="Re-type Password" class="form-control" type="password" required="">
<input type="hidden" name="username" value="<?php echo $db_username ?>">
</div>
</div>
<div class="form-group">
<input class="btn btn-lg btn-primary btn-block" name="send" value="Change Password" type="submit">
</div>
<div class="form-group">
<span style="color: red"><?php if(isset($message['mail'])) {echo $message['mail']; } ?></span>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
}
} // End if (isset['code'])
if(!isset($_GET['code']))
{
?>
<html>
<head>
</head>
<body>
// Here i am displaying another form that gets email address and sends email
</body>
</html>
<?php
}
Remove single-quotes around the arguments, you are using them to delimit the URL so don't use them inside the URL (or at least escape them) :
echo "Password must match <a href='forgot_pass.php?code=$code&username=$hidden_username'>Try Again</a>";
Try with this way
echo "Passowrd must match
Try Again"
you have mismatch in columns
try to change your code to
echo "Passowrd must match
<a href='forgot_pass.php?code=".$code."&username=".$hidden_username".'>Try Again</a>
"
Please check if your filenames are correct.
You named: reset.php and forgot_pass.php
In forgot_pass.php your action goes towards reset_pass.php
remove single quote
"forgot_pass.php?code=$code&username=$hidden_username>"
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
Log in page looks like not redirecting to the next page how do i fix this kind of problem? Log in page looks like not redirecting to the next page and still stick on index.php page how do i fix this error.... i think the session is the problem?
index.php
<?php include('header.php'); ?>
<?php include('navbar.php'); ?>
<div class="container">
<div class="margin-top">
<div class="row">
<div class="span12">
<div class="login">
<div class="log_txt">
<p><strong>Please Enter the Details Below..</strong></p>
</div>
<form class="form-horizontal" method="POST">
<div class="control-group">
<label class="control-label" for="inputEmail">Username</label>
<div class="controls">
<input type="text" name="username" id="username" placeholder="Username" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="password" name="password" id="password" placeholder="Password" required>
</div>
</div>
<div class="control-group">
<div class="controls">
<button id="login" name="submit" type="submit" class="btn"><i class="icon-signin icon-large"></i> Submit</button>
</div>
</div>
<?php
if (isset($_POST['submit'])){
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($dbcon, $query)or die(mysql_error());
$num_row = mysqli_num_rows($result);
$row=mysql_fetch_array($result);
if( $num_row > 0 ) {
header('location:../admin_uplbcdc/dashboard.php');
$_SESSION['id']=$row['user_id'];
}
else{ ?>
<div class="alert alert-danger">Access Denied</div>
<?php
}}
?>
</form>
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php') ?>
dashboard.php
<?php require_once('../db/dbcon.php'); ?>
<?php include('../admin_uplbcdc/session.php'); ?>
<?php include('../admin_uplbcdc/header_2.php'); ?>
<?php include('../admin_uplbcdc/navbar.php'); ?>
<div class="container">
<div class="margin-top">
<div class="row">
<?php include('../admin_uplbcdc/head.php'); ?>
<div class="span2">
<?php include('../admin_uplbcdc/sidebar.php'); ?>
</div>
<div class="span10" align="center">
<br/> <br/>
<?php include('../admin_uplbcdc/slider.php'); ?>
</div>
</div>
</div>
</div>
<?php include('footer.php'); ?>
Set correctly error reporting and see the Warnings.
You can't start session or redirect using header when there is any output before, move session_start to the top of PHP script.
index.php
<?php include('header.php'); ?>
<?php include('navbar.php'); ?>
<?php
session_start();
if (isset($_POST['submit'])) {
// all PHP code goes here
}
?>
HTML goes here
Basically if the user comes to the page they get a form where they type in their username. That then checks against the db and then adds a generated key to their row in the db and emails the key link to them. The link brings them back to the same page but with a different form asking to update their password.
This is where my problem lies. The script first checks if that key exists. Even though it does exist I keep getting the uh oh key does not exist error. I've read through it a few times, taken breaks and still can't get it. Hopefully someone here can catch the issue!
Snippet of the problem:
<?php
if ($_GET['do'] == "password") {
$forgetKeyEmail = mysql_real_escape_string($_GET['key']);
if ($forgetKeyEmail !== "") {
$keyQuery = mysql_query("SELECT * FROM users WHERE forgetKey = '$forgetKeyEmail' LIMIT 1");
$keyCheck - mysql_num_rows($keyQuery);
if ($keyCheck == 1) {
?>
form goes here to update password
<?php
if ($_GET['do'] == "update") {
$hasher = new PasswordHash(10, false);
$resetPasswdord = $hasher->HashPassword(mysql_real_escape_string($_POST['inputPassword']));
$resetPassword = $_POST['inputPassword'];
if ($_POST['inputPassword'] !== "") {
mysql_query("UPDATE users SET password = '$resetPassword' WHERE forgetKey = '$forgetKeyEmail'");
echo "g";
?>
success message
<?php
}
else {
?>
empty field message
<?php
}
}
}
else{
?>
incorrect key message (what I keep getting)
<?php
}
}
}
Full code:
<?php
if ($_GET['do'] == "password") {
$forgetKeyEmail = mysql_real_escape_string($_GET['key']);
if ($forgetKeyEmail !== "") {
$keyQuery = mysql_query("SELECT * FROM users WHERE forgetKey = '$forgetKeyEmail' LIMIT 1");
$keyCheck - mysql_num_rows($keyQuery);
if ($keyCheck == 1) {
?>
<form method="POST"class="form-horizontal" action="?do=update&key=<?php echo $forgetKeyEmail; ?>" >
<div class="control-group">
<label class="control-label" for="inputPassword">New Password</label>
<div class="controls">
<input type="text" id="inputPassword" name="inputPassword" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Reset!</button>
</div>
</div>
</form>
<?php
if ($_GET['do'] == "update") {
$hasher = new PasswordHash(10, false);
$resetPasswdord = $hasher->HashPassword(mysql_real_escape_string($_POST['inputPassword']));
$resetPassword = $_POST['inputPassword'];
if ($_POST['inputPassword'] !== "") {
mysql_query("UPDATE users SET password = '$resetPassword' WHERE forgetKey = '$forgetKeyEmail'");
echo "g";
?>
<div class="alert alert-success" style="margin:0;">
<strong>Woooo!</strong> Your password has been changed, you can now login.
</div>
<?php
}
else {
?>
<div class="alert alert-error" style="margin:0;">
<strong>Woops!</strong> You need to fill out a password!
</div>
<?php
}
}
}
else{
?>
<div class="alert alert-error" style="margin:0;">
<strong>Uh oh!</strong> That key is incorrect.
</div>
<?php
}
}
}
elseif ($_GET['do'] == "reset") {
$resetUsername = mysql_real_escape_string($_POST['inputUser']);
if ($resetUsername !== "") {
$checkQuery = mysql_query("SELECT * FROM users WHERE username = '$resetUsername' LIMIT 1");
$checkExist = mysql_num_rows($checkQuery);
$userData = mysql_fetch_array($checkQuery);
$mailEmail = $userData['email'];
if ($checkExist == 1) {
$forgetKey = genRandomString() . genRandomString();
mysql_query("UPDATE users SET forgetKey = '$forgetKey' WHERE username = '$resetUsername'");
$message = "Hey there, ".$resetUsername." - We've received a request to reset your password. <br /><br /> Please click the following link to do so: <a href=\"http://localhost/vanilla/forgot.php?do=reset&key=".$forgetKey."\"";
echo $forgetKey;
mail($mailEmail, 'realvanil.la Password Reset', $message);
?>
<div class="alert alert-info" style="margin:0;">
An email has been sent to <strong><?php echo $userData['email']; ?></strong> with your reset information!
</div>
<?php
}
else {
?>
<div class="alert alert-error">
<strong>Uh oh!</strong> We can't seem to find an account with that username. Remember, it's your Minecraft username!
</div>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
}
else {
?>
<div class="alert alert-error">
<strong>Uh oh!</strong> You need to tell us your username ;)
</div>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
}
else {
?>
<form method="POST"class="form-horizontal" action="?do=reset" >
<div class="control-group">
<label class="control-label" for="inputUser">Username</label>
<div class="controls">
<input type="text" id="inputUser" name="inputUser" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Send Email!</button>
</div>
</div>
</form>
<?php
}
?>
you may want to edit you script so it does not have any syntax errors.
$keyCheck - mysql_num_rows($keyQuery);
change to
$keyCheck = mysql_num_rows($keyQuery);