Reputation: 129
Just wondering if someone could assist me on my latest issue. I'm very new at programming and really appreciate the help I get on here (so bear with me, we all have to start from somewhere!) :)
Basically I have this application and I've created a login for it and it verifies the information just fine and brings it onto the next page when you've successfully logged in perfectly.
What I'm having trouble understanding is starting up a PHP session with it? What I want to achieve at the end of this is to:
My html code is :
<!DOCTYPE html>
<html>
<head>
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="http://localhost/findadeal/themes/deal.css" />
<style>
#login-button {
margin-top: 30px;
}
</style>
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="js/custom3.js"></script>
</head>
<body>
<div data-role="page" id="login">
<div data-theme="a" data-role="header">
<h3>Find A Deal</h3>
</div>
<div data-role="content">
<?php
if( !isset( $_SESSION ) ){
session_start();
}
if( isset( $_SESSION['username'] ) ){
/* User is logged in */
}
?>
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
<a data-role="button" id="login-button" data-theme="b">Login</a>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<!--Newly rendered page after successful login!-->
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h2>Find A Deal</h2>
</div>
<div data-role="content">
<h3></h3>
<a href="#view" data-role="button" data-icon="search">View Deals</a>
<a href="http://localhost/findadeal/login/newdeal.php" data-role="button" data-icon="plus">Add Deals</a>
</div>
</body>
</html>
This is the Javascript function creating the Ajax request Etc:
$(document).on('pagebeforeshow', '#login', function(){
$('#login-button').on('click', function(){
if($('#username').val().length > 0 && $('#password').val().length > 0){
userObject.username = $('#username').val(); // Put username into the object
userObject.password = $('#password').val(); // Put password into the object
// Convert an userObject to a JSON string representation
var outputJSON = JSON.stringify(userObject);
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
ajax.sendRequest({action : 'login', outputJSON : outputJSON});
} else {
alert('Please fill all nececery fields');
}
});
});
$(document).on('pagebeforeshow', '#index', function(){
if(userObject.username.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
$.mobile.changePage( "#login", { transition: "slide"} ); // In case result is true change page to Index
}
$(this).find('[data-role="content"] h3').append('Welcome ' + userObject.username); // Change header with wellcome msg
//$("#index").trigger('pagecreate');
});
// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/findadeal/login/json2.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Login unsuccessful, please try again!'); // In case result is false throw an error
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
}
}
// object to store username and password.
var userObject = {
username : "",
password : ""
}
And finally this is my PHP file:
<?php
session_start();
$var1 = $_REQUEST['action'];
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$username = $jsonObject->{'username'}; // Get username from object
$password = $jsonObject->{'password'}; // Get password from object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
@mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "SELECT * FROM restaurant WHERE username = '".$username."' and password = '".$password."'";
$result=mysql_query($query);
$num = mysql_numrows($result);
if ($num != 0) {
$_SESSION['username'] = $username;
}
else {
echo "false";
}
?>
If someone could help me out it'd be fantastic! I think I've the session started on the HTML side, and the javascript has the right elements to it, it's figuring it out on the PHP side is where I tend to lose myself a little. I'm trying to get the users id to be passed across the various forms of the application but is there a way this can be done without them ever having to insert it?
Upvotes: 0
Views: 7412
Reputation: 1620
You have two things you hope to accomplish
By storing your data in the $_SESSION array you will have access to that data in every PHP script the user accesses.
In order to have access to the session array you must call session_start();
before accessing the $_SESSION
array. Remember to only call session_start only once per PHP execution. If session_start is called multiple times is will generate a warning or an error (I don't remember which)
You can check if the $_SESSION
array is set to know if the session has been started
if( !isset( $_SESSION ) ){
session_start();
}
if( isset( $_SESSION['username'] ) ){
/* User is logged in */
}
You might want to also take a look at this related question PHP User Authentication with Sessions
ANSWER: @user2025934
1) A session_start(); must be called only once and at first to begin the array and I add the mini php if statements above at the end of your example to the top of all of my php/html files that I want to carry the values across yes? With that in mind have I achieved what I need with the code I have above? (I've edited it with your changes)
Yes, adding this code snippet will give you access to the $_SESSION
array on any page you place it in.
if( !isset( $_SESSION ) ){
session_start();
}
2) Also, is there a way I can test this to ensure its working? To ensure it's working I > assume I add an echo function to the second if statement in which the users username will be outputted? –
Echo`ng some output like below is one or many way to test if its working
if( isset( $_SESSION['username'] ) ){
/* User is logged in */
echo "It Works! - The user is logged in!";
}
Upvotes: 3
Reputation: 5768
Put session_start();
at the top of your PHP file. Then when they successfully log in, you can do this:
if ($num != 0) {
$_SESSION['username'] = $username;
}
This will save the username to the session so you can then access the username of the user across your PHP pages for the duration of their session.
Upvotes: 1