PHP upload filename to mysql - mysql

This code transfers the file to the specified folder and db table but when I launch/open/run the page on the browser,it automatically sends something to the db table and the filename field is empty.I haven't even clicked/uploaded anything yet. I don't know if i explained it properly.The problem is when i opened the page,i checked the db table rows and an empty row was made.the id increments btw, and the filename field is empty.(not uploading anything yet.) What's wrong with the code?
<?php
if(isset($_FILES['filename'])){
$errors= array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "admin";
$filename = false;
if(isset($_FILES['filename'])){
$filename = $_FILES['filename']['name'];
}
// Create connection
mysql_connect($servername, $username, $password) or die ('MySQL Not found // Could Not Connect.');
mysql_select_db("admin") or die(mysql_error()) ;
mysql_query("INSERT INTO upload_test (fileName)
VALUES ('$filename')") ;
?>
my form:
<form name="form" method="POST" enctype="multipart/form-data" >
<input name="filename" type="file" id="filename" />
<input name="submit" type="submit" id="submit"/>
</form>

That is because you are always executing the INSERT statement. You only want insert a record once you have uploaded.
if(isset($_FILES['filename'])){
$errors = array();
$file_name = $_FILES['filename']['name'];
$file_size =$_FILES['filename']['size'];
$file_tmp =$_FILES['filename']['tmp_name'];
$file_type=$_FILES['filename']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['filename']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
// if there are no errors...
if (empty($errors)==true) {
// upload the file...
move_uploaded_file($file_tmp,"uploads/".$file_name);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "admin";
// and create a new record in the database
mysql_connect($servername, $username, $password) or die ('MySQL Not found // Could Not Connect.');
mysql_select_db("admin") or die(mysql_error()) ;
mysql_query("INSERT INTO upload_test (fileName) VALUES ('$file_name')") ;
echo "Success";
}else{
print_r($errors);
}
}
On a side-note, a shorter way to get the extension of file is to use pathinfo()
$file_ext = pathinfo($_FILES['filename']['name'], PATHINFO_EXTENSION);

Related

Fatal Error: Uncaught error Call to undefined function mysql_real_escape_string() HTML/PHPMYADMIN

I am currently stocked :( basically I am doing a login page There is no problem with the login page but once i submit it... this is my code for my login page.
<form action= "process.php" method="POST">
Username: <input type="text" id="user" name="username">
Password: <input type="password" id="pass" name="password">
<input type="submit" value="Submit" >
now my process.php however is making the same error..I cant seem to find the problem. Please Help Here is the code
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
//to prevent sql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string ($password);
//connect to the server and select database
mysql_connect("localhost","root","");
mysql_select_db("franklin offshore");
//query the database for user
$result = mysql_query("select * from login where username='$username'
and password='$password'")
or die ("Failed to query database ".mysql_error());
$row = mysql_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password)
{
echo "LOGIN SUCCESS WELCOME" .$row['username'];
}
else
{
echo "Failed to LOGIN" ;
}
?>
This is what it keeps showing
Fatal error: Uncaught Error: Call to undefined function
mysql_real_escape_string()
Please help
I recommend to use mysqli (replace mysql with mysqli in your code) and to connect to your database with a variable.
Like this:
$db = mysqli_connect("localhost", "username", "", "database");
Then you have to put $db in your mysqli_query as a parameter.
Here is an example:
$result = mysqli_query($db, "select * from login where username='$username' and password='$password'");
Try below... It will work.
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$db = mysqli_connect("localhost","root","","franklin offshore");
$result = mysqli_query($db, "select * from login where username = '$username' and password = '$password'")
or die("Faild to query database " .mysqli_error());
$row = mysqli_fetch_array($result);
if ($row['username']== $username && $row['password'] == $password){
echo "Login success!!! Welcome " .$row['username'];
} else {
echo "Faild to login!";
}
?>
As someone mention in above you need to replace all the mysql with mysqli in your code.
Please refer this link MySQL vs MySQLi when using PHP
And also remove "mysql_real_escape_string" code also.
Thank you.

how to add name number email id to my mysql database

i have created a website with shared hosting from a company and i have created themes and fronted end development is completed. now the problem is
If some one visited my site and entered their details in temple having name, mail,number.
So how i can see those name and email and number in my mysql database.
I have installed mysql database.
Assuming visitors already have filled a HTML <form> element and data are inserted into the database, you will need to execute a SELECT statement to get the visitors details.
SELECT name, mail, number FROM [tableName]
Here's a PHP example :
<?php
$host = "127.0.0.1";
$user = "myuser";
$pass = "mypass";
$bdd = "mydatabase";
try {
$objBdd = new PDO("mysql:host=$host; dbname=$bdd; charset=utf8", $user, $pass) ;
$objBdd->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
} catch(Exeception $prmE) {
die('Error : ' . $prmE->getMessage()) ;
}
$getMyVisitors = $objBdd->query("SELECT name, mail, number FROM myTable");
while ($visitorData = $getMyVisitors->fetch()) {
echo "----\r\n";
echo "Name : " . $visitorData['name'] . "\r\n";
echo "Mail : " . $visitorData['mail'] . "\r\n";
echo "Number : " . $visitorData['number'] . "\r\n";
echo "----\r\n";
}
$getMyVisitors->closeCursor();
$objBdd = NULL;
Every statements using dynamic user data (example: username, password, comments ...) should be prepared.
If you want to use a WHERE condition, use prepared statements like
$getMyVisitors = $objBdd->prepare("SELECT name, mail FROM myTable WHERE number = ?");
$getMyVisitors->execute(array("+33000000000"));
Now, if the visitors informations are not saved in the database, you will need to create a HTML form element.
Your HTML form element should looks like :
<form action="myScript.php" method="POST">
<input type="submit" value="Send my informations">
</form>
Where myScript.php is a PHP script that will save the visitor's informations into the database. Use my example above to make that script, you will need to use an INSERT statement.
You will need to add input elements in the form as much as you need, in your case, three (name, mail, number).
Note that you will need to set the name attribute to each of your inputs to be able to get the inputs value in your PHP.
Example : <input type="email" name="visitorMail"> goes with $myVisitorMail = $_POST['visitorMail'];.
You Could directly use php to do this task! The sample code would get you going around!
You could view there details by firing query like
SELECT Name,Phone,Email FROM Customers
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Connecting mySQL db through PHP

Let me begin by saying I am extremely new at this. I am trying to develop a mobile app and a website with no real experience. There is likely something that I have missed or I am doing wrong but I cannot seem to pin point where the issue is. Prior to creating my own, I followed a video guide (with the demo files downloaded to my computer) but cannot seem to connect to my database. I have also copied the demo files and placed them into my code and it is still getting me caught on one section. I am using the program MAMP for the connection and Brackets for the code. Below are my session files:
Database connection-
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "Login System";
$con = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
My sign up document-
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
echo <h2>Please fill in all fields;
exit ();
} else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO users (first, last, email, uid, pwd) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
?>
My Login Sheet
<?php
include_once 'header.php';
?>
<section class="main-container">
<div class="main-wrapper">
<h2>Signup</h2>
<form class="signup-form" action="includes/signup.inc.php" method="POST">
<input type="text" name="first" placeholder="Firstname">
<input type="text" name="last" placeholder="Lastname">
<input type="text" name="email" placeholder="E-mail">
<input type="text" name="uid" placeholder="Username">
<input type="password" name="pwd" placeholder="Password">
<Button type="submit" name="submit">Sign up</Button>
</form>
</div>
</section>
<?php
include_once 'footer.php';
?>
I have reset the password for 'root' to 'root' and ensured I can login with that. The document that checks for error's lists if any field is empty, return to the previous page with the word "=empty" in the url. No matter what I type into my fields, it is either not pushing the information into the database or I have incorrectly mapped my fields so one of the database fields is empty.
Any help would be greatly appreciated. As I said at the beginning of this post, I am extremely new at this. You may see something that is incredibly obvious and somewhat dumb... you've been warned! I am working on creating a mobile application and website that allows users to login. The login attempt will reference my localhost database to confirm that the user does not exist or that the user is not in use.
Thank you!
To check the connection handling, you can add this after the connect attempt:
$conn = mysqli_connect( ... );
if ( !$conn ) {
die( 'Did not connect: ' . mysqli_connect_error() );
}
To check the handling after a query, you can add this after the query attempt:
$result = mysqli_query( $conn, $sql );
if (false === $result) {
die( 'Query error: ' . mysqli_error($conn) );
}
Using php -l right off the bat I found some errors in your code in the includes/signup.inc.php file.
The line echo <h2>Please fill in all fields; was not quoted which would cause an error 500 when I tried to load the page. To fix this I added single quotes echo '<h2>Please fill in all fields</h2>'; and added </h2> to close the HTML tag.
After that was fixed the page would return Please fill in all fields even though I had filled all the fields in the sign up form. to fix this issue I changed mysqli_real_escape_string($conn, $_POST['POST_DATA']); to strip_tags(trim($_POST['POST_DATA']));.
The email line is a little bit different, mysqli_real_escape_string($conn, $_POST['email']); is changed to filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));
I also changed the $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT); (PHP Documentation: http://php.net/manual/en/function.password-hash.php) line to add salt. What is salt?
In cryptography, a salt is random data that is used as an additional
input to a one-way function that "hashes" a password or passphrase.
Salts are closely related to the concept of nonce. The primary
function of salts is to defend against dictionary attacks or against
its hashed equivalent, a pre-computed rainbow table attack.
Source: en.wikipedia.org/wiki/Salt_(cryptography)
Also take a look at this post in stackexchange/security for some more information Link: https://security.stackexchange.com/a/51983
New includes/signup.inc.php file
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = strip_tags(trim($_POST['first']));
$last = strip_tags(trim($_POST['last']));
$email = filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));
$uid = strip_tags(trim($_POST['uid']));
$pwd = strip_tags(trim($_POST['pwd']));
//Error handlers
//Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
echo '<h2>Please fill in all fields</h2>'; // was echo <h2>Please fill in all fields; which would cause an error 500
exit ();
}
else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
}
else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
}
else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
}
else {
//Hashing the password
$options = [
'cost' => 12,
];
$hashedPwd = password_hash($password, PASSWORD_BCRYPT, $options); // Adding salt to hashed password
//Insert the user into the database
$sql = "
INSERT INTO users (first, last, email, uid, pwd)
VALUES ('" . $first . "',
'" . $last . "',
'" . $email . "',
'" . $uid . "',
'" . $hashedPwd . "');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
}
else {
header("Location: ../signup.php");
exit();
}
?>
In addition it would be a good idea to learn how to use the OOP style of mysqli to do more complex database manipulation
PHP Documentation on mysqli: php.net/manual/en/mysqli.query.php
It would also be good to add a column to act as a serial number to allow later editing of values for the users using this MySQL Query:
ALTER TABLE `users` ADD `serial` INT PRIMARY KEY AUTO_INCREMENT;

