MYSQL PHP No Database Selected - Can't Find Error - php

<?
require_once('etcore.php');
mysql_connect($dburl,$dbuser,$dbpass) or die(mysql_error());
mysql_select_db("rshost") or die(mysql_error());
$username=strtoupper(clean($_POST['username']));
$password=md5($_POST['password']);
$andover = mysql_query("SELECT * FROM users WHERE usernameupper='$username' AND password='$password'") or die(mysql_error().__LINE__);
$numberofthings = mysql_num_rows($andover) or die(mysql_error().__LINE__);
if ($numberofthings = 1) {
$getit=mysql_fetch_array($andover) or die(mysql_error().__LINE__);
$_SESSION['id'] = $getit['id'];
header('Location: index.php');
}
else {
?>
<h1>Login:</h1>
<img src='http://media.idownloadblog.com/wp-content/uploads/2011/12/Warning.png' width="25" height="25" />
<strong style="color:#F03;">Incorrect Username and/or Password </strong><br>
<form method="POST" action="login.php">
Username: <input name="username" type="text" /><br />
Password: <input name="password" type="password" /><br />
<input name="submit" type="submit" value="Log In!" /><br />
</form>
<? } ?>
This is the code I am using. Whenever I run the code, I get the error "No database selected" on line 7. Any help would be appreciated. Thanks! BTW: Db user, pass and URL are all in the 'etcore.php' file, so it is not a problem there. I have also tried replacing those variables with strings and get the same error.

How about:
mysql_select_db("rshost", mysql_connect($dburl,$dbuser,$dbpass))
or even better:
$handle = mysql_connect($dburl,$dbuser,$dbpass);
mysql_select_db("rshost", $handle);
And maybe for a better knowledge and understanding:
manual page
in the section parameters
so it would be clear why it may OR may not work without using the $handle argument

Give the database privileges. May be you don't have the user permission to access database,
check this
mysql> grant all privileges on Databasename.* to 'username'#'localhost' identified by password

Related

php - Can't get the right if else condition in regards of variables connecting to the database

