PHP loop back through an if statement after SQL update - php

I'm trying to figure out a way to loop back through an if statement if the user fills in the the missing fields that updates the database? I was thinking of setting the header location back on it's self but I don't think that will work. Any suggestions please?
<?php
if(!isset($_SESSION)) { session_start(); }
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: ../login.php");
exit;
}
require_once "../config.php";
$key = $_SESSION["key"];
if (empty($key)) {
$example = $website = "";
$example_err = $website_err = "";
$conn = $link;
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["example"]))){
$example_err = "Please enter a valid key.";
} else{
$example = trim($_POST["example"]);
}
if(empty(trim($_POST["website"]))){
$website_err = "Please enter website URL.";
} else{
$website = trim($_POST["website"]);
}
if(empty($website_err) && empty($example_err)){
$stmt = $conn->prepare("UPDATE users SET website=?, example=? WHERE id=?");
$stmt->bind_param("sss", $param_website, $param_example, $param_id);
$param_website = $website;
$param_example = $example;
$param_id = $_SESSION["id"];
$stmt->execute();
$stmt->close();
$conn->close();
if($stmt){
*DO SOMETHING HERE*
} else{
echo "Something went wrong. Please try again later.";
}
}
}
} else{
echo "Success!";
}?>

If the form is on the same page, please set the form action as
<form action="" method="post">
and if not in the same page, please replace the following:
*DO SOMETHING HERE*
with
header("Location:".$_SERVER['HTTP_REFERER']);

Related

PHP select data using pdo get into array and use the data

I have a login, where i need to pull data given the email, i do this with a select and pdo. But it isn't working.
I get the password and email given from a form. Then i check if there not empty, then i want to get the password from the database to check it with the given password. If this is good, then i give the account id and username in a session.
If it was not good, i set the header and give a error message
try {
$connect = new PDO("mysql:host=$hostnaam; dbname=$databasenaam", $gebruikersnaam, $wachtwoord);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connectie mislukt: " . $e->getMessage();
}
<?php
ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ob_start();
if(isset($_REQUEST['password']))
{
require 'connect.php';
$password = $_REQUEST['password'];
$mail = $_REQUEST['email'];
if(empty($mail) || empty($password)){
header('location: ../login.php?error=empty');
exit();
}
else{
$sql = "SELECT * FROM account WHERE email = $mail";
$result = $connect->prepare($sql);
$result->execute();
$row = $result->fetchAll(PDO::FETCH_ASSOC);
$passwordCheck = password_verify($password_hashed, $pdo['wachtwoord']);
if($passwordCheck == false ){
header("Location: ../login.php?error=passwordWrong");
exit();
}
else if($passwordCheck == true){
session_start();
$_SESSION['userId'] = $row['account_id'];
$_SESSION['username'] = $row['gebruikersnaam'];
header("Location: ../index.php?login=succes");
exit();
}
else{
header("Location: login.php?error=noUser");
exit();
}
}
}
else{
header("Location: ../login.php?error=fail");
exit();
}

Page is redirecting to my php script from form

I am trying to make a login system with php but i cant figure out why my form is just redirecting me to the script file when i click on my login button. it works fine on my sign up form. everything seems to work exept its redirecting me to the script file. My php file that contains my form: https://codepen.io/hubbe-andersson/pen/yGOPoM
EDIT: I have put my phpscript into my header.php instead and now im getting ERR_TOO_MANY_REDIRECTS in chrome what is caussing this?
<?php
if(isset($_POST['login-sub'])) {
require 'databash.php';
$username = $_POST['mailname'];
$password = $_POST{'pwd'};
if(empty($username) || empty($password)) {
header("Location: index.php?error=tommarutor");
exit();
} else {
$sql = "SELECT * FROM USERS WHERE uidUsers=? OR emailUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: index.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_parem($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
$resultat = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultat)) {
$checkpwd = password_verify($password, $row['pwdUsers']);
if($checkpwd == false) {
header("Location: index.php?error=fellosenord");
exit();
}
else if ($checkpwd == true) {
seassion_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: index.php?login=lyckades");
exit();
}
else {
header("Location: index.php?error=fellosenord");
exit();
}
}
else {
header("Location: index.php?error=ingenanvandare");
exit();
}
}
}
} else {
header("Location: index.php");
exit();
}
line 6 error: use [...] instead of {...}
Look at the middle code block. Everything inside that focuses on determining which error the results will return, so establish that in your $_SESSION data and then redirect header("Location.... once. Most mistakes are little ones like the line 6 error, make a habit of adding // comments to your code so that it's easier to sort out the lines and sections of your code.
<?php
if(isset($_POST['login-sub'])) {
require 'databash.php';
$username = $_POST['mailname'];
$password = $_POST['pwd'];
if(empty($username) || empty($password)) {
header("Location: index.php?error=tommarutor");
exit();
} else {
$sql = "SELECT * FROM USERS WHERE uidUsers=? OR emailUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: index.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_parem($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
$resultat = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultat)) {
$checkpwd = password_verify($password, $row['pwdUsers']);
if($checkpwd == false) {
session_start();
$_SESSION['error']="fellosenord";
} else if ($checkpwd == true) {
seassion_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
$_SESSION['login']="lyckades");
} else {
session_start();
$_SESSION['error']="fellosenord";
} //end checkpwd
} else { // if fetch fails, send error
session_start();
$_SESSION['error']="ingenanvandare";
} // end fetch
header("Location: index.php");
} // end if stmt exists
} // end not empty input
} else { // if isset isn't set...
header("Location: index.php");
exit();
} // end isset
php database mysqli
Your index.php page need to start off by looking for the query string passed via $_SESSIONS to prevent people from trying to access the page without the related form.
session_start();
if ( empty($_SESSION['id']) ) { // no session info...
...
} else {
...
}
Ask your teacher to explain finding errors and solving problems so you can learn what to look for.