Unable to Change Password Correctly

As much as I've tried I can't see why this code wouldn't work. Whenever I atmempt to change a password using this page, it says an incorrect password has been supplied.
This is the last page I have to get to work for this site, so any help would be appreciated.
<?php
require_once ("dbconnect.php");
// include file to do db connect
require_once ('checklog.php');
require_once ("functions.php");
session_start();
$username = ($_POST['username']);
$password = ($_POST['password']);
$newpassword = ($_POST['newpassword']);
$repeatpassword = ($_POST['repeatpassword']);
if (isset($_POST['submit'])) {
if ($username && $password) {
$hashpass = salt($password);
$query = "SELECT ID FROM users WHERE username='$username' AND password='$hashpass'";
if ($username == $datausername && salt($password) == $datapassword) {
// PASSWORD CHANGING IS DONE HERE
if ($newpassword == $repeatpassword) {
// From register
if (strlen($newpassword) > 25 || strlen($newpassword) < 6) {
$message = "Password must be 6-25 characters long";
}
else {
// part 8
// Process details here
if ($db_server) {
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}
else {
if ($db_server) {
// clean the input now that we have a db connection
$newpassword = clean_string($db_server, $newpassword);
$repeatpassword = clean_string($db_server, $repeatpassword);
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)) {
$message = "This is your current password. Please try again.";
}
else {
// Process further here
$newpassword = salt($newpassword);
$query = "UPDATE INTO users (password) VALUES ('$password')";
mysqli_query($db_server, $query) or die("Insert failed. " . mysqli_error($db_server));
$message = "<h1>Your password has been changed!</h1>";
}
mysqli_free_result($result);
}
else {
$message = "Error: could not connect to the database.";
}
mysqli_close($db_server);
// include file to do db close
}
}
// This code appears if passwords dont match
}
else {
$message = "<h1>Your new passwords do not match! Try again.</h1>";
}
}
else {
$message = "<h1>Incorrect password!</h1>";
}
}
else {
$message = "<h1>That user does not exist!</h1>" . "Please <a href='password.php'>try again</a>";
}
// Close connection!
}
else {
$message = "<h1>Please enter a valid username/password</h1>";
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<?php
include_once ("header.php");
?>
<div id="apDiv1"><span class="rich-list">
<title>Change your Password</title>
<h1>So you want to change your password, <?php
echo $_SESSION['username'];
?>?</h1>
<form action='password.php' method='POST'>
<div align="right">Current Username:
<input type='text' name='username'><br />
Current Password: <input type='password' name='password'><br />
New Password: <input type='password' name='newpassword'><br />
Repeat New Password: <input type='password' name='repeatpassword'><br />
<input type='submit' name='submit' value='Confirm'>
<input name='reset' type='reset' value='Reset'>
</div>
</form>
<?php
echo $message
?>
<?php
include_once ("footer.php");
?>
</div>
</body>
</html>
</body>
</html>
I don't know how the 'salt' function is defined - you might want to include it in your post.
I suspect that salt will pick some random salt, and hash with that - if so, to verify, you will need to use the salt from the encrypted password, or you will get a different outcome.
So, to verify a password:
get the username and guess,
get the encrypted password for the username
get the salt from the encrypted password (often the first few characters)
encrypt the guess with the salt from the encrypted password
compare this encrypted guess to the encrypted password.
Ignoring the many bad practices in your code for now, the problem is that you never retrieve the user's password from the database:
// $datausername and $datapassword have not been set, so this will always be false
if ($username == $datausername && salt($password) == $datapassword) {
// ... code
} else {
$message = "<h1>Incorrect password!</h1>";
}
You did set the $query string, but you forgot to run the actual query in the database and retrieve the results, if any.
To run a query, first you establish a database connection:
$dbc = new mysqli("db_host", "db_user", "db_password", "db_name");
if (mysqli_connect_errno()) {
die("Could not connect to MySQL: " . mysqli_connect_error());
}
Let's assume you did that in your "dbconnect.php" file, so now you have a valid $dbc connection and your $query string. The following will give you a mysqli_result object, or FALSE if the query fails.
$result = $dbc->query($query);
Please see the PHP manual for more information on how to use that object.
Also, PHP has an excellent built-in function called password_hash - I suggest you use this instead of what appears to be a custom-defined function 'salt'.
To further improve your code, you should learn about SQL Injection and how to avoid it, such as by using prepared statements.

Cannot figure out why my SQL query is not returning a result

Here is the entire code guys. I am trying to create a simple user authentication system.
Here is the entire code guys. I am trying to create a simple user authentication system.
Here is the entire code guys. I am trying to create a simple user authentication system.
Here is the entire code guys. I am trying to create a simple user authentication system.
<?php
if (!isset($_POST['username']) OR !isset($_POST['password']) OR empty($_POST['username']) OR empty($_POST['password'])) {
echo "Please login:";
echo '<form method="POST">';
echo 'Username: <input type="text" name="username">';
echo 'Password: <input type="password" name="password"></br>';
echo '<input type="submit" value="Login">';
echo '</form>';
}
else {
$username = $_POST['username'];
$password = md5($_POST['password']);
try {
$pdo = new PDO('mysql:host=localhost;dbname=userauth', 'norman101', 'beecher123');
}
catch(PDOException $e) {
echo 'ERROR:' . $e->getMessage();
}
$sql = "SELECT * FROM userinfo WHERE username=?, AND password=?";
$pds = $pdo->prepare($sql);
$pds->execute(array($username, $password));
$row = $pds->fetch(PDO::FETCH_ASSOC);
print_r($row);
}
?>
I think you are missing the AND operator:
$sql = "SELECT * FROM userinfo WHERE username=? AND password=?";
try this
$pds= $pdo->prepare("SELECT * FROM userinfo WHERE username=:username AND password=:password");
$pds->execute(array(':username' => $username, ':password' => $password));
$row = $pds->fetchAll(PDO::FETCH_ASSOC);