I am trying to make login with angularjs and PHP. But hitting problem I cannot understand why?
<?php
date_default_timezone_set("Asia/Bangkok");
session_start();
$data = json_decode(file_get_contents("php://input"));
$email = mysql_real_escape_string($data->email);
$password = mysql_real_escape_string($data->password);
{
$con=mysqli_connect("localhost","root","thanh03021986","erp");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_query($con,"SELECT email, password FROM user WHERE email = '$email'");
$numrow = mysqli_num_rows($query);
if($numrow > 0){
while($rows = mysqli_fetch_array($query))
{
$dbemail = $rows['email'];
$dbpassword = $rows['password'];
}
$con->close();
if($email==$dbemail && $password == $dbpassword){
$_SESSION['uid'] = $email;
header('location:/A.php');
}
}
}
?>
When the If() return true the $_SESSION['uid'] = $email works but the header('location:/A.php'); does not work. I try to put header('location:/A.php'); out of IF(), header works ??? Please help and explain?
The session_start function must be called first as well as the header function must me called before any HTML code.
See the headerfunction manual
The redirection with header, you must be sure that there's nothing in the html already (not even the <html> tag), and an absolute path. So, you should do this in order to work:
header('Location: http://pathblablabla.bla/A.php');
Also, note that I put Location, not location. Not sure if it's case-sensitive, but just in case...
Related
I am trying to redirect a user after a logging with saving the session. I am trying to do that using header function in PHP:
<?php
include 'phpconnect.php';
if(isset($_POST['but_submit'])){
$uname = mysqli_real_escape_string($conn,$_POST['txt_uname']);
$password = mysqli_real_escape_string($conn,$_POST['txt_pwd']);
if ($uname != "" && $password != ""){
$sql_query = "select count(*) as cntAdmin from admindb where adminID='".$uname."' and AdminPassword='".$password."'";
$result = mysqli_query($conn,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntAdmin'];
if($count > 0){
$_SESSION['uname'] = $uname;
header('Location: adminpanel.php');
}else{
die("Invalid username and password");
}
}
}
?>
Credentials are correct, all other functions (for example registration form with inputting some data into the database) is working. Echo function call works fine if credentials are wrong, so database connection is fine. I suppose something wrong with header, but have no clue.
try this
header("Location: /adminpanel.php");
as a last resort you can use this
echo "<script>";
echo "window.location.href='/adminpanel.php'";
echo "</script>";
I'm trying to show welcome message with user name. I have a session setted up, everything is working without errors, however I can't make user name appear next to "welcome". I read loads of posts, most of the suggestions were asking to add session_start(); before echo. Still nothing..
Here is code for session.php if someone could help me:
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["user_name"])) {
header('Location: login.php');
}
?>
And here is code for the profile page where user name should appear:
<?php
include('session.php'); //file shown above
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i>
<?php
session_start();
echo $_SESSION['fname'];
?>
</i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
I'm just learning PHP and this is a basic test.
Thank You for any information.
Hava a nice day !
UPDATE:
loginscript.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$uname=$_POST['uname'];
$password=$_POST['password'];
$conn = mysql_connect("**.***.***.***", "*********", "*********");
$uname = stripslashes($uname);
$password = stripslashes($password);
$uname = mysql_real_escape_string($uname);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("*********", $conn);
$query = mysql_query("select * from WebsiteUsers where password='$password' AND uname='$uname'", $conn);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$uname;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
mysql_close($conn);
}
}
?>
logout.php:
<?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>
You need to quote your array keys, for example you have:
$_SESSION["UserID"] = $row[user_id];
But this should in fact be
$_SESSION["UserID"] = $row['user_id'];
Note the single quotes around the array key in $row. I see you use double quotes and I think there are minor differences but the point is, use quotes around array key strings. Please read https://stackoverflow.com/a/2317969/3536236 .
There also might be an issue that you set the value with double quotes and then call the value with single quotes --
$_SESSION["fname"] = $row['fname'];
print $_SESSION['fname'];
But that's just a theory there.
Further debugging:
Print_r($_SESSION); <== what does this give you after the values are set?
Use MySQLi or PDO rather than MySQL_ as this is now deprecated and should no longer be used.
Add exit; after your header relocation calls. Because the rest of the script will still execute before the relocation header call is run, so you need to tell the script to stop executing as soon as you reach the header(location: ) point.
Be consistent and have all single ' or all double " quotes in your array key identifiers.
Remove session_start() from inside your HTML, this function call MUST be at the very start/ top of the page, and nowhere else. You can replace this session_Start with the print_r referenced above, for debugging purposes.
Debugging
First step, you need to enable errors on your page, so whatever page you're working on add this code to the top:
error_reporting(E_ALL);
ini_set('display_errors', 1);
This will output any errors the code fines to your browser when you run the page. Extremely useful and informative.
Next, I will show you the process you need to establish where in the logic chain the data is being "lost".
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
print_r($result) <== should return something like "this is a type 4 element". False shows your DB is empty or your MySQL code is bad.
$row = mysql_fetch_array($result);
var_dump($row) <== should return the values from the DB. It should also tell you what data type this variable is, as you demand an array, below:
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
}
else {
die("This will display if the IF statement does not show TRUE.");
}
The die statement above would show you that the error is not in the session but more in your handling of the MySQL output,
I reaffirm you should use single quotes on all your array keys everywhere! Keep it consistent!!
Restructure your MySQL to be more this shape:
mysql_query($query) or print_r("line ".__LINE__.": ".mysql_error());
So that if there is any issue with your MySQL code it is found and shown to you. Much of programming is about finding where the error comes from, rather than the error itself.
Try something like this:
$db_result = mysql_fetch_array($result); $row = $db_result[0];
instead of :
$row = mysql_fetch_array($result);
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
if(mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if($_SESSION["fname"]=="") {// changed from $_SESSION['user_name'],checks if sesison is empty , will redirect to login page.
header('Location: login.php');
}
?>
You have to use session_start(); in the start of the profile.php
I have this login code. When I write on a page to request someones username, I enter <?php echo $username; ?> but that's not the only thing I want to echo on the page. I also want to echo $website but that doesn't work. What am I doing wrong in the code? Is there a way to also add $website to the code so it echo's the
require('connect.php');
session_start();
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
}else{
echo "";
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Your username is " . $username;
echo "Your domain is " . $website;
} else {
?>
<!--loginpage follows here -->
EDIT
I mean when a customer registers their account, they need to fill out a form and they need to enter their site. How can I, by using the above script, echo the $website so they see their own website printed?
I think you want:
$website = $_SERVER['HTTP_REFERER'];
You can check out all of the possible information at the PHP man page at http://php.net/manual/en/reserved.variables.server.php.
EDIT - as per your edited question.
You simple need to check the $_POST for whatever they entered in a "webpage" field.
Such as and using a ternary operator:
$webpage = (isset($_POST['webpage'])) ? $_POST['webpage'] : "No webpage entered";
To get the name if the website use the php $_SERVER global variable
$website=$_SERVER['SERVER_NAME'];
if i didn't misunderstood your question,try to set $website variable like this way
if(isset($_POST['website'])){
$website=$_POST['website']; //from your form
}else{
$website="user didn't provide website name";
}
Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version
Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}
I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.
I am new to PHP scripting and come from Java background. Here is a trivial thing which has turned into a brainteaser for me as of now. So here is the problem, I assigned a variable some value and when try to use that value inside if/else statement that variable actually doesn't posses the previous assigned value to it. Here is the code:-
<?php
session_start();
$email = $_POST["Email"];
$password = $_POST["Password"];
$db_username="root";
$db_password="root";
$database="mydb";
$localhost = "mysql";
$con = mysql_connect($localhost,$db_username,$db_password);
mysql_select_db($database,$con) or die( "Unable to select database");
$query = "select * from photobook.users where email ='$email' and password ='$password';" ;
$result = mysql_query($query);
$num=mysql_num_rows($result);
if($num == 1){
while($row = mysql_fetch_array($result))
{
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
}
header("location: home.php");
}
else{
include "photoBookProtocol.php";
print "<br>email value after photobookprotocol file include is $email";
print "<br>password value after photobookprotocol file include is $password";
$obj=new Protocol();
$var = $obj->loginCheck($email,$password);
print "value of var received is $var";
if($var == 0){
session_destroy();
print "<br>user does not exist";
//header("location: login.php");
}
else{
$_SESSION['email'] = $var[0];
$_SESSION['username'] = $var[1];
print "<br>user exists";
header("location: home.php");
}
}
mysql_close($con);
?>
So when I pass the $email and $password in loginCheck($email, $password) inside "else" clause there is nothing passed. Any idea why this is happening?
There is nothing wrong with your variable scope, so either:
There is nothing in the POST data
The include overwrites the two variables
loginCheck() is receiving the correct variables but there is a bug within the function
As a side note, since your script depends on POST data, you should have a condition to check if the required data is present before proceeding:
if(isset($_POST['Email'], $_POST['Password']))
{
// something posted
}