PHP file doesn't execute code after connecting to a database

After I run my PHP code, hello1 is printed on the screen, but not hello2. I assume there's something wrong with my code for connect.
I can't find what's wrong with my code. Unfortunately to me my code seems correct even after going over it multiple times. How can I fix it?
BTW, I am running MAMP on a MacBook Air.
<?php
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
if (!$connect) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
echo "hello3";
}
session_start();
if (isset($_POST["Sign Up"]))
{
if (empty($_POST["Email"]) || empty($_POST["Password"]))
{
echo '<script> alert ("Both Feldsa are required)</script">';
}
else
{
$_SESSION['email'] = $_POST['Email'];
$_SESSION['password'] = $_POST['Password'];
$_SESSION['Repeatpassword'] = $_POST['Repeatpassword'];
$_SESSION['name'] = $_POST['name'];
$_SESSION['weight'] = $_POST['weight'];
$_SESSION['feet'] = $_POST['feet'];
$_SESSION['inches'] = $_POST['inches'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['goal'] = $_POST['Goal'];
// Escape all $_POST variables to protect against SQL injection
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$RepPassword = $mysqli->escape_string(password_hash($_POST['Repeatpassword'], PASSWORD_BCRYPT));
$name = $mysqli->escape_string($_POST['name']);
$Weight = $mysqli->escape_string($_POST['weight']);
$feet = $mysqli->escape_string($_POST['feet']);
$inches = $mysqli->escape_string($_POST['inches']);
$age = $mysqli->escape_string($_POST['age']);
$goal = $mysqli->escape_string($_POST['goal']);
$hash = $mysqli->escape_string(md5(rand(0, 1000)));
// Check if user with that email already exists
// We know user email exists if the rows returned are more than 0
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'") or die($mysqli->error);
if ($result->num_rows > 0) {
$_SESSION['message'] = 'User with this email already exists!';
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO User (Email_Address, Password, Full Name, Weight, Feet, Inches, Age, Goal, hash) "
. "VALUES ('$email', 'password', 'name', 'Weight', 'feet', 'inches', 'age', 'goal', 'hash')";
}
if (! $mysqli->query($sql)
{
$_SESSION['message'] = 'Registration successfully';
echo $_SESSION['message'];
header("location: loginaccount.html");
}
}
else {
$_SESSION['message'] = 'Registration failed!';
echo $_SESSION['message'];
}
}
if (isset($_POST["Login"]))
{
$email = $mysqli->escape_string($_POST['Email']);
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'");
if ($result->num_rows == 0) { //
{
$_SESSION['message'] = "User with that email doesn't exist!";
echo $_SESSION['message'];
}
else {
$user = $result->fetch_assoc();
if (password_verify($_POST['password'], $user['Password'])) {
$_SESSION['email'] = $user['Email_Address'];
$_SESSION['name'] = $user['Full Name'];
$_SESSION['weight'] = $user['Weight '];
$_SESSION['feet'] = $user['Feet '];
$_SESSION['inches'] = $user['Inches '];
$_SESSION['age'] = $user['Age '];
$_SESSION['goal'] = $user['Goal '];
$_SESSION['logged_in'] = true;
$_SESSION['active'] = $user['Active'];
header("location: loginaccount.html");
}
}
mysqli_close($connect);
session_destroy();
?>
At the start of your script:
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
At line 3 here, you try and use $mysqli. That variable doesn't exist. You haven't declared it, so at that point, you are going to get a PHP runtime error when you try and reference the method of an object, which is in fact a non-existent variable.
It's actually worse than that, because you are mixing procedural mysqli with object oriented mysqli. What you really need is this, but the obvious issue is that your mysqli connection variable is named $connect!
echo "hello1";
$connect = new mysqli("localhost:8888", "Capstone", "", "capstone");
$connect->set_charset('utf8');
You can also use try/catch to find more about errors
try{
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
P.S. - in $mysqli->set_charset("utf-8"); $mysqli is not defined, use $connect here

Empty fields can get inserted into my database

I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.

php login script, give an error message if the name or password is incorrect

How do I change this script, which he displays an error message if the name or password is incorrect?
I'm new here in, Can someone explain it to me
<?php
$username=$_POST['username'];
$password=md5($_POST['password']);
$login=$_POST['login'];
if(isset($login)){
$mysqli = new mysqli("localhost", "root", "Tech112!", "ripper");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
$stmt = $mysqli->prepare("SELECT * FROM login where LOWER(`username`) = ? and password = ?");
$stmt->bind_param('ss', strtolower($username), $password);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$name = $row['name_login'];
$user = $row['username'];
$pass = $row['password'];
$rank = $row['type_login'];
if($user==$username && $pass=$password){
session_start();
if($rank=="2"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
} else if($rank=="1"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
}
}
}
?>
Tom Lammers
You need to add an else statement, like so
if($user==$username && $pass=$password){
session_start();
if($rank=="2"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
} else if($rank=="1"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
}
else {
echo "Invalid login";
}
This will output an error message only, you'll need to format that code to something more useful.
I would also count the rows, to ensure you're actually getting something back from the MySQL, like so.
if($result->num_rows == 1) {
if($user==$username && $pass=$password){
session_start();
if($rank=="2"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
} else if($rank=="1"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
}
else {
echo "Invalid login - Username and passwords do not match";
}
}
else {
echo "Invalid Login - Single entry not returned";
}
I would also do a major security review on your code, you should never be storing passwords in plain text format.

Categories