Error Too Many Redirects - php

Trying to create my server.php script, so everythning was fine, till now. I wanted to prevent form resubmission and added header('location: index.php'); to my script. And then I faced the problem:ERR_TOO_MANY_REDIRECTS. And as many of you already understand my database was full of a junk. So, here is my code:
<?php
$username = $email = $password = "";
$usernameErr = $emailErr = $passwordErr = "";
$servername = 'localhost';
$serveruser = 'root';
$serverpassword = 'root';
$db = 'example';
$conn = new mysqli($servername, $serveruser, $serverpassword, $db);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['register'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
if(empty($username)) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-z ]*$/", $username)){
$usernameErr = "Only letters and whitespaces allowed";
}
}
if(empty($email)) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Wrong email format";
}
}
if(empty($password)) {
$passwordErr = "Password required";
} else {
$password = test_input($_POST["password"]);
}
}
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
function test_input($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = stripslashes($data);
return $data;
}
?>

To prevent TOO MANY REDIRECT put this code
if ($usernameErr == "" && $emailErr == "" && $passwordErr == "") {
$sql = "INSERT INTO users (username, email, password)
VALUES('$username','$email','$password')";
if($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("location: index.php");
}
within
if(isset($_POST['register'])) { //.................}
this block after checking errors
And to prevent re-submission of form use accepted answer on this question
Preventing form resubmission

You can do couple of ways to stop this:
1) You can write either of these, unset($_POST['register']); or $_POST = array(); just before header('location:index.php');so it will not pass through if(isset($_POST['register'])) condition and so it will not go in infinite loop.
2) Or use full URL in header like this: header("location: mydomain.com/index.php"); It will stop infinite loop too.

Related

How to stop mysqli_query from adding records with missing info?

I have form that subscribers enter their email address and this gets posted to mysql database. The problem is that if you visit the page, even without subscribing, a record is added to the database even without the required email address. Even worse, it seems to be adding records every three seconds. How can i stop this? Is there something wrong in my code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
header('location: index.php');
mysqli_close($conn);
Just check with the if statement if there is an email you can save and put saving to database into that if statement as below:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
$emailErr = ''; //it is a good practice to initialize variable before its use.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
//if you have an email in $email and there is no
//error in $emailErr
if(!empty($email) && empty($emailErr)) {
//insert it to the db.
//THIS IS INSECURE WAY - Check links in comments!
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
header('location: index.php');
exit();

How to debug a mistake when inserting data into the table?

PHP code didn't insert.
<?php
$message = " ";
require "database.php";
if (isset($_POST["submit"])) {
if (empty($_POST["email"]) || empty($_POST["password"])) {
$message = "Email or Password is Incorrect";
} else {
$email = '$_POST[email]';
$pass = '$_POST[password]';
if ($email && $pass) {
$db = mysqli_select_db($conn, "auth");
$sqli = "INSERT INTO users (email, password) VALUES($email, $pass)";
if (mysqli_query($conn, $sqli)) {
$message = "New record created successfully";
} else {
$message = "Cannot create user!";
}
}
}
}
?>
$conn = mysqli_conncect("localhost","root","","auth");
I tried everything but not found the mistake to insert the query into the table.
Remove the single quotation in your else statement. PHP will interpret it as a string instead of a POST variable.
That is:
$email = $_POST['email'];
$pass = $_POST['password'];

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 getting error message when i try to register with php page in android

PFB code. DB connection is success but when try to register with register.php script in my android phone getting error page or getting please fill all values. I am not getting success. Kindly help. I am also using the URL register url in my java code as well http://xxxx/Userregistration/register.php.
register.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if ($name == '' || $username == '' || $password == '' || $email == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "SELECT * FROM KumbhaApp WHERE username='$username' OR email='$email'";
$check = mysqli_fetch_array(mysqli_query($con, $sql));
if (isset($check)) {
echo 'username or email already exist';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO KumbhaApp (name,username,password,email) VALUES('$name','$username','$password','$email')";
}
}
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
} else {
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (mysqli_query($con, $sql)) {
echo 'successfully registered';
header('Location: securedpage.php');
} else {
echo 'oops! Please try again!';
}
mysqli_close($con);
}
?>
It is not required, it is require. Your code
required ("http://localhost:8080/UserRegistration/dbConnect.php");
^
is wrong.

why won't this page redirect?

I'm having a problem with redirecting a page in php.
<?php
include '../include/dbfunctions.php';
$email = $password = "";
$err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['login']) && !empty($_POST['password'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$link = get_db_connection();
if (mysqli_connect_errno()) {
die(" Something went wrong ! ");
}
$user_email = mysqli_real_escape_string($link, $email);
$user_password = mysqli_real_escape_string($link, $password);
$query = "SELECT username FROM user WHERE user_email = '$user_email' AND user_password = SHA1('$user_password') AND user_active = '1';";
$data = mysqli_query($link, $query);
if (mysqli_num_rows($data) == 1) {
$row = mysqli_fetch_array($data);
$username = $row['username'];
mysqli_close($link);
if (!empty($username)) {
header('location:http://www.xxxxxxxxxxxxxx.be/login/dashboard.php');
exit();
}
} else {
$err = "Invalid combination of e-mail and password";
echo $err;
}
} else {
}
}
?>
I can't figure it out. If i fill in an invalid password or email, i get the error message. But when they are correct, nothing happens.
if (!empty($username)) {
header('location:http://www.yoursite.be/login/dashboard.php?error=error in login please try agine');
exit();
}
if (!empty($username)) {
header('location:http://www.xxxxxxxxxxxxxx.be/login/dashboard.php');
exit();}
$username might be empty.

Categories