apache2 and php - please advise - php

OK, I originally posted this a question about php, but have since realized it could be a server configuration problem, which I know little about. I left the php script in case, and am hoping someone might have some pointers on this - I already checked permissions (755).
"NetworkError: 500 Internal Server Error - http://localhost/register.php?name=uname&password=upassword"
I was hoping someone here would be able to catch my error - sorry if this is obvious I've been learning as I go.
<?php
define('USER', 'root');
define('PASS', 'password');
$dbh = new PDO('mysql:host=localhost;dbname=users', USER, PASS);
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
$query = 'INSERT INTO `users` (`name`, `password`) VALUES (?,?)';
$query->bind_param($uname, $upassword);
$queryResults = $dbh->prepare($query);
$queryResults->execute();
$queryResults = null;
$dbh = null; // close the connection
?>
This keeps giving me a 500 internal server error indicating the php script, (in firebug for firefox), and I can't really figure out where I'm going wrong. I can also post ajax if needed.

You are using a Query String http://localhost/register.php?name=uname&password=upassword". Its purely a GET Method.
Your have to check whether the GET Method is exist then you need to access the GET Method Data.
$uname = "";
if(isset($_GET['uname'])) {
$uname = $_GET['uname'];
}
$upassword = "";
if(isset($_GET['password'])) {
$upassword = $_GET['password'];
}
if(($uname != "") && ($upassword != "")) {
$upassword = password_hash($upassword, PASSWORD_DEFAULT)
$query = sprintf("INSERT INTO `users` (`name`, `password`) VALUES (%s, %s)", $uname, $upassword);
----- Statements ------
}

I don't know why it's throwing 500 error, but you clearly have error in code.
Your $query variable is string and it does not have $query->bind_param() method. I assume you are trying to do this (bind_param is MySqli while bindParam is PDO):
$dbh->prepare($query);
$sth->bindParam($uname, $upassword);
Also since you are passing variables via URL, than you must use $_GET instead of $_POST. Just make sure you first check if these parameters exists in $_GET and only than use them:
if (!empty($_GET['name'])) {
$uname = $_GET['name'];
}
NOTE ?name=uname&password=upassword means variable names are name and password. It's values are $_GET['name'] = 'uname' / $_GET['password'] = 'upassword'.
Never pass username and password using $_GET as it's insecure. Better use some secure file to save them.

Related

PHP not showing any error, the latter 2 else if statements are working well, but not the first one

<?php
$db = mysqli_connect('localhost', 'username', 'password', 'database');
$username = "";
$password = "";
$regcode = "";
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$regcode = $_POST['regcode'];
$sql_R = "SELECT * FROM regcode WHERE regcode='$regcode'";
$sql_R2 = "SELECT * FROM staff WHERE regcode='$regcode'";
$res_R2 = mysqli_query($db, $sql_R2);
$res_R = mysqli_query($db, $sql_R);
if ((mysqli_num_rows($res_R) > 0) && (mysqli_num_rows($res_R2) < 1)){
$query = "INSERT INTO staff (username, password, regcode)
VALUES ('.$username.', '.$password.', '".$regcode."')";
$results = mysqli_query($db, $query);
echo file_get_contents("register.html");
exit();
}else if(mysqli_num_rows($res_R2) > 0){
$regcode_error = "Reg.Code already used by someone, please inform administrator for further information.";
}else{
$regcode_error = "Reg.Code doesn't exists, please inform Administrator for further information.";
}
}
?>
Here's what happened: I'm trying to let my system recognize a code called 'regcode' from the database so when it's verified users will able to register their account, user won't be able to register their account IF the regcode is in use in the staff database or when the regcode isn't exist in the regcode database the problem is:
- My database didn't add the new info after it's verified.
- I've tried the other way such as testing the regcode invalid or being in use, and it works well by displaying the error message.
I'm trying to figure this out like hours, and I still can't get it. I'm new to php btw, thanks for the advice.
This line is incorrect
VALUES ('.$username.', '.$password.', '".$regcode."')";
it should be
VALUES ('$username', '$password', '$regcode'";
You were concatenating, incorrectly and where you didnt need to, remember double quoted strings will automatically expand $variables
NOTE: Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
This would have been easier for you to debug yourself if you included some error checking code. Add
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
to the top of your script. This will force any mysqli_ errors to
generate an Exception that you can see on the browser and other errors will also be visible on your browser.

PHP insert blank values instead of GET values

I have this script on my site:
<?php
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_found) {
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
}
else {
print "Database NOT found";
mysql_close($db_handle);
}
?>
I then open this url in my browser:
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
But instead of inserting "ringk" and "test" in the table, it inserts this:
Can't understand why, any help would be greatly appreciated.
This code is wrong!
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
Replace this.
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['user']."','".$_GET['address']."')";
It's not working because you're calling
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
Which creates $_GET["user"] and $_GET["address"] but you are trying to put in the db $_GET['username'] and $_GET['password'] which don't exist.
You should call:
http://ringkapps.altervista.org/addToDatabase.php?username=ringk&password=test
Plus, read something on security for PHP apps, your code is prone to a lot of vulnerabilities!!!
In the url : http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
We can see user = ringk and address = test.
Where user is the key and ringk it's value.
Where address is the key and test it's value.
You can print all the $_GET value by using var_dump($_GET) and see by yourself what's in it.
My guess is that what you want is to access
$_GET['user'] and $_GET['address']
then just replace the line :
VALUES('".$_GET['username']."','".$_GET['password']."')";
with
VALUES('".$_GET['user']."','".$_GET['address']."')";
or you could update the url to match the code.

