// 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.
Related
Okey guys , i try to secure page with access code ,but page is not secrued if some people write in url pagename.php page is loading without checked my code is. Code is work after put correct access code redirect to my page but , page is not secured client visit page without code after write in url my page .....
<?php
include ('modules/conf.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$secretcode = mysqli_real_escape_string($db,$_POST['secretcode']);
$sql = "SELECT * FROM password WHERE password = '$secretcode'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $secretcode;
session_start();
header("location: question.php");
}else {
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("", "Съжеляваме вашият код е невалиден");';
echo '}, 1000);</script>';
}
}
?>
<div class="section">
<div class="container-fluid gamebox">
<div class="row">
<div class="col-md-6">
<div class="secretcode">
<h1 class="text-center">въведете код от брошурата</h1>
<form action="" method="post" class="formsecretcode text-center">
<input type="secretcode" id="codeverify" name="secretcode" placeholder="въведете вашият код">
<input type="submit" class="buttonsubmit" name="submit" value="провери код">
</form>
</div>
</div>
As I stated in comments and seeing that nobody posted an answer so far, am submitting the following.
Check to see if the session is set (with an optional "if { equal to something }"), and if not, else { kick them out }.
The logic is, and to be part of every page using sessions that you wish to protect and assuming $secretcode equals 12345 as an example:
<?php
session_start();
if (isset($_SESSION['login_user']) && $_SESSION['login_user'] == '12345'){
// Do something
}
else {
// Do something else
}
It's also best to add exit; after header, otherwise your code may want to continue executing.
Reference:
http://php.net/manual/en/function.header.php
Footnotes:
You don't need to use session_start(); twice as that may trigger that the session was already started.
Use it once and at the "top" of every page, while making sure you're not outputting before header.
References:
http://php.net/manual/en/features.sessions.php
How to fix "Headers already sent" error in PHP
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional notes:
You could optionally check for both a username and secret word in the query which makes it a bit more unique.
$username = "Johnny B. Good";
$sql = "SELECT * FROM password
WHERE username = '$username'
AND password = '$secretcode'";
Unless you're only checking for a secret code only, then leave your query the way it is now.
i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.
I'm new to web development.
Right now I'm working on a login feature on a site. I used Javascript/AJAX to fetch the username and password and send it to a PHP file for verification on the MYSQL database. That's what I'm about to make.
My question is why can't the header() function working properly? I want after the user login she is redirected to the profile page (profile.php)
Here's snippet of the PHP (login.php):
$query = "SELECT * from user WHERE username = '$uname' AND password = md5('$pass');";
$ret = mysql_query($query) or die(mysql_error());
if(!$ret) {
$msg = "Invalid query " . mysql_error() . "\n";
$msg .= "Whole query " . $query;
die($msg);
}
$userid = -1;
while($row = mysql_fetch_array($ret)) {
$userid = $row["ID"];
}
$cnt = mysql_num_rows($ret);
if($cnt == 1) {
session_start();
$_SESSION["userid"] = $userid;
$_SESSION["uname"] = $uname;
echo "You have logged in successfully!";
header("Location: profile.php");
} else {
echo "Wrong Username/Password";
}
And here's for the Javascript (an AJAX function):
var obj;
var url = "login.php";
var params = "uname=" + document.getElementsByName("uname")[0].value + "&pass=" + document.getElementsByName("pass")[0].value;
if(window.XMLHttpRequest) { // Major browsers
obj = new XMLHttpRequest();
obj.open("POST",url,true);
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.setRequestHeader("Content-length", params.length);
obj.setRequestHeader("Connection", "close");
obj.onreadystatechange = function() {
if(obj.readyState == 4) {
if(obj.status == 200) {
// success
} else {
alert("Problem in returned data" + "Error status=" + obj.status);
}
}
}
obj.send(params);
I don't think the redirect will work with AJAX. This is what will happen:
AJAX request is sent to login.php
login.php sends back a header with Location: profile.php
The browser then redirects and fetches profile.php
The results of profile.php is then passed to your XMLHttpRequest Object.
A way to get the AJAX response to redirect your page is to do this:
The response from login.php returns a JSON response containing the status code (302 or 301) and the location to redirect to.
The response itself has a status code of 200 (successful).
The process the JSON response and check the status code for 302 or 301 and redirect to the location.
You need to take out the echo statement before header(). Header won't work if anything has been output to the browser before it is called.
Here's the php doc on that.
What's happening exactly?
After header() is called in php, php still executes the rest of the script unless you stick an exit; after the header() call. This is only if you don't want to execute the rest of login.php
You can one thing replace your code header("Location: profile.php"); by echo "window.location.href='profile.php'; and replace your success function as
if(obj.status == 200) {
eval(obj.responseText);
}
Thats it. now a response will be evaluated by script and will redirect your page on profile.php
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.
I have created a page called profile.php that gets a value from mainpage.php, by using "get" method. But, If the value that was sent from mainpage.php is empty or wrong, the page redirects to the mainpage.php. However, I used "post" method in profile.php that allows users to post something in profile.php. So that If the user submits something, profile.php reloads and reloading profile.php makes the variable, that i get from mainpage, empty and directs the page to mainpage.php unwillingly.How can i fix it? Codes;
$another_user = $_GET['username'];//gets a value from mainpage.php
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."'");
$sent = mysql_fetch_array($check);
if(!$sent)
{
header('Location: mainpage.php');
exit();
}
//some codes around here
<form action="profile.php" method="post">
Commet: <input type="text" name="comment" placeholder = "comments?"/>
<input type="submit"/>
</form>
<?php
if(isset($_POST['comment'])&&!($_POST['comment']=""))
{
$writing = $_POST['comment'];
echo $writing;
}
Thanks
To start with you have a syntax error in your second line, as the colors show you already. So change it into:
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."')";
There are many solutions to your problem. One of them could be to verify which page the user is coming from. If this is mainpage.php you can verify the username and if this is profile.php you should check the comment variable.
You can make use of the $_SERVER['HTTP_REFERER'] variable to check which is the referer. So something like:
if ($_SERVER['HTTP_REFERER'] == "http://www.domain.com/mainpage.php") {
//do your username check
}
else if ($_SERVER['HTTP_REFERER'] == "http://www.domain.com/profile.php") {
//do your comment check
}
Another and maybe easier way would be to make sure that your $_POST['comment'] has not been set when dealing with the username.. Like this:
if (!isset($_POST['comment'])) {
$another_user = $_GET['username'];//gets a value from mainpage.php
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."'");
$sent = mysql_fetch_array($check);
if(!$sent) {
header('Location: mainpage.php');
exit();
}
}
else {
//...
}