Really can't finish my project because of this condition. My project is a Login Page.
It always continues to the first if condition, but it is for else condition. I just only started studying this php now, although it is being taught to us last week.
login.php
<?php
session_start();
include 'register/dbconnect.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($connect, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
header("Location: index.php");
} else {
header("Location: login/home/home.php");
}
?>
index.php (in the login form part)
<form action="login.php" method="POST">
<input type="text" name="uid" class="loginField" placeholder="Enter your username" required><br />
<input type="password" name="pwd" id="passss" class="loginField" placeholder="Enter your password" required>
<img src="withAcc/img/blindeye.png" onMouseOver="showPass()" onMouseOut="hidePass()" id="eye1" class="eyes"><br /><br />
<p><input type="checkbox" id="keepSigned" value=""> <label for="keepSigned">Stay signed in</label>
Forgot password?</p>
<input type="Submit" value="Login" id="logInBut" ><br />
<p>Do you have an account? Register</p>
</form>
Edited login.php
if (!$row = $result->fetch_assoc()) {
header("Location: index.php");
} else {
header("Location: login/home/home.php");
}
I edited it like this, but it neither works. It always going to index.php, although the username and password is stored in the database.
This is a pretty strange condition:
if (!$row = mysqli_fetch_assoc($result)) {
And I can't help but wonder if some combination of operator precedence and query success/failure is going to silently produce unexpected results here. I imagine a more intuitive way of doing this would be to check the number of rows in the query result:
if (mysqli_num_rows($result) > 0) {
However, there are a couple other improvements you should make as well to round this out a bit better. First, as mentioned in comments on the question above, you should definitely make use of prepared statements to avoid SQL injection. This is important not only for security but also for general stability and debugging of your code. (Directly using input as code like you currently do makes you much more responsible for the syntax of that code, which often leads to errors.)
Additionally, after executing a query (and before examining the results of that query, so before your if statement) you should check if the query was successful. If it's not successful, your $result variable will be null. So check if $result is null and if it is, don't try to use it for logging in. Instead, examine the error from the database. Something as simple as:
echo mysqli_error($connect);
Also, and this is very important, you are currently storing user passwords in plain text. This is a very, very bad thing. User passwords should always be hashed so that they can't be retrieved in their original form. PHP has some built-in functionality to help with this.

Two part form validation in PHP

I am working on my first $_POST form. I have created a simple HTML form and used the post method and my action points to a php document. I want to do some validation with the php to make sure the passwords match and simple things like that. I guess I am not understanding how to make the form work for me because right now when I submit my form, all it does is show my php code on the next page. How do you get the php to actually check the values instead of just displaying the code? Here is what I have for my php file:
<?php
function validatePassword($pwd) {
//create array to store test information
$messages = [];
//test for at least 8 characters
if (strlen($pwd) < 8) {
$messages []= "Your Password Must Contain At Least 8 Characters!<br />";
}
//test for max length
if (strlen($pwd) > 16) {
$messages []= "Your Password is too long!<br />";
}
//test to see if password contains number
if(!preg_match("#[0-9]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Number! <br />";
}
//test to see if password has capital letter
if(!preg_match("#[A-Z]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Capital Letter!<br />";
}
//test to see if password has a lowercase letter
if(!preg_match("#[a-z]+#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Lowercase Letter!<br />";
}
//test to see if password has special character
if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
$messages []= "Your Password Must Contain At Least 1 Special Character!<br />";
}
//test to see if password contains a space
if (strpos($pwd, ' ') > 0) {
$messages []= "Your password cannot contain a space!<br />";
}
//password passed all tests
if (empty($messages)) {
return "Password is acceptable<br />";
}
//return the array
return implode("\n", $messages);
}
if ($pass1 != $pass2){
$msg = "Passwords do not match";
}
else{
$msg = "Password confirmed!";
}
validatePassword($pass1);
?>
Form code:
<html>
<head>
<title>PHP Form</title>
</head>
<body>
<form name=newForm method=post action=formProcess.php>
UserName: <input type=text name=userName size=15 maxlength=15><br>
Password: <input type=password name=pass1 size=15><br>
Confirm Password: <input type=password name=pass2 size=15><br>
<p>
I agree to the terms and conditions.<br>
<input type=radio name=terms value=yes> Yes
<input type=radio name=terms value=no> No
<p>
Enter comments here:<br>
<textarea name=comments rows=6 cols=50 wrap=physical></textarea>
<p>
<input type=submit name=submitForm>
<input type=reset name resetForm>
</p>
</form>
</body>
</html>
By the way I know I can put the php in the HTML document, but I really want to attempt to do two seperate files and see how this works. Thanks for any help!
It seems you don't have a web server
Download xampp and place your php file in the htdocs folder of the server, then you should be able to see it on http://localhost
Don't forget to actually start your Apache server and make sure it has a green light and no errors. Usually Skype will block it because it uses its port, so be careful on that.
Ok, first let's make some valid HTML
<html>
<head>
<title>PHP Form</title>
</head>
<body>
<form name="newForm" method="post" action="formProcess.php">UserName:
<input type="text" name="userName" size="15" maxlength="15">
<br>Password:
<input type="password" name="pass1" size="15">
<br>Confirm Password:
<input type="password" name="pass2" size="15">
<br>
<p>I agree to the terms and conditions.
<br>
<input type="radio" name="terms" value="yes">Yes
<input type="radio" name="terms" value="no">No
<p>Enter comments here:
<br>
<textarea name="comments" rows="6" cols="50" wrap="physical"></textarea>
<p>
<input type="submit" name="submitForm">
<input type="reset" name="resetForm">
</p>
</form>
</body>
</html>
Then in your formProcess.php file, delete everything and try something like
<?php
echo $_POST["userName"];
?>
If this doesn't print the value you submitted in your username field, then there is a problem with your server.
In order to run PHP pages you need to first install it with a web server.
If you're using windows you can try WAMP which bundles PHP with Apache and MySQL:
http://www.wampserver.com/en/
For Linux:
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu
For MAC:
https://www.mamp.info/en/
In PHP there are two type validation such javascript validation (Client side validation) and another is Php Validation such as (Server side Validation).
1- In java Script validation done on Client Machine.
2- In Server Side (PHP validation) Done On server.

SQL Injectable Webpage

I'm creating a SQL Injection demo as a project for my class. I've created a login page but i cant seem to be able to inject it. Here is what I have written for the page. I have tried blind SQLi creating multiple clauses withing the username field. The only other thing I can think of is to use subqueries or to change my code to make it easier.
EDIT* Trying to Inject the username field *
<?php // Check to see if there was a request method that is a post type
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// Check to see if username field is null
if (!empty($_POST['username'])) {
// Connect to the server using credentials
$con = mysql_connect('localhost','root','sqlcool1');
// If the connection was not successful
if (!$con){
echo 'OUCH';
die('Could not connect: '.mysql_error());
}
// Select the correct database from the server
$db = mysql_select_db('injectme',$con);
// Pass a sql query through the table to pull the user field that was entered in the form
// Return the results in an array
$sql = mysql_query('SELECT * FROM user WHERE username = "' . $_POST['username'] . '"');
$row = mysql_fetch_row($sql);
// compare $row["password"] to $_post["password"]
// if they match it's good: log them in
// if not, they're beat: don't log them in
if ($_POST["username"] == $row[1] && $_POST["password"] == $row[2]) {
// do something to let them know that it worked
echo('<html>
<head>
<meta http-equiv="refresh" content="3; url=search.php">
</head>
<body>
<p style="color:green">logged in</p>
</body>
</html>');
} else {
// do something to let them know it didn't work
echo('<p style="color: red">Invalid username or password.</p>');
echo('<form name="login" action="login.php" method="POST">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="submit_button" value="Submit">
<button type="submit" formaction="register.php">Register</button>
</form>');
}
//Close the connected session with the server
mysql_close($con);
} else {
// Repost Form
echo ('<p style="color: red"> No username / password provided.</p>');
echo('<form name="login" action="login.php" method="POST">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="submit_button" value="Submit">
<button type="submit" formaction="register.php">Register</button>
</form>');
}
}
else
{
echo('<form name="login" action="login.php" method="POST">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="submit_button" value="Submit">
<button type="submit" formaction="register.php">Register</button>
</form>');
}
?>
The code you have posted is entirely vulnerable and can be used to view the content of the entire database. One way to exploit it is with time based attack where you create an artificially long response time if a condition is true.
Consider the following username :
" UNION SELECT (WHEN "A" = (SUBSTR(password, 1, 1)) THEN SLEEP(5) ELSE 1 END) AS username, 1 as password FROM user LIMIT 0, 1 --
If the response is longer than 5 seconds, you can know the value of the first character is "A" otherwise just test for an other character. After that you just have to repeat the same pattern for other position in the string until you have found all characters of the password. After that, you can just directly use the admin password. Since it requires a lot of queries those type of attack are often scripted.
If you want to read more about it, it's called Blind SQL Injection.
To successfully exploit this vulnerability, you need to be able to inject some code such that the resulting SQL statement will return something that will pass the later test:
$_POST["username"] == $row[1] && $_POST["password"] == $row[2]
So the second column needs to be equal to the submitted username and the third row needs to be equal to the submitted password.
Now as the injection happens with the submitted username, you have a problem.
Because you cannot supply a username that fulfills both the inject some data into the result set aspect and the inject a value for the username that is identical to the injected code that injects a value for the username aspect.
The former is quite easy (assuming three columns in user):
username := '" UNION SELECT 1, "admin", "'
password := ''
This results in:
SELECT * FROM user WHERE username = "" UNION SELECT 1, "admin", ""
However, the $_POST["username"] == $row[1] part remains unresolvable as you would need to make the second SELECT return the submitted username as username column value. And that’s just not possible.
Now if you just remove the $_POST["username"] == $row[1] it works fine.
It depends on what you are trying to inject. If you are trying to inject a second query, this is not possible - the mysql_query function does not support multiple queries. From the docs:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
Of course, it is still vulnerable to additional WHERE clause injections.

adding new user to mysql through php

Have problem with adding new user using mysql and php. Trying to find out how to done my problem probably all day, but I didn't this.
So I connect my db in connect.php
<?php
$db = mysql_connect("localhost","root","") or die("MySQL are not launched? Could not connect to DB");
if(!$db) {
die("Your DB variable probably has no \$db name. No DB launched");
}
if(!mysql_select_db("fdb",$db)) {
die("wrong DB name");
}
?>
made html inputs where user try to make account:
<form method="post" action="reguser.php">
type username: <input type="text" name="user" size="22"/><br>
type password: <input type="text" name="password" size="15"/><br>
retype password: <input type="text" name="password2" size="15"/><br>
type e-mail: <input type="text" name="email" size="50"/><br>
<input type="submit" value="submit"/>
and when he pushes submit it checkes on all error (ex not same passwords) but the problem i get the same error could not register from checking mysql_query($SQL)
else {
$SQL = "INSERT into users(name, password, email) VALUES ('$user','$password','$email'";
mysql_query($SQL) or die('could not register');
print "your registration complete<br>";
}
You seem to be missing a ) here:
VALUES ('$user','$password','$email'";
Try this:
VALUES ('$user','$password','$email')";
That is most likely merely a syntactical issue.

SQL error when creating my own form in joomla

hey guys i want to creat my own form in joomla and use the post method .
so i download extension to make my own code in articles in joomla like this
<form action="http://localhost/ocr/includes/Create_Subject.php" method="post">
username <input type="text" name="menu_name" value=""/><br/>
password <input type="text" name="id" value=""/><br/>
<input type="submit" name="save" value="Submit" />
</form>
and then i go to my website data base and create a table called show to add into it my values which i get it from my form and also
make a php file called (Create_Subject.php) and i put it in includes file in my website and called it by action like u see in my code in my html and the code of that php here
<?php
$coonect=mysql_connect("localhost","root","");
if(!$coonect){
echo "Data_base error";
die(mysql_error());
}
?>
<?php
$username=$_POST['menu_name'];
$id=$_POST['id'];
$db_select=mysql_select_db("ocr");
if(!$db_select){
die(mysql_error());
echo" error";
}
$query= "INSERT INTO show (
name , id )
VALUES( '{$username}' ,{$id} ) " ;
if(mysql_query($query)){
header("www.google.com");
exit;
}else{
echo"<p> error </p>";
}
?>
`
and when iam run the site show to my an error what am doing wrong any heleeeep plez ....:))
Here you can find plenty of information about SQLQuering with Joomla!
http://docs.joomla.org/Accessing_the_database_using_JDatabase
You can ask anything you want if you have any trouble...

Categories