PHP, SQL, User Database

I hope I formatted the code properly. I am having trouble making this if statement to work. I've searched and from what it looks like this statement should work. However, when I run it no matter the password if the username starts with kacey then it goes to echo "Logged in as: " . kacey;
Likewise, if I put the input to kaceyfeewaf, it still goes to echo "Logged in as: " . $myuser; This happens regardless of the password I put in. the line $result['username'] should validate to KACEY.
$sql = "SELECT * FROM $dbTable WHERE username = $myuser AND password = $mypass";
$result = mysql_query($sql);
if($result['username'] = $myuser && $result['password'] = $mypass;)
{
echo "Logged in as: " . $myuser;
} else {
echo "Fail ";
}
There are a few issues here.
Firstly, the variables you have in your query are strings, therefore they require to be quoted:
WHERE username = '$myuser' AND password = '$mypass'
Having or die(mysql_error()) to mysql_query() would have signaled the syntax error.
Then you're assigning instead of comparing with
if($result['username'] = $myuser && $result['password'] = $mypass;)
use two equals ==
However, that isn't how you check if those rows exist.
You need to use mysql_num_rows() or use a while loop while using a function to fetch/iterate over results found.
Here is an MySQLi example using mysqli_num_rows():
$conn=mysqli_connect("hostname","username","password","db");
$check_select = mysqli_query($conn, "SELECT * FROM `users`
WHERE email = '$email' AND pw='$pass'");
$numrows=mysqli_num_rows($check_select);
if($numrows > 0){
// do something
}
Now, we don't know where those variables have been assigned, and if from a form that it's using a POST method with matching name attributes.
I.e.:
<form action="" method="post">
<input type="text" name="username">
...
</form>
$username = $_POST['username'];
Another thing which is unknown to us is the MySQL API you're using to connect with. Make sure that you are indeed using the same one as you are using to query with, being mysql_. Different APIs do not intermix, such as mysqli_ or PDO. Use the same one from connection to querying.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Here is a PDO solution pulled from one of ircmaxell's answers:
https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You should use == instead of simple = for your if condition
First of all delete that if stmt and make new one where you check for num rows. If there is num rows > 0 you have valid login. And then print needed results from database od current query.
Edit:
You have = insted of == or === so stmt is always true.

PHP/MySQL - Checking results

I'm trying to create a login system with PHP, but the SQL query is not returning the result I'm expecting.
I have a typical username and password page, and I'm using what the user types in there to check for an account. I know for a fact that the database contains real usernames and passwords but the call to mysqli_num_rows is always returning 0.
Is there something I'm doing wrong?
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con, "SELECT * FROM StaffTable WHERE staffNo='$username' AND password='$password'");
echo mysqli_num_rows($result); //This always prints out 0.
if(mysqli_num_rows($result) == 1)
{
echo "OK";
}
Ignoring the plain-text-password thing which you claim to be aware of, something like this perhaps...
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
$stmt = $con->prepare('SELECT 1 FROM StaffTable WHERE staffNo = ? AND password = ?');
if (!$stmt) {
throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('ss', $username, $password);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
if ($stmt->fetch()) {
echo 'OK';
}
To summarise...
I've checked that the input variables are set and assigned defaults if they're not that shouldn't produce any false positives
I've used a prepared statement with bound parameters to avoid SQL injection vulnerabilities
I throw exceptions when errors occur. These are great because they halt execution and give you all the information you need to debug the problem.
This is my main problem with mysqli over PDO. mysqli is simply not noisy enough when errors occur. You shouldn't have to manually check for error conditions all the time.
I've changed the query to a simple boolean check as that's all you were using it for. The row either exists, or it doesn't.
Try something more along the lines of
$username=$_POST['username'];
$password=md5($_POST['password']);
$query="SELECT * FROM StaffTable WHERE staffNo='".$username."' AND password='".$password."'";
$result=mysqli_query($con,$query);
if (mysqli_num_rows($result)==0)
{
echo "Incorrect Password Or Username Combo";
}
else {
while($row=mysqli_fetch_object($result)) {
$_SESSION['id']=$row['id'];
}
I would say to start with at least running the passwords in encryption for now and look into SQL injection and upgrade as you learn more about what you're looking at.
The biggest flaw in yours aside from what's already been pointed out is
($con, "SELECT * FROM StaffTable WHERE staffNo='$username' AND password='$password'");
With the variables you cannot put them within the query that way; you would want to do something more along the lines of
($con, "SELECT * FROM StaffTable WHERE staffNo='".$username."' AND password='".$password."'");
If you'll notice I escaped from the plain text so that the variables would be set. The reason you're returning 0 results everytime is because you are actually searching for username $username with $password as their password.
Good luck!

Storing info in a PostgreSQl database issue

Ok I am making a registry for my website.
First page asks for some personal info
if($error==false) {
$query = pg_query("INSERT INTO chatterlogins(firstName, lastName, gender, password, ageMonth, ageDay, ageYear, email, createDate) VALUES('$firstNameSignup', '$lastNameSignup', '$genderSignup', md5('$passwordSignup'), $monthSignup, $daySignup, $yearSignup, '$emailSignup', now());");
$query = pg_query("INSERT INTO chatterprofileinfo(email, lastLogin) VALUES('$emailSignup', now());");
$userNameSet = $emailSignup;
$_SESSION['$userNameSet'] = $userNameSet;
header('Location: signup_step2.php'.$rdruri);
}
The first query works. The second query works but doesn't save the email...
the session doesn't work but the header works and sends me to the next page
I get no errors even if I comment out header
next page
#session_start();
$conn = pg_connect("host=localhost dbname=brittains_db user=brittains password=XXXX" );
$signinCheck = false;
$checkForm = "";
if(isset($_SESSION['$userName'])) {
$userName = $_SESSION['$userName'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
if(isset($_SESSION['$userNameSet'])) {
$userName = $_SESSION['$userNameSet'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
This is the top starting the session depending on if your logged in or not.
then if I enter in the info here and put it through this
if($error==false) {
$query = pg_query("UPDATE chatterprofileinfo SET aboutSelf='$aboutSelf', hobbies='$hobbies', music='$music', tv='$tv', sports='$sports', lastLogin='now()' WHERE email='$userName'") or exit(pg_last_error());
//header('Location: signup_step3.php'.$rdruri);
}
nothing shows up for on my database from this.
I have no idea where I went wrong
the website is
http://opentech.durhamcollege.ca/~intn2201/brittains/chatter/
For starters, don't put things that aren't strings in single-quotes like that. 'now()' means a literal string "now()"
Also, if you're doing updates to your database you're better of using prepared statements to help prevent against sql injection. In your case, see http://www.php.net/manual/en/function.pg-prepare.php

Categories