So I haven't really worked with PHP Sessions much and trying to learn. Despite trying to look online I'm a bit stuck. So I have a login page which works and lets people login but when they get to the welcome page I can't display anything other than the id, username or password (if I really wished)
So here's the code for the login page~:
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, firstname, lastname, email, phone, username, password FROM tourn_admins WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["firstname"] = $firstname;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Control Panel | Tournament | SymplieCloud</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
</head>
<body>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100">
<form class="login100-form validate-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<span class="login100-form-title p-b-26">
</span>
<span class="login100-form-title p-b-48">
<img src="" width="40%" height="auto" class="login-logo">
</span>
<div class="wrap-input100 validate-input <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>" data-validate = "">
<input class="input100" type="text" name="username" value="<?php echo $username; ?>">
<span class="focus-input100" data-placeholder="Username"></span>
</div>
<div class="wrap-input100 validate-input <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>" data-validate="Enter password">
<span class="btn-show-pass">
<i class="zmdi zmdi-eye"></i>
</span>
<input class="input100" type="password" name="password">
<span class="focus-input100" data-placeholder="Password"></span>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn">
Login
</button>
</div>
</div>
<div style="padding: 20px;">
<span><?php echo $username_err; echo $password_err; ?></span>
</div>
<div class="text-center p-t-115">
<span class="txt1">
Having difficulties?
</span>
<a class="txt2" href="#">
Contact Us
</a>
</div>
</form>
</div>
</div>
</div>
<div id="dropDownSelect1"></div>
<!--===============================================================================================-->
<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/animsition/js/animsition.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/bootstrap/js/popper.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/daterangepicker/moment.min.js"></script>
<script src="vendor/daterangepicker/daterangepicker.js"></script>
<!--===============================================================================================-->
<script src="vendor/countdowntime/countdowntime.js"></script>
<!--===============================================================================================-->
<script src="js/main.js"></script>
</body>
</html>
Then Heres the code for the welcome page:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <h1><?php echo $_SESSION["firstname"]; ?><b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
Reset Your Password
Sign Out of Your Account
</p>
</body>
</html>
So I'm trying to be able to display all the rows data. So I have ID, Firstname, Lastname, Email, Phone, Username, Password and Timestamp. I just want to be able to display them through the session like $_SESSION["firstname"]; As you may be able to see I have tried to have a go but is unsuccesfull. Again, am learning here so if you see anything which could be better, any critisim would be apprciated :) Thanks in advance!
You're not binding enough results to your prepared statement:
$sql = "SELECT id, firstname, lastname, email, phone, username, password FROM tourn_admins WHERE username = ?";
Your statement fetches 7 columns, but your mysqli_stmt_bind_result call only has 3 variables:
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
You need to add variables for all the columns you are reading in the query i.e.
mysqli_stmt_bind_result($stmt, $id, $firstname, $lastname, $email, $phone, $username, $hashed_password);
Related
I am trying to insert form data to my profile table when I click the add button, but whenever I test my code below it just reloads my add.php page and clears the form instead of adding it to my table.
add.php code:
<?php
//connection to the database
$pdo = require_once 'pdo.php';
session_start();
//if user is not logged in redirect back to index.php with an error message
if(!isset($_SESSION['user_id'])){
die("ACCESS DENIED");
return;
}
//if the user requested cancel go back to index.php
if(isset($_POST['cancel'])){
header('Location: index.php');
return;
}
//handling incoming data
$uid = $_SESSION['user_id'];
if (isset($_POST['first_name']) && isset($_POST['last_name']) &&
isset($_POST['email']) && isset($_POST['headline']) && isset($_POST['summary'])){
if (strlen($_POST['first_name']) == 0 || strlen($_POST['last_name']) == 0 ||
strlen($_POST['email']) || strlen($_POST['headline']) == 0 || strlen($_POST['summary']) == 0){
$_SESSION['error'] = "All fields are required";
header("Location: add.php");
return;
}
if(strpos($_POST['email'], '#') === false){
$_SESSION['error'] = "Email address must contain #";
header("Location: add.php");
return;
}
$stmt = $pdo->prepare('INSERT INTO profile
(user_id, first_name, last_name, email, headline, summary)
VALUES ( :uid, :fn, :ln, :em, :he, :su)');
$stmt->execute(array(
':uid' => $uid,
':fn' => $_POST['first_name'],
':ln' => $_POST['last_name'],
':em' => $_POST['email'],
':he' => $_POST['headline'],
':su' => $_POST['summary'])
);
$_SESSION['success'] = "profile added";
header("location: index.php");
return;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Profile Add</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Adding Profile for UMSI</h1>
<form method="post" action="index.php">
<p>First Name:
<input type="text" name="first_name" size="60"/></p>
<p>Last Name:
<input type="text" name="last_name" size="60"/></p>
<p>Email:
<input type="text" name="email" size="30"/></p>
<p>Headline:<br/>
<input type="text" name="headline" size="80"/></p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80"></textarea>
<p>
<input type="submit" name="add" value="Add">
<input type="submit" name="cancel" value="Cancel">
</p>
</form>
</div>
</body>
</html>
here I created my connection to the database using pdo connection and also require my config.php file for database sign in credentials
here is my pdo.php code:
<?php
require_once 'config.php';
//setting DSN
$dsn = "mysql:host=$host;dbname=$dbname;charset=UTF8";
//creating a PDO instance
try{
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if($pdo){
echo "database connected Successfully";
return;
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
my database sign in credentials are in this file, the username, password and dbname are not necessarily correct, I only changed them for the sake of asking.
here is my config.php code:
<?php
//my variables
$host = 'localhost';
$user = 'myusername';
$password = 'mypass';
$dbname = 'mydb';
?>
my index.php code has a static display for the profile entries, I wanted to be able to add the profiles first so I can make it dynamically display the profiles but here is my index.php code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Resume Registry</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Mandla'ke Makondo's Resume Registry</h1>
<p>
<?php
if(isset($_SESSION['user_id'])){
echo " <a href='logout.php'>Logout</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<a href='login.php'>Please log in</a>";
}
?>
</p>
<?php
if(isset($_SESSION['user_id'])){
echo"<table border = '1'>
<tr><th>Name</th><th>Headline</th><th>Action</th><tr><tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td><td><a href = 'edit.php'>Edit</a> <a href = 'delete.php'>Delete</a></td></tr>
</table>";
echo "<a href='add.php'>Add New Entry</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<table border='1'>
<tr><th>Name</th><th>Headline</th>
<tr>
<tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td></tr>
</table>";
}
?>
</div>
</body>
enter code here
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Resume Registry</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Mandla'ke Makondo's Resume Registry</h1>
<p>
<?php
if(isset($_SESSION['user_id'])){
echo " <a href='logout.php'>Logout</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<a href='login.php'>Please log in</a>";
}
?>
</p>
<?php
if(isset($_SESSION['user_id'])){
echo"<table border = '1'>
<tr><th>Name</th><th>Headline</th><th>Action</th><tr><tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td><td><a href = 'edit.php'>Edit</a> <a href = 'delete.php'>Delete</a></td></tr>
</table>";
echo "<a href='add.php'>Add New Entry</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<table border='1'>
<tr><th>Name</th><th>Headline</th>
<tr>
<tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td></tr>
</table>";
}
?>
</div>
</body>
I'm trying to convert my procedural login to OOP but I get ArgumentCountError. This is a project for my homework, can you help me?
Down below is my php code with class and login function and HTML Login page with small php script.
DB Connection is PDO.
When i going to istance my php function with "$login = new Login;
$login->login($email,$password,$type);" i get this error:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Login::login(), 0 passed in C:\xampp\htdocs\public_html\project OOP\include\login.php on line 50 and exactly 3 expected in C:\xampp\htdocs\public_html\project OOP\include\login.php:8 Stack trace: #0 C:\xampp\htdocs\public_html\project OOP\include\login.php(50): Login->login() #1 {main} thrown in C:\xampp\htdocs\public_html\project OOP\include\login.php on line 8.
I know that there are a lot of mistakes here, but I'm a beginner.
class Login{
private $email;
private $password;
private $type;
public function login($email,$password,$type){
if(!empty($_POST['email']) && !empty($_POST['password'])&& !empty($_POST['type'])):
switch ($_POST['type']) {
case 'Buyer':
$records = $conn->prepare('SELECT * FROM buyer WHERE email = :email');
break;
case 'Seller':
$records = $conn->prepare('SELECT * FROM seller WHERE email = :email');
break;
default:
break;
}
$_SESSION['type'] = $_POST['type'];
$records->bindParam('email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if($results && count($results) > 0 && md5($_POST['password'], $results['password'])){
$_SESSION['user_id'] = $results['buyer_id'];
$_SESSION['name'] = $results['buyer_name'];
$_SESSION['email'] = $results['email'];
$_SESSION['password'] = $results['password'];
$_SESSION['phone'] = $results['phone'];
$_SESSION['description'] = $results['description'];
$_SESSION['status'] = $results['status'];
header("Location: index.php");
} else {
$message = 'Sorry, those credentials do not match';
}
endif;
}
}
This is only for test
$email = "keno1#gmail.com";
$password = "123456";
$type = "Buyer";
$login = new Login;
$login->login($email,$password,$type);
My HTML code:
<?php
session_start();
if ( isset($_SESSION['user_id']) ){
header("Location: index.php");
}
require 'database.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login V1</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/login.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
<!--===============================================================================================-->
</head>
<body>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100">
<div class="login100-pic js-tilt" data-tilt>
<img src="images/img-01.png" alt="IMG">
</div>
<form class="login100-form validate-form" action="login.php" method="POST">
<span class="login100-form-title">
Member Login
</span>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="text" name="email" placeholder="Email">
<span class="focus-input100"></span>
<span class="symbol-input100">
<i class="fa fa-envelope" aria-hidden="true"></i>
</span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Password is required">
<input class="input100" type="password" name="password" placeholder="Password">
<span class="focus-input100"></span>
<span class="symbol-input100">
<i class="fa fa-lock" aria-hidden="true"></i>
</span>
</div>
<select class="browser-default custom-select" name="type">
<option disabled="disabled" selected="selected">Profile type</option>
<option>Buyer</option>
<option>Seller</option>
</select>
<div class="container-login100-form-btn">
<button class="login100-form-btn" type="submit" name="submit">
Login
</button>
</div>
<div class="text-center p-t-12">
<span class="txt1">
Forgot
</span>
<a class="txt2" href="#">
email / Password?
</a>
</div>
<div class="text-center p-t-136">
<a class="txt2" href="register.php">
Create your Account
<i class="fa fa-long-arrow-right m-l-5" aria-hidden="true"></i>
</a>
</div>
</form>
</div>
</div>
</div>
<!--===============================================================================================-->
<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/bootstrap/js/popper.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/tilt/tilt.jquery.min.js"></script>
<script >
$('.js-tilt').tilt({
scale: 1.1
})
</script>
<!--===============================================================================================-->
<script src="js/main.js"></script>
</body>
</html>
Your login function is being interpreted as a constructor because it has the same name as the class. (See PHP 4 Style Constructors.)
You must not be seeing the deprecation message because of your error reporting settings.
The deprecation isn't the problem, though. It ends up turning into a fatal error because
$login = new Login;
calls the login method with no arguments, since PHP treats it like a constructor.
You don't need a __construct() method though, because that function isn't actually supposed to be a constructor. You can just change the name of the class or the method, that should fix the error.
I want to store data (id, profile_image, caption) from another table
(I just download the code for uploading images)
The problem is when I am about to save the data, processForm.php always give me a zero value for Session ID which is my current ID is "1".
I'm a newbie here.
(login.php)
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to
welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="icon" href="logo2.png" type="image">
<head>
<title>Fox - Log In | Sign Up</title>
<meta charset="windows-1252">
</head>
<body>
<div class="header" id="myHeader" >
<img src="logo.png" alt="Fox Logo" width="5%" height="20%">
<div class="tooltip">
<img src="text.png" alt="Fox text" width="50%" height="15%" usemap="#foxlogo">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="login.php">
</map>
</div>
<div class="container">
<img class="img" src="bg2.jpg">
</div>
<div class="signup"><br><br><br><br><br>
<h1 style="text-align:center; font-size:12;">Log In</h1><br>
<form style="margin-left:25px; margin-top: -20px;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<p style="font-size: 14px; color: white;margin-left: 0px;width: 980px;">Username</p>
<input placeholder="Enter Username" type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<br><span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<p style="font-size: 14px; color: white;margin-left: 0px;width: 980px;">Password</p>
<input placeholder="Enter Password" type="password" name="password" class="form-control" >
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input style="margin-top:20px;" type="submit" class="button" value="Login">
</div>
<p2>Sign up now</p2>
</form>
</div>
<div>
<img class="user" src="user.png">
</div>
<a type="link2" style="margin:30px; text-decoration: none;" href="#">Terms & Policies</a>
<a type="link2" style="text-decoration: none;" href="#">Help</a>
</div>
</body>
</html>
(welcome.php)
<?php
require_once "config.php";
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" href="logo2.png" type="image">
<head>
<meta charset="UTF-8">
<title>Fox | Home</title>
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<br>
<a style="margin-left:90%;position: relative;" href="logout.php" name="signout" class="btn btn-danger">Sign Out</a>
<div style="margin-right:96%"class="tooltip">
<img style="margin-right: 96%;margin-top:0%;" src="logo.png" alt="Fox Logo" width="100%" usemap="#foxlogo">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="welcome.php">
</map>
<hr>
<div class="profile">
<div class="page-header">
<h1><b><?php echo htmlspecialchars($_SESSION["username"]); ?></b></h1>
<div class="container">
<img name="profile" class="image" src="images/placeholder.png" id="profileDisplay" style="display: block;width: 45%;margin: 10px auto;border-radius:50%;"><br>
<input type="file" name="profileImage" id="profileImage" style="display: none;">
<div class="overlay">
<div class="text"><br>
Update Profile<br><br><br>
View profile
</div>
</div>
<?php
$con = mysqli_connect("localhost","root","","demo");
$q = mysqli_query($con,"SELECT * FROM users WHERE id ='{$_SESSION["id"]}'");
while($row = mysqli_fetch_assoc($q)){
echo $row['created_at'];
}
?>
</div>
<p>
Reset Your Password<br><br><br>
</p>
</div>
</body>
</html>
(config.php)
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
(updateprofile.php)
I try to echo my current id(1) in this form and it is fine. but in saving id in XAMPP php my admin gives me ZERO. processForm gives me zero value for my SESSION ID
picture1:I try to echo my ID and its fine
Picture2:After I upload a picture. it gives me a zero value for ID
<?php
require_once "config.php";
include 'processForm.php';
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" href="logo2.png" type="image">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<head>
<meta charset="UTF-8">
<title>Fox | Home</title>
<style type="text/css">
body, html{ font: 14px sans-serif; text-align: center;height: 100%; width: 100%; }
</style>
</head>
<body>
<div style="margin-left:90%"class="tooltip">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="welcome.php">
</map>
</div>
<img style="margin-right: 90%; margin-top:2%;" src="logo.png" alt="Fox Logo" width="5%" usemap="#foxlogo">
<a style="margin-left:90%; margin-top:-5%; position: relative;" href="logout.php" name="signout" class="btn btn-danger">Sign Out</a>
<hr>
<div style="margin-left: 35%"class="container">
<div class="row">
<div class="col-4 offset-m-d4 form-div">
<form enctype="multipart/form-data" action="index.php" method="post" >
<h3 class="text-center">Upload Profile</h3>
<?php //echo htmlspecialchars($_SESSION["username"]);
echo " My id is {$_SESSION["id"]}"; ?>
<div class="form-group text-center">
<img src="images/placeholder.png" id="profileDisplay" onclick="triggerClick()" style="display: block;width: 60%;margin: 10px auto;border-radius:50%;">
<input type="file" name="profileImage" onchange="displayImage(this)" id="profileImage" style="display: none;">
</div>
<div clas="form-group">
<label for="caption">Caption</label>
<textarea name="caption" id="caption" class="form-control"></textarea>
</div>
<div class="form-group">
<br>
<button type="submit" name="save-user" class="btn btn-primary btn-block">Upload</button>
</div>
</form>
</div>
</div>
</div>
<br><br><br><br>
<script src="scripts.js"></script>
</body>
</body>
</html>
(processForm.php)
<?php
require_once "config.php";
//connect db
$conn = mysqli_connect('localhost','root','','demo');
if(isset($_POST['save-user'])){
$caption = $_POST['caption'];
$profileImageName =time() . '_' . $_FILES['profileImage']['name'];
$target = 'images/' . $profileImageName;
if(move_uploaded_file($_FILES['profileImage']['tmp_name'], $target)){
//* */
$sql = "INSERT INTO photos (id,profile_image,caption) VALUES ('{$_SESSION['id']}','$profileImageName','$caption')";
if (mysqli_query($conn, $sql)){
$msg="Image uploaded and saved to database";
$css_class = "alert-success";
}else{
$msg="Database error: Failed to save user";
$css_class = "alert-danger";
}
//
$msg="Image uploaded";
$css_class = "alert-success";
header("location: welcome.php");
}else{
$msg="Failed to upload";
$css_class = "alert-danger";
header("location: updateprofile.php");
}
}
you can add the output of the $_SESSION variable with a var_dump(); After the loggin and another one in the same moment of the saved of the photo in mysql , and compare??? I think that your (processForm.php) is missing at the beginning too ... session_start ();
I am trying to get a user to insert value of specific row in db table. However I keep getting an error: Call to a member function register()
Here is the php and html code that I am using to update the table
<?php
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_client_info WHERE UCODE=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(isset($_POST['submit']))
{
$purchasedata = $_POST['purchasedata'];
$cpurchasedata = $_POST['cpurchasedata'];
if($cpurchasedata!==$purchasedata)
{
$msg = "<div class='alert alert-block'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry!</strong> Input Does Not Match. Make sure the details match.
</div>";
}
else
{
$stmt = $user-> register("UPDATE tbl_client_info SET purchasedata=? WHERE UCODE=:uid");
$stmt->execute(array(":purchasedata"=>$purchasedata,":uid"=>$rows['UCODE']));
//
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
Okay, we have added data to your account.
</div>";
}
}
}
else
{
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
No Sorry That Did Not Work, Try again
</div>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Forgot Password</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="fonts/css/font-awesome.min.css" rel="stylesheet">
<link href="css/animate.min.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Custom styling plus plugins -->
<link href="css/custom.css" rel="stylesheet">
<link href="css/icheck/flat/green.css" rel="stylesheet">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<!-- Sweet Alert -->
<script src="dist/sweetalert-dev.js"></script>
<link rel="stylesheet" href="dist/sweetalert.css">
<!--.......................-->
</head>
<body style="background:#f3f3f3;">
<div id="wrapper">
<div id="login_content" class="animate form">
<section class="login_content">
<form method="post">
<h1>Purchase Data</h1>
<div class='alert alert-success'>
<strong>Hello </strong><?php echo $row['firstname'] ?>! //add more text here
</div>
<?php
if(isset($msg))
{
echo $msg;
}
?>
<input type="text" class="input-block-level" placeholder="500mb" name="purchasedata" required />
<input type="text" class="input-block-level" placeholder="Retype the bundle" name="cpurchasedata" required />
<hr />
<button class="btn btn-large btn-primary" type="submit" name="btn-update-data">Add data to my account</button>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">All Done ?
Go Home
my class.user.php looks like this:
<?php
require_once 'dbconfig.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function lasdID()
{
$stmt = $this->conn->lastInsertId();
return $stmt;
}
public function register($uname,$email,$upass,$code,$purchasedata)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_client_info(User_Name,billingemail,password,purchasedata,tokenCode)
VALUES(:User_Name, :billingemail, :password, :purchasedata, :active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->bindparam(":purchasedata",$purchasedata);
$stmt->execute();
return $stmt;
}
What is it that I am doing wrong? I have searched the error, but I can't see where I have gone wrong. Any help or links to help would be appreciated.
$user should be $user_home. You have used the wrong varible while calling register function.
I want to log the users IP when they login all I want it to do it update a column
I know $_SERVER['REMOTE_ADDR']; get their ip.
I want to log it on login on their username row in mysql.
Here's an image of my mysql table
https://gyazo.com/cf5b223df03d0da8a15bf61ed037d847
LoginCheck.php:
<?php
# Processes
function cleanString($con, $string) {
return mysqli_real_escape_string($con, stripcslashes($string));
}
# buttons use the request method
if (isset($_REQUEST['login'])) {
$username = strtolower(cleanString($con, $_POST['username']));
$password = cleanString($con, $_POST['password']);
$errors = array();
if (empty($username) || empty($password)) {
# If they left the shit blank like a jew
$errors[] = "Please make sure you entered a valid username and password";
}
$password = md5($password);
$db_check_username = mysqli_query($con, "SELECT username FROM users WHERE username='$username' OR email='$username'");
$db_check_userdata = mysqli_query($con, "SELECT username,password FROM users WHERE username='$username' AND password='$password' OR email='$username' AND password='$password'");
if (!$db_check_username || !$db_check_userdata) {
$errors[] = mysqli_error($con);
}
if (mysqli_num_rows($db_check_username) == 0) {
# If the username doesn't exist like a bitch
$errors[] = "No account could be found with that username.";
}
if (mysqli_num_rows($db_check_userdata) == 0) {
# If the Username and Password don't match
$errors[] = "Username and Password combination incorrect.";
}
if(empty($errors)) {
session_start();
$_SESSION['username'] = $username;
$success[] = "You have successfully logged in. Redirecting in a moment.";
echo '<meta http-equiv="refresh" content="5; url=index.php" />';
} else {
$danger = $errors;
}
}
?>
Login.php
<?php
# Include da files mate
include('includes/config.php');
include('includes/logincheck.php');
# Other Shit
//nothing yet
?>
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<title>Twisted Movies | Login Page</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- ================== BEGIN BASE CSS STYLE ================== -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
<link href="assets/plugins/jquery-ui/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
<link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="assets/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<link href="assets/css/animate.min.css" rel="stylesheet" />
<link href="assets/css/style.min.css" rel="stylesheet" />
<link href="assets/css/style-responsive.min.css" rel="stylesheet" />
<link href="assets/css/theme/red.css" rel="stylesheet" id="theme" />
<!-- ================== END BASE CSS STYLE ================== -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="assets/plugins/pace/pace.min.js"></script>
<!-- ================== END BASE JS ================== -->
</head>
<body class="pace-top">
<!-- begin #page-loader -->
<div id="page-loader" class="fade in"><span class="spinner"></span></div>
<!-- end #page-loader -->
<div class="login-cover">
<div class="login-cover-image"><img src="assets/img/login-bg/bg-1.jpg" data-id="login-cover-image" alt="" /></div>
<div class="login-cover-bg"></div>
</div>
<!-- begin #page-container -->
<div id="page-container" class="fade">
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated fadeIn">
<!-- begin brand -->
<div class="login-header">
<div class="brand">
<span class="logo"></span> Twisted Movies
<small>Where the best movies are AD free!</small>
</div>
<div class="icon">
<i class="fa fa-sign-in"></i>
</div>
</div>
<!-- end brand -->
<div class="login-content">
<form action="" method="POST" class="margin-bottom-0">
<div class="text-center">
<?php
if (!empty($success)) {
foreach ($success as $value) {
echo '<div class="alert alert-success">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($danger)) {
foreach ($danger as $value) {
echo '<div class="alert alert-danger">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($warning)) {
foreach ($warning as $value) {
echo '<div class="alert alert-warning">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($info)) {
foreach ($info as $value) {
echo '<div class="alert alert-info">';
echo $value.'<br>';
echo '</div>';
}
} else {
echo '<div class="alert alert-info">';
echo "Please enter a username and password.";
echo '</div>';
}
?>
</div>
<div class="form-group m-b-20">
<input type="text" name="username" placeholder="Username" class="form-control input-lg"/>
</div>
<div class="form-group m-b-20">
<input type="password" name="password" placeholder="Password" class="form-control input-lg"/>
</div>
<div class="checkbox m-b-20">
<label>
<input type="checkbox" /> Remember Me
</label>
</div>
<div class="login-buttons">
<button type="submit" name="login" class="btn btn-success btn-block btn-lg">Sign me in</button>
</div>
<div class="m-t-20">
Not a member yet? Click here to register.
</div>
<center><?php include 'includes/footer.php'; ?></center>
</form>
</div>
</div>
<!-- end login -->
</div>
<!-- end page container -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="assets/plugins/jquery/jquery-1.9.1.min.js"></script>
<script src="assets/plugins/jquery/jquery-migrate-1.1.0.min.js"></script>
<script src="assets/plugins/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<!--[if lt IE 9]>
<script src="assets/crossbrowserjs/html5shiv.js"></script>
<script src="assets/crossbrowserjs/respond.min.js"></script>
<script src="assets/crossbrowserjs/excanvas.min.js"></script>
<![endif]-->
<script src="assets/plugins/jquery-hashchange/jquery.hashchange.min.js"></script>
<script src="assets/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script src="assets/plugins/jquery-cookie/jquery.cookie.js"></script>
<!-- ================== END BASE JS ================== -->
<!-- ================== BEGIN PAGE LEVEL JS ================== -->
<script src="assets/js/login-v2.demo.min.js"></script>
<script src="assets/js/apps.min.js"></script>
<!-- ================== END PAGE LEVEL JS ================== -->
<script>
$(document).ready(function() {
App.init(ajax=true);
LoginV2.init();
});
</script>
</body>
</html>
Right after you have session_start():
$ip = $_SERVER['REMOTE_ADDR'];;
$stmt = $con->prepare("UPDATE users SET `IP`=? WHERE username=?");
$stmt->bind_param("ss", $ip, $username);
$stmt->execute();
Some tips:
Try to always use prepared statements when dealing with user data.
use a HTTP class to get the IP. The IP is not always in REMOTE_ADDR, especially if the site is behind a proxy such as Cloudflare