I have a PHP function in my site to help eliminate SQL Injection.
I don't know if I have done this right, and I've tried to Google my question however it seems to be only wordpress related. I have my function in a file named requirements.php and have used require("requirements.php"); in order to call the file.
However when it's called in the html there is the error
Call to undefined function protect()
Here is the PHP script where the file is called:
<?php
require("database.php");
require("requirements.php");
$email = protect($con, $_POST['email']);
$password = protect($con, $_POST['password']);
$confpassword = protect($con, $_POST['confpassword']);
(The file continutes...)
And here is the file "requirements.php"
<?php
session_start();
function protect ($con, $str){
$str = mysqli_real_escape_string($con, $str);
return $str;
}
?>
The error occurs on line 4 reading:
$email = protect($con, $_POST['email']);
(Where protect is called)
I had someone working on my project who did this, however they aren't around to ask about this therefore I figured after some trial and error I would ask here.
Related
PHP login system works on local but doesn't work on Hostgator PHP 7.1. My local is PHP 7.2
I've built out a fully working portal on my local machine. I can CRUD on my local machine. As soon as I put it on the server online, the login system doesn't work. I still can register new users as the user info populates in the DB, so its not a DB config issue. I am getting these errors:
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in .....
Fatal error: Uncaught Error: Call to undefined function mysqli_stmt_get_result() in ....
I have spent 5 hours trying to figure out why it won't work on the Hostgator server but will work on my local.
Here is my code:
if(isset($_POST['loginSubmit'])){
//include connection configs
require '../../db_configs.php';
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if(empty($email || $password )){
header("Location: ../../../portalSignIn.php?signin=fieldsempty");
exit();
}
else
{
//user email query
$sqlEmail = "SELECT * FROM users WHERE email='$email'";
$emailResult = mysqli_query($conn, $sqlEmail);
$stmt = mysqli_stmt_init($conn);
//SQL Error
if(!mysqli_stmt_prepare($stmt, $sqlEmail)){
header("Location: ../../../portalSignIn.php?signin=SQL_FAILED");
exit();
}
if(mysqli_num_rows($emailResult) == 0){
//email doesn't exist
header("Location: ../../../portalSignIn.php?signin=incorrectemail");
exit();
}
else
{
//bind data if email exists
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)){....
Its breaking at this point --> mysqli_stmt_bind_param($stmt, "s", $email);
I've looked into https://www.plus2net.com/php_tutorial/mysqli_mysqlnd.php and Hostagtor doesn't have these settings. And I have used mysqli_stmt_bind_param() successfully on the sign up page.
You have plenty of mistakes in your code. Let me explain a few of them to you.
Don't escape your variables using mysqli_real_escape_string(). Just don't use this function at all.
empty($email || $password ) is going to check a boolean value. This does not make much sense. Remove the empty call and check the negation. If neither $email nor $password then one of them is empty.
Don't use mysqli_query. You are going to prepare a statement, so do not call this function. Also you need to parameterized the SQL. Use ? as placeholder for the value.
mysqli_num_rows in this place would throw an error. You don't need this function at all. If you wanted to use it you would need to pass the as a parameter the output of get_result()
To fetch values using prepared statement you need to prepare/bind/execute/get_result. Only then you can fetch a row if it exists. If nothing is returned then $record will be null.
if (isset($_POST['loginSubmit'])) {
//include connection configs
require '../../db_configs.php';
$email = $_POST['email'];
$password = $_POST['password'];
if (!$email || !$password) {
header("Location: ../../../portalSignIn.php?signin=fieldsempty");
exit();
} else {
//user email query
$sqlEmail = "SELECT * FROM users WHERE email=?";
$stmt = $con->prepare($sqlEmail);
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_assoc();
if (!$record) {
//email doesn't exist
header("Location: ../../../portalSignIn.php?signin=incorrectemail");
exit();
} else {
// handle your data here
}
}
}
And as always don't forget to enable mysqli error reporting. See How to get the error message in MySQLi?
The issue I am having is because Hostgator does not have mysqlnd available for shared hosting users but only those with VPS or dedicated servers:
https://www.hostgator.com/help/article/compatible-technologies
It can be enabled for other users and instructions can be done following this tutorial:
https://www.plus2net.com/php_tutorial/mysqli_mysqlnd.php
This was a learning lesson, especially in getting to know your webhost.
I am having an issue echoing or printing from my PHP to my HTML. I am sure I am missing something basic with how PHP works, however I have been unable to find anything about this issue on the internet or on here. I am very confused, because I am not receiving an errors or any context to the problem at all. The rest of my code works fine, except for echo.
I normally use echo() for testing to ensure stuff exists, however this issue has plagued me during the entire development of this application. It only now bothers me because I will need to echo out a script to load in data (Which I will hide after the load using Vue).
This issue oddly enough only has happened inside of areas where I am using if to do things, especially when it has array_key_exists.
If anyone could help I would appreciate it (Or if someone could provide a better idea for me to transfer json data from PHP to JavaScript other than having to echo it out, since that opens a weak spot in my code for users to cheat my clicker game).
I have tried to test this in other parts of my code with the same results. I cannot use echo() or print() within any if statement. I can use it elsewhere however.
All of my PHP files end up inside of my index.php by usage of require
<?php
if (array_key_exists("saveData", $_POST)) {
$saveData = $_POST['saveData'];
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
}
if (array_key_exists("logSubmit", $_POST)) {
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
echo("SALO Ready!");
}
?>
I would expect for this to echo out "SALO Ready" however I get nothing instead.
EDIT: PHP's white screen of death does not work or apply. Everything else in my application works as expected
UPDATE #1: I have done some testing as recommended, and found that when I echo out of my if statements, one of two things happen
1) The echo() fires, and in the preview under Network on Chrome you can see it their however it does not display in the DOM. This is the case for any if statement that does not meet the below situation.
2) If the echo() is fired from a block used for registering or logging in, it will not display in the preview either. I will be restructuring my code to have those be functions called by the forms when submitted, instead of them just being conditional blocks. While this code is not included in this question, the initial login runs the code below as well to load up user data.
UPDATE #2: I have consolidated my code and followed some recommendations. My code is now inside of functions, that are fired by some if isset conditions. This actually PARTLY fixed my issue. I can echo from all of my functions (Register, Login, Save, Load). Now my issue would appear to be a comment below in relations to output buffering. While my initial question is (Mostly) solved, would anyone be able to help explain how to solve this? I only have ob_start() right now, followed by my functions, if isset conditions, and then everything else in my application. How can I get the echo go to them DOM? I will include the chunk of my code below that will absolutely need to echo out down the road.
EDIT: I have changed how I have ob_start() setup within my code. I call it in the functions that need it and then flush it afterwards. I will be testing with my load script later tonight to try to force the echo() out of the function. Genuinely confused as to why it had not worked in functions but works outside of them, even before this edit
function load() {
$link = // Link Excluded for Security ;
if (mysqli_connect_error()) {
die ("DB Connection Error");
}
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
mysqli_close($link);
echo("Loading Triggered!");
}
if(isset($_POST['logSubmit'])) {
login();
load();
}
As mentioned, this shows the echo() inside of the network tab when I click on primary.php and click preview, it just isn't going to the DOM
Just use keep your code inside a function and call the function name while post your input
Ex:
function yourFunctionName(){
if (array_key_exists("saveData", $_POST)) {
$saveData = $_POST['saveData'];
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
}
if (array_key_exists("logSubmit", $_POST)) {
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
echo("SALO Ready!");
}
}
There is a way to output contents to the DOM when using ob_start by using ob_flush();
ob_start(), when called stores all outputs buffer until instructed to be sent to the browser.
See:
What is Output Buffering?
(The suggested solution provides a re usable function to empty the buffer, sending contents to browser)
How to flush output after echo call
When I run the following PHP code in my browser, I get an empty page in return. Why is this so?
<?php
require_once "conf.php";
function nuser()
{
$fname = $_POST['name'];
$uname = $_POST['user'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$query = "INSERT INTO websign(name,uname,email,pass)VALUES('$fname','$user','$email','$pass')";
$data = mysql_query($query)or die(mysql_error());
if ($data)
{
echo "your registration is completed";
}
}
function signup()
{
.......
.......
}
?>
Your code doesn't do anything.
You have defined two functions, but you never call either of them.
You need to add nuser() to the end of the script.
This assumes that the script executes at all. You said "when i run it on browser", but PHP doesn't run in browsers, it runs on servers. See this question on the subject.
Your program might also fail because you are using an obsolete database API that has been removed from PHP. You should select a modern replacement. You are vulnerable to SQL injection attacks that a modern API would make it easier to defend yourself from.
I have a simple script to allow a user to register an account. A warning about $_POST indexes being undefined occurs on the following two lines of the script that receives the form submission:
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
I've tried a var_dump($_POST), and those indexes are clearly defined. Furthermore, the following line works, and enters the information you would expect:
$id = $this->flexi_auth->insert_user($email, $username, $password, false, false, true);
If $_POST['email'] and $_POST['username'] were really undefined, there's no way that line would work. The user created in the database is with the username and email entered on the submission form. That being the case, why is it throwing obviously false warnings?
Try something like this.
$email = '';
$username = '';
if(!empty($_POST['email']) && !empty($_POST['username'])
{
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
}
It is possible that they could be undefined, hence the notices.
CodeIgniter has a function to help handle this, it returns FALSE if the item does not exist:
$this->input->post('item');
So, instead of:
$_POST['email']
You can use:
$this->input->post('email')
and so on...
You'll probably also want to check that you have valid values (not empty, for example) before creating a new user.
I want to redirect to a confirmation page after the person has registered, once they have entered the details they need it is sent to the database using the PHP script below which all works. Although when I try to add a redirect using header, it does not run the PHP script. Any ideas to what I am doing wrong?
PHP
if (isset($_POST['firstname'], $_POST['surname'], $_POST['email'], $_POST['username'], $_POST['password'], $_POST['interest'])){
$firstname = ($_POST['firstname']);
$surname = ($_POST['surname']);
$username = ($_POST['username']);
$password1 = ($_POST['password']);
$email = ($_POST['email']);
$interest = ($_POST['interest']);
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
}
You should use MySQLi or PDO with prepared statements as mysql_ functions have been deprecated. You should at least look into using something like mysql_real_escape_string as you may be open to sql injection attacks.
Otherwise, like others have said use:
header("Location: new_page.php");
exit();
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
header('Location: page.php');
Include at the beginning of the script:
<?php
ob_start();
?>
You can add header('Location:yourpage.php');
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
header('Location:yourpage.php');
exit();
You can add the #ob_start(); on top of the page.
This is an educated guess on what your problem might be:
You say the page is redirecting, but the php is not parsed. So... if the page just displays your php, it means is outside php reading directory... check that pls (see if it starts with localhost/your ip/domain, etc).