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.
Related
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
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.
I have been trying to get a page working for a number of days now, and there doesn't seem to be much help from the "related" questions on this site.
I have made a signup.php page, which has a form for inputting user credentials to signup up for the site I am building, when the form is filled out and the user presses the 'submit' button, the form uses the action "signupsuccess.php" which has all of the php code for inserting the credentials into the database, and then redirects the user to the "Login.php" page.
My problem:
I have written code to say that if the user has not put in any data for one of the fields in the form, then they are brought back to the signup.php page by using this code:
<?php
if(!isset($_POST['fname'])&&($_POST['lname'])&&($_POST['email'])&&($_POST['pass'])){
header('Location:Signup.php');
exit;
}
else{
$host = "localhost";
$user = "******";
$password = "******";
$conn = mysql_connect($host, $user, $password);
$db = mysql_select_db('*****', $conn);
if(! get_magic_quotes_gpc() )
{
$fname = addslashes ($_POST['fname']);
$lname = addslashes ($_POST['lname']);
$email = addslashes($_POST['email']);
$pass = addslashes($_POST['pass']);
}
else
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass= $_POST['pass'];
}
$query = mysql_query("select * from users where pass='$pass' AND email='$email'", $conn);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$errors[] = 'That user already exists, try another email';
}else
{
$sql = "INSERT INTO users ".
"(fname,lname, pass, email) ".
"VALUES('$fname','$lname','$pass','$email')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
}
mysql_close($conn);
?>
But the header() just won't bring the user back when they haven't put anything in to the fields. Is there anything I am doing obviously wrong or can anyone help me sort out the redirection of the user if they haven't entered anything.
Your if statement is incorrect. If you're just trying to check to see if those variables are set you need to call isset() on all of them.
You can do this with individual calls to isset() or all in one call.
if(!isset($_POST['fname'],$_POST['lname'],$_POST['email'],$_POST['pass'])){
header('Location:Signup.php');
exit;
}
FYI, you are wide open to SQL injections. addslashes() does not prevent SQL injections. Also, the mysql_* funcstions are obsolete and you should not be writing new code using them. Look into mysqli or PDO instead.
I don't think you really need a redirection, you probably should overcome this issue from the frontend, maybe a js validation could do the trick and is way simpler.
1.- change the action of submit to run the function "validate()"
2.- create the function that will be something like:
$(document).ready(function(){
function validate(){
if ($.trim($("#inputid").val()) == ""){
$(this).css('border', '2px solid red');
} else if ($.trim($("#inputid2").val()) == "") {
$(this).css('border', '2px solid red');
} else if ($.trim($("#inputid3").val()) == "") {
$(this).css('border', '2px solid red');
} else {
submit();
}
}
});
Where '#input?' is the selector for the input you want to validate and null is the value that you want to avoid, in this case, no value, just empty input. Then if all the inputs are filled it will execute submit() function which you should create to do whatever he has to.
Note: This kind of selectors are for jquery so you must include it in your code as well, put this in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
Note 2: This is the frontend approach. I don't know if this is convenient but at least is an option and helps.
Good luck!
Your if statement was the problem. because the isset was only affecting
$_POST['fname'],
the if statment was being skipped so
header('Location:Signup.php')
was not being reached.
I like to put
echo 'test';
in my code while i am testing it and move it around the code. That way, if it is not echoing 'test', i know that the code isn't even being reached. That could have helped you in this case, showing you that the problem wasn't the header, it was the if statement. Also, consider using PDO for mysql connections. It is more secure against mysql injections.
Your condition (if corrected according to the previous answers) would still always result in the else case. Since you are checking for $_POST fields, those will always be present. isset()returns false if the variable is not set (but it is: it comes from your form) or is NULL (which it is not: it contains an empty value). So, isset() will return true fopr every field. What you need is, for each field: if (empty(trim($_POST['fname']))) || ... )empty() returns false when the variable is not set or empty (i.e NULL, an empty string, 0, 0.0, false, etc, see here: http://php.net/manual/en/function.empty.php)Plus, you need to do something about the deprecated mysql_functions and your vulnerability to attacks.
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).
I'm kinda new to the OOP(? If this IS OOP, I don't know) language, and I'm trying to make a simple login-proccess, with MySQLi. The problem are, that the code doesn't work. I can't login (and It's not showing me any errors) and I can't register an new account (same problem) - It's like the code are dead or something.
I'm not sure I've done it right, but this is my best, so far. 'cause I'm new to OOP(?).
Index.php:
<?php
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$userControl = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."'";
$userControlResult = $mysqli->query($userControl);
if($mysqli->num_rows($userControlResult) > 1) {
$userRow = $mysqli->fetch_assoc($userControlResult);
$dbid = $userRow['id'];
$dbuser = $userRow['username'];
$_SESSION['id'] = $dbid;
$_SESSION['username'] = $dbuser;
header("location: me.php");
die();
} else {
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
}
?>
I suppose that if I can solve the first error, I can solve the second too.
Thanks!
Many things I would recommend changing about your code:
Don't use mysql_real_escape_string() if you're using mysqli. You can't mix these APIs.
No need to escape a string returned by md5(), because it's guaranteed to contain only hexadecimal digits.
Don't use mysqli_real_escape_string() anyway -- use parameters instead.
Always check if prepare() or execute() return false; if they do, then report the errors and exit.
You can get a mysqli result from a prepared statement using mysqli_stmt_store_result().
Don't SELECT * if you don't need all the columns. In this case, you already have $username so all you really need to fetch is the id column.
No need to check the number of rows returned, just start a loop fetching the rows (if any). Since you exit inside the loop, your "else" error clause will be output only if the loop fetches zero rows.
Consider using a stronger password hashing function than MD5. Also, add a salt to the password before hashing. Read You're Probably Storing Passwords Incorrectly.
Example:
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$userControl = "SELECT id FROM users WHERE username=? AND password=?";
if (($userControlStmt = $mysqli->prepare($userControl)) === false) {
trigger_error($mysqli->error, E_USER_ERROR);
die();
}
$userControlStmt->bind_param("ss", $username, $password);
if ($userControlStmt->execute() === false) {
trigger_error($userControlStmt->error, E_USER_ERROR);
die();
}
$userControlResult = $userControlStmt->store_result();
while($userRow = $userControlResult->fetch_assoc()) {
$_SESSION['userid'] = $userRow["id"];
$_SESSION['username'] = $username;
header("location: me.php");
die();
}
// this line will be reached only if the while loops over zero rows
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
?>
A good command to enter at the top of the script (under the
ini_set('display_errors', 1);
This will display any errors on your script without needing to update the php.ini (in many cases). If you try this, and need more help, please post the error message here and I'll be able to help more.
Also, if you are using $_SESSION, you should have
session_start();
at the top of the script under the
Make sure your php is set to show errors in the php.ini file. You'll need to do some research on this on your own, but it's fairly easy to do. That way, you'll be able to see what the error is and go from there.