index.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
email = $("#cs-username-1").val();
password = $("#cs-login-password-1").val();
if(email=='' || password=='')
{
$("#loginsuccess").html("<p id='red'>All fields are mandatory!<p>");
}
else
{
$.ajax({
type:"POST",
data:{"email":email,"password":password},
url:"login.php",
success: function(data)
{
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect) {
window.location.replace(data.redirect);
} else {
$("#loginsuccess").html('<p id="red">' + data.error + '</p>');
}
}
});
}
});
});
</script>
login.php
<?php
include("config.php");
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
$sql = mysqli_query($con,"select student_id from student where email='".$email."' and password='".$password."' and status='1'");
if (mysqli_num_rows($sql) > 0)
{
$results = mysqli_fetch_array($sql);
$_SESSION['student'] = $results['student_id'];
if (!isset($_POST))
{
header ("Location: dashboard.php");
}
else
{
echo json_encode(array('redirect' => "dashboard.php"));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
?>
dashboard.php
<?php
session_start();
echo $_SESSION['student'];
/*if(!isset($_SESSION['student']))
{
header("location: index.php");
}*/
include('assets/db/config.php');
?>
In this code I am simply create login module. Here, what happen I am create login via jQuery where I have login.php file and I am storing student_id inside the session variable but when I redirect to dashboard.php and echo $_SESSION['student'] then it throw an error i.e. Notice: Undefined index: student in C:\xampp\htdocs\test\dashboard.php on line 3 I don't know why where am I doing wrong? Please help me.
Thank You
Please start the session in login.php file :
include("config.php");
session_start();
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
Or put the session_start in config.php file
Related
I am working with https://www.thereverendmichael.com/3.0/
with a demo login of demo/demo (username/password). It's just too much code to post it all but I will post the integral parts I am having an issue with. The issue I am having is that for some reason when I attempt an Ajax query to an https page and attempt to set the successful $_GET variables as $_SESSION variables, they do not transfer over and it returns unauthorized access.
[form.php]
<?
session_start();
header('Access-Control-Allow-Origin: *');
if (!isset($_SESSION['id'])) {
?>
<html>
<head>
<script type="text/javascript">
alert("Unauthorized access. Redirecting to login page...");
window.location="https://www.thereverendmichael.com/3.0/index.php";
</script>
</head>
</html>
<? } ?>
[index.php]
$("#login-submit").click(function(){
$("#login-form").trigger("submit");
});
$("#login-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "https://www.thereverendmichael.com/3.0/login.php",
data: $("#login-form").serialize(),
cache: true,
AllowGet: true,
success: function(data)
{
switch(data)
{
case "1":
alert("Admin login successful. Redirecting...");
window.location = "https://www.thereverendmichael.com/console/admin.php";
break;
case "2":
alert("Login successful. Redirecting...");
window.location = "https://www.thereverendmichael.com/3.0/form.php";
break;
case "3":
alert("Username does not match account records. Please try again.");
break;
case "4":
alert("Password does not match account records. Please try again.");
break;
}
}
});
});
[login.php]
<?php
header('Access-Control-Allow-Origin: *');
$conn = mysql_connect("107.180.20.91", "redphyre", "Qazplm10!") or die(mysql_error());
$conn = mysql_select_db("mikenbrenda", $conn);
$user = $_GET['username'];
$pass = md5($_GET['password']);
$sql = "SELECT username,password,admin FROM users WHERE username = '$user'";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($res);
class SessionManager
{
static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
// Set the cookie name before we start.
session_name($name . '_Session');
// Set the domain to default to the current domain.
$domain = isset($domain) ? $domain : isset($_SERVER['SERVER_NAME']);
// Set the default secure value to whether the site is being accessed with SSL
$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
// Set the cookie settings and start the session
session_set_cookie_params($limit, $path, $domain, $secure, true);
session_start();
}
}
if ($row[0] == $user && $pass == $row[1]) {
SessionManager::sessionStart('login', 0, '/', 'www.thereverendmichael.com', true);
$_SESSION['id'] = $user;
if ($row[2] == "1") {
$_SESSION['admin'] = $row[2];
setcookie("admin", $row[2]);
echo "1";
}
else {
echo "2";
}
}
else {
if ($row[0] != $user) {
echo "3";
}
if ($row[1] != $pass) {
echo "4";
}
}
?>
I want to send data from php to php and in same time I also want to send data from js to php. I have one index.php which contains php and js part. In enrolled.php I want to collect my data. SQL injection or other security problems are not important. I do not get any error but it does not save to database.
Small part of index.php
<!DOCTYPE html>
<html lang="en">
<head>
//smt....Not important
</head>
<body>
//smt....Not important
<div id="dom-target" style="display: none;">
<?php
include_once "connection.php";
session_start();
$username = $_SESSION['username'];//coming from previous page.
echo htmlspecialchars($username); //for sending variable from php to js.
?>
</div>
<script type = "text/javascript">
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
var div = document.getElementById("dom-target");
var username = div.textContent;//these lines help to gett data from php
document.getElementById("usernamee").innerHTML = username;//for checking
$.ajax({
type: "POST",
url: "addenrolled.php",
data: {
// Send the username (js, not php)
username: username,
subject: subjectone,
course: courseone,
grade: gradeone
}, success: function(data) {
alert("sucess");
}
});
});
</script>
</body>
</html>
enrolled.php
<?php
include_once "connection.php";
$nick = $_POST['username'];
$subject=$_POST['subject'];
$course=$_POST['course'];
$grade=$_POST['grade'];
echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $con->prepare("INSERT INTO enrolledtable ('nickname', 'subject', 'course', 'grade') VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
header('Location: index.php');
exit();
}
?>
Change your jQuery to this
<script>
$(document).ready(function(){
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
$.post('enrolled.php', {subjectone: subjectone, courseone: courseone, gradeone: gradeone, addmore: "yes"}, function(response){
console.log(response);
})
});
});
</script>
Then in your PHP modify the prepare statement to the following
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
enrolled.php
<?php
session_start();
include_once "connection.php";
if (isset($_POST['addmore'])) {
$nick = $_SESSION['username'];
$subject=$_POST['subjectone'];
$course=$_POST['courseone'];
$grade=$_POST['gradeone'];
// //echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
// header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
//header('Location: index.php');
exit();
}
}
?>
my PHP code was working fine until I decided to use jquery for my signup page to handle and check the fields, it's working there is no error, everything is submitted to the server correctly so there is no problem with the code PHP nor jquery, but the header("location: ../****.php") no longer send me to another page after I hit submit, instead it loads the new page on top of the old one without refreshing.
This is my jquery code for the signup page:
<script>
$(document).ready(function() {
$("#myForm").submit(function(event){
event.preventDefault();
var username = $("#signup-username").val();
var pwd = $("#signup-pwd").val();
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
});
});
</script>
and this is my PHP code in my include page:
<?php
if (isset($_POST['submit'])){
include_once 'dbh.inc.php';
$username= mysqli_real_escape_string($conn, $_POST['username']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$errorEmpty = $errorValid = false;
if(empty($username)|| empty($pwd)){
echo "Fill in all Fields!";
$errorEmpty = true;
}
else{
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $uid);
$uid = $username;
$stmt->execute();
$result = $stmt->get_result();
$usernamecheck = mysqli_num_rows($result); // check if the results
$rowNum = $result->num_rows;
if($rowNum > 0){
echo "Username is taken!";
$errorValid = true;
}
else{
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, pwd) VALUES (?, ?)");
$stmt->bind_param("ss",$uid, $password);
$uid = $username;
$password = $hashedPwd;
$stmt->execute();
$result = $stmt->get_result();
header("location: ../user-login.php");
}
}
}else{
header("location: ../user-signup.php");
exit();
}
?>
<script>
$("#signup-username, #signup-pwd").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorValid = "<?php echo $errorValid; ?>";
if (errorEmpty == true $$ errorValid == true){
$("#signup-username, #signup-pwd").addClass("input-error");
if (errorFEmpty == false && errorValid == false){
$("#signup-username, #signup-pwd,").val("");
}
</script>
how do I fix this?
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
When the above code gets to the point where header("Location: file.php");
It'll fetch that file into $(".form-message")
To Avoid this you can use ajax to post data and javascript inbuilt redirection
$.ajax({
type: "POST",
url: "includes/user-signup.inc.php",
data: "username="+ username +"&pwd="+ pwd,
success: function(data) {
window.location.href = "../****.php";
}
});
Hope this answer was helpful.
Your code operates exactly as it should.
$(document).ready(function() {
$("#myForm").submit(function(event){
// THIS LINE RIGHT HERE
event.preventDefault();
******************
$(".form-message").load("includes/user-signup.inc.php",{
******************
});
});
});
Event prevent default stops the redirect action. Additionally you then use jquery to load the contents of the file into the DOM element with the class:
.form-message
Remove event.preventDefault();
when I click login it loads home.php on index.php and looks very strange.. is it possible to make it redirect or erase everything on index.php then load home.php
function login(){
var name = $('input#answer').val();
var pass = $('input#password').val();
if( $(name) == '' || $(pass) == '' )
$('#output').html('Please enter both username and password.');
else
$.post( ('php/login.php'), $('#myForm :input').serializeArray(),
function(data){
$('#output').html(data);
});
$('#myForm').submit(function(){
return false;
});
};
<?php
session_start();
if(isset($_SESSION['users']) != ""){
header("Location: ../php/home.php");
}
require '../php/dbConnect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = ("SELECT * FROM `accounts` WHERE username = '$username'")or die(mysql_error());
$response = mysql_query($query);
$row = mysql_fetch_array($response);
if($row['password'] == md5($password))
{
$_SESSION['user'] = $row['username'];
header("Location: ../php/home.php");
}
else{
echo("Wrong Credentials");
}
?>
Perhaps try:
$_SESSION['user'] = $row['username'];
header("Location: ../php/home.php");
die();
You usually need to issue a die() command after the header() statement.
I wanted to do is connect some files in different folder inside elogFiles folder. My problem is i dont know how to connect the files inside of another folder files.
here is the family tree of my files:
http://s38.photobucket.com/user/eloginko/media/folder_zpsa156e2a5.png.html
My problem the links is not correct.
Both code are not related. And the user.php is asking for connection from inside the dbc folder database.php and myScript.js wants to find user.php where is located inside the view folder.
myScript.js: " url: 'js/../view/user.php',"
user.php: "include_once('view/../dbc/database.php');"
can anyone help me correct the correct directory links.
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
echo "1";
exit;
} else {
echo "Incorrect Email or Password";
}
}else{
echo "Please enter Email and Password";
}
?>
myScript.js
$(document).ready(function() {
$('div#show:empty').hide();
$('#login').click(function(){
var email = $('#lemail').val();
var password = $('#lpassword').val();
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'js/../view/user.php',
success: function(data)
{
if (Number(data) == 1)
{
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
}
else
{
$('div#show:empty').show();
$('#show').html(data);
}
}
});
return false;
});
});
As your hierarchy is presently, provided, if you are on your http://localhost/elogFiles/view/user.php, you just need to go level one up ../
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
$response['status'] = '';
$response['message'] = '';
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
$response['status'] = 'OK';
} else {
$response['status'] = 'ERROR';
$response['message'] = 'Username/Password not found';
}
}else {
$response['status'] = 'ERROR';
$response['message'] = 'Please input username/password';
}
echo json_encode($response);
exit;
?>
Since, user.php processes the AJAX request, point the AJAX url attribute to this file. Consider this example:
myScript.js
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'http://localhost/elogFiles/view/user.php',
dataType: 'JSON',
success: function(data) {
if (data.status == 'OK') {
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
} else {
$('div#show:empty').show();
$('#show').html(data.message);
}
}
});