I'm working on a log in session, and I want to display errors on the same page, for example - "Invalid Password" or "User does not exist".
Heres my code:
<?php
session_start();
mysql_connect('mysql.database.com','user','database')or die ('Connection Failed: '.mysql_error());
mysql_select_db('database')or die ('Error when selecting Database: '.mysql_error());
function remove($mensaje)
{
$nopermitidos = array("'",'\\','<','>',"\"");
$mensaje = str_replace($nopermitidos, "", $mensaje);
return $mensaje;
}
if(trim($_POST["usuario"]) != "" && trim($_POST["password"]) != "")
{
$usuario = strtolower(htmlentities($_POST["usuario"], ENT_QUOTES));
$password = $_POST["password"];
$result = mysql_query('SELECT password, usuario FROM usuarios WHERE usuario=\''.$usuario.'\'');
if($row = mysql_fetch_array($result)){
if($row["password"] == $password){
$_SESSION["k_username"] = $row['usuario'];
header( 'Location: diseno.php' ) ;
}else{
echo '<p class="message2">Invalid password</p>';
}
}else{
echo '<p class="message2"User does not exist</p>';
}
mysql_free_result($result);
}else{
echo '<p class="message2">Must enter a user and password</p>';
}
mysql_close();
?>
<SCRIPT LANGUAGE="javascript">
location.href = "index.php";
</SCRIPT>
As you can see that's my validation and action for the log in form. Instead of echoing errors in a new page I want to display it in the same page. I tried with javascript and it didn't work I used.
var page = document.URL = "http://www.mysite.com/login.php"
page.getElementById( 'wrongpassword' ).style.display = 'block';
All divs I want to display are set as none in the login.php file.
Anyone could help me?
The easiest way to accomplish this is to process the login and then include the PHP code which displays the normal page. I'm not sure how you've designed your site, but including index.php at the end might do the trick. Right now, you are using a JS redirect, which won't give you the result that you want.
Instead of echoing the message, I like to set a $message variable which includes the message. When you render the main page, simply echo this variable in the appropriate place if it is set.
For doing it simply you can make use of JQuery. I have done it on my website so I can say it really works.
Start your session, checking the values and either assign the value in global variables of javascript or print it there only
eg.
<?php
session_start();
//checking ur values
echo "<script src=\"js/jquery-1.8.3.min.js\"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
//you can assign values here or print error messages to any div
('.div_class').html("unuthorised user");
});
</script>";
?>
Here I have used a downloaded JQuery file from
http://jquery.com/download/
You can choose other wise to use the online version of this JQuery file. The syntax for that is
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
Feel free to get back in case of any further query/issues regarding the above code.
Related
I need to be able to orientate with a php code that communicates with data from a mysql database, this file is called "validate.php". Its main functions are to verify that there are no empty fields at the time of login, and assign a profile if a user has value 1 and another profile when the value is 0 in the records of the table "users"
The idea is that "validate.php" check the user and direct it to a page according to their profile, but I can not do that.
My code is:
<?php
require('access_db.php');
session_start();
if(isset($_POST['send'])) { // We verify that the form data has been sent
//We verify that the user_name and the user_pass fields are not empty
if(empty($_POST['user_name']) || empty($_POST['user_pass'])) {
echo"
<script>
alert('Please enter your username and password correctly ');
location.replace('login.php');
</script>
";
}else {
//"Clean" the form fields of possible malicious code
$user_name = mysqli_real_escape_string($link,trim($_POST['user_name']));
$user_pass = mysqli_real_escape_string($link,trim($_POST['user_pass']));
// We verify that the data entered in the form match those of the DB
$query=mysqli_query($link,"select user_id,user_name,user_admin FROM users WHERE user_name='".$user_name."' and user_pass ='".$user_pass."'");
$row = mysqli_fetch_array($query);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row["user_name"];
$_SESSION['user_admin'] = $row["user_admin"];
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
{
}
}else{
header("Location: login.php");
}?>
My main problem is here:
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
When I login with my admin user in my page "login.php" you should check the information and go to a page according to your profile, only appears in the browser "http://localhost/proyect/validate.php" and the text "dashboard" on the page, But, if I write in the browser "http://localhost/proyect/dashboard.php" load the page with all the information.
I do not know what I'm doing wrong.
Someone can help me, I'll be very grateful, I've been on this for days.
Thanks.
Don't print, try this instead:
if($_SESSION['user_admin']==1){
header('location:dashboard.php');
exit;
}else{
header('location:dashboard2.php');
exit;
}
Thanks for the suggestion Magnus Eriksson
you need to redirect not echo out the contents of the php file
and also do check for { as there are extra ones
if($_SESSION['user_admin']==1){
header("Location: dashboard.php");
}else{
header("Location: dashboard2.php");
}
This question already has answers here:
Redirect to another page with a message
(6 answers)
Closed 8 months ago.
What's the best way to display a success message after redirecting to same page? I've been thinking about doing that with javascript but maybe there's a way to do this with Php? The user submit from profile.php and gets redirected to same page. I'd like to grab a variable... Can I concatenate after $_SERVER['HTTP_REFERER']? Whats the best approach?
here a snippet of code: query.php
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$stmt->close();
$db->close();
}
You could skip the session, and pass a url query parameter as a code or the message.
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?message=success1');
exit;
}
$stmt->close();
$db->close();
}
Then have code that checks for $_GET['message] ...etc
You can use sessions. Just start session, save message in global array $_SESSION, then in profile.php check if $_SESSION with your key is set and it isn't empty show it. After it you can unset your key in $_SESSION.
query.php
<?php
session_start();
//your code
if($stmt) {
$_SESSION['myMessage'] = 'Some message';
//your code
}
//rest of your code
profile.php
<?php
session_start();
//your code
if(isset($_SESSION['myMessage']) && $_SESSION['myMessage'] !== '') {
//display message or do with it what you want
}
//rest of code
If you're processing your form in the same page, then you don't have to do any redirection. The solution to achieve the desired result would be like this:
Put your form processing code at the very top of your PHP script i.e. profile.php page.
Use a boolean variable to hold the status of ->execute() statement, and use that same variable at later point of your code.
So the code would be like this:
// Declare a boolean variable at the beginning
$status = false;
// your code
$status = $stmt->execute();
$stmt->close();
$db->close();
}
if($status){
// Data submitted succesfully
}else{
// Data couldn't get submitted
}
If you want to process the form at the same file, you don't need to redirect again to the same page.
As mention by the other answer, you process the form at the top of the page.
To display a message after success or failure, you store the message in a variable. Later with the from you echo the message variable if it is set.
// Check if form was submitted
if(isset($_POST['submit'])) { // I name the submit button "submit"
// process the form
if ($stmt->execute()) {
$message = "<div> Success </div>";
} else {
$message = "<div> Failed </div>";
}
}
// Display The form and the message if not empty
if (! empty($message)) {
echo $message;
}
// Form
// script.js
$(document).ready(function(){
$(".loginProzor").hide();
$(".login").click(function(){
$(".loginProzor").fadeToggle(300);
});
$("#prijavi").click(function(){
if($("#user").val() == "" || $("#pass").val() == ""){
$("#labelGreska").html("Unesite korisničke podatke");
}
else{
$.post($("#forma").attr("action"), $("#forma :input").serialize(),
function(data){
$("#labelGreska").html(data);
});}
$("#forma").submit(function(){
return false;
});
});
});
// form
<form id="forma" action="login.php" method="post">
<label>Korisničko ime</label><br>
<input type="text" name="user" id="user"><br>
<label>Lozinka</label><br>
<input type="password" name="pass" id="pass"><br>
<input type="submit" value="Prijavi se" id="prijavi">
<label id="labelGreska"></label>
</form>
//login.php
<?php
include 'funkcije.php';
include 'spojiBazu.php';
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!$user){
$greske[] = 'Unesite korisničko ime';
}
$pass = md5($pass);
$ucitaj = mysql_query("select * from login where username = '$user' and password = '$pass'");
session_start();
if(mysql_num_rows($ucitaj) === 0){
echo 'Korisnički podaci nisu validni, molimo pokušajte ponovo.';
}else{
$korisnik = mysql_query("select username from login where username = '$user'");
$podatak = mysql_result($korisnik, 0);
$_SESSION['user'] = $podatak;
header("Location: index.php");
}
?>
Hello
I'm learning web development and I ran into a problem. I created simple login form. It evaluates some errors using jQuery and the rest of errors are evaluated using PHP. Everything works except Header command in PHP. When user succesfully logs in, header command should redirect to index.php so user can verify it is logged in, but in this case header tag don't work.
Before applying jQuery (all errors were handled by PHP) header command worked with no problems. Can you tell what's wrong here?
Details,
Since AJAX happens "behind the scenes" (so to speak) your redirect will just interrupt the response to your javascript handler. So PHP cannot redirect your browser now, jQuery can. So use jQuery to redirect the user.
You'll need to return the URL and have your callback kick the browser to a new location.
On this note, since you have to return data to the front end, you'll want to add a status or similar variable so that you can switch your front end behavior based on whether the call "failed" or not.
Exactly what Marc B pointed,
"You're doing the ajax call - the php header will redirect the ajax response... not the page that the user is currently sitting on. You will have to modify your javascript code in the client to change the location."
A javascript redirect is as simple as window.location.href = "http://mylocation";.
Solution to your problem,
JQUERY
// script.js
$(document).ready(function(){
$(".loginProzor").hide();
$(".login").click(function(){
$(".loginProzor").fadeToggle(300);
});
$("#prijavi").click(function(){
if($("#user").val() == "" || $("#pass").val() == ""){
$("#labelGreska").html("Unesite korisničke podatke");
}
else{
$.post($("#forma").attr("action"), $("#forma :input").serialize(),
function(data){
if(data=="success"){
window.location.href = "index.php";
} else{
alert("login failed");
}
});
}
$("#forma").submit(function(){
return false;
});
});
});
PHP
<?php
include 'funkcije.php';
include 'spojiBazu.php';
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!$user){
$greske[] = 'Unesite korisničko ime';
}
$pass = md5($pass);
$ucitaj = mysql_query("select * from login where username = '$user' and password = '$pass'");
session_start();
if(mysql_num_rows($ucitaj) === 0){
echo 'failed';
exit;
}else{
$korisnik = mysql_query("select username from login where username = '$user'");
$podatak = mysql_result($korisnik, 0);
$_SESSION['user'] = $podatak;
echo "success";
}
?>
from http://www.php.net/manual/en/function.header.php
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called.
You can try with a javascript redirection or remake your source code with the header at the begining
header() will not work after output has been echoed to the screen.
Check funkcije.php and spojiBazu.php to see if any echo happening. If they are you need to find a way to remove the echos from those to included files before you call header() in login.php.
I'm trying to redirect users of a web page to one of two different pages, depending on which of two buttons they click. My approach was to link each onclick event to a javascript function, which would in turn call a php function which uses the header() function to redirect to the appropriate page. Unfortunately, the latter of the two php functions, namely insertIntoTable(), is being called automatically each time the page loads and redirecting, without giving the user a chance to even look at the page with the buttons. I'm wondering if this is an artifact of way PHP is expanded? I don't really understand, becauseit seems like the wrapping javascript function shouldn't be called until the onclick event listener does so, and the php functions shouldn't be called until on the the javascript functions linked to onclick do so. Here is the code...
<?php
session_start();
?>
<html>
<head>
<script>
function createATable()
{
<?php createATable(); ?>
}
function insertIntoTable()
{
<?php insertIntoTable(); ?>
}
</script>
</head>
<body>
<?php
// Define our redirection functions for button click events
function createATable()
{
header("Location: http://codd.edu/Project2/createtable.php?<?php echo htmlspecialchars(SID); ?>");*/
}
function insertIntoTable()
{
header("Location: http://codd.edu/Project2/insertintotable.php?<?php echo htmlspecialchars(SID); ?>");*/
}
// Set session variables so that we don't need to worry about whether
// we're coming from sign in or registration - if $Session['user_name']
// isn't set, we know were coming from the sign in
if (!$_SESSION['user_name'])
{
$_SESSION['user_name'] = $_POST['nametextbox'];
$_SESSION['user_psswd'] = $_POST['psswdtextbox'];
echo "<br />setting session variables";
}
echo "<br />Not setting session variables";
// If we aren't setting the session variables, then we are coming from the
// registration page, and therefore know that this isn't an admin account
$_SESSION['is_admin'] = "false";
// Connect to database
$conn = mysql_connect("localhost", "601", "23");
or die('Could not connect: ' . mysql_error());
// Open database
mysql_select_db("601", $conn)
or die('Could not find database: ' . mysql_error());
// Get USER tuples, if any
$user = mysql_query("SELECT * FROM USERS WHERE name='$_SESSION[user_name]' AND password='$_SESSION[user_psswd]'");
// If there are no entries for this SELECT command, we cannot
// allow the user to log in
$num_user = mysql_num_rows($user);
if ($num_user < 1)
{
$_SESSION['is_user'] = "false";
header("Location: http://codd.edu/Project2/login.php?<?php echo htmlspecialchars(SID); ?>");
exit;
}
else
{
$_SESSION['user_id'] = SID;
$_SESSION['is_user'] = "true";
echo "Welcome ", $_SESSION['user_name'], "!";
echo "<br />User ID: " . $_SESSION['user_id'];
echo "<br /> User Password: " . $_SESSION['user_psswd'];
echo "Is valid user? " . $_SESSION['is_user'];
session_destroy();
echo "<button name='createtable' onclick='createATable()'>Create a Table</button>";
echo "<br /><button name='insert' onclick='insertIntoTable()'>Insert into Table</button>";
}
?>
</body>
</html>
I see no reason why createATable() shouldn't be called anytime the page is loaded. PHP is evaluated before javascript and on a different environment. Moreover, PHP allows you do define/declare a function after you call it, that is exactly what you're doing.
Pretend to be the PHP interpreter: it has no idea of what javascript is. You can even wrap the <?php createATable(); ?> line with yadayadayada ... qweryasdasd before and after it, and it will run.
Please, read this and see if it helps: http://www.developer.com/tech/article.php/923111/Client-side-Versus-Server-side-Coding---Part-1.htm
PS.: this is not related to your question, but please take a look at this: http://en.wikipedia.org/wiki/SQL_injection
Php runs on the server, the htnl output goes to the client.
Instead of trying to use php to redirect, use javascript or a simple a href.
I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.