Every time I leave any textbox unfilled for the 1st time, it would be registered to the db same as if I leave all the textboxes empty but when you do it for the 2nd time (any of the two), that would be the time the alert box would pop-up... I don't what to do.
Help me please.
Here's my code:
<?php
ini_set('display_errors', 0);
$email= $_POST['email'];
$user= $_POST['user'];
$password= $_POST['password'];
$image =($_FILES['image']['name']);
$submit= $_POST['submit'];
if (empty($email) || empty($password) || empty($user) )
{
echo "<script type='text/javascript'>
alert('You did not complete all of the required fields');
window.location='blah2.php';
</script>";
}
if(isset($submit))
{
$con = mysqli_connect("localhost", "root", "", "top")
or die('error in connection'.mysqli_connect_error());
$q = "SELECT username , email FROM registries WHERE username = ? OR email = ?";
$stmt = mysqli_prepare ($con, $q);
mysqli_stmt_bind_param($stmt, 'ss', $user, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $user , $email);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_num_rows($stmt);
if($result > 0)
{
echo "<script type='text/javascript'>
alert('Email address or Username is already taken. Please pick another one.');
window.location='blah2.php';
</script>";
}
else
{
$q="INSERT INTO registries VALUES (?,?,?,?)";
$stmt = mysqli_prepare($con, $q);
move_uploaded_file($_FILES["image"]["tmp_name"],"uploads/" . $_FILES["image"]["name"]);
mysqli_stmt_bind_param($stmt, 'ssss', $email, $user, $password, $image);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_close($stmt);
header('Location: blah.php');
}
}
with this
$submit= $_POST['submit'];
$submit is always set
maybe you could try
if (isset($_POST['Submit']))
and for debugging purpose you could try to var_dump $email, $password and $user and check if maybe they are really empty when you post your form once or twice
If I understand you right then just move
if(isset($submit)){
on top of your code right after
ini_set('display_errors', 0);
Related
I have created a simple php login form which connects to a database and checks the validity of username and password. If they are correct it allows access if not an error message is displayed. My problem is that when I go to my login page it is automatically giving me an error message saying"invalid user etc" before i have even attempted to login in. Any suggestions as to why this might be?
<?php
session_start();
include('conn.php');
$theUserID = $_POST['userID'];
$theUserPassword = $_POST['password'];
$query = "SELECT userID, firstName, password FROM user INNER JOIN password ON user.passwordID=password.passwordID WHERE userID='$theUserID' AND password='$theUserPassword'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(mysqli_num_rows($result)>0){
//let them in
$_SESSION['myuser40058058']=$theUserID;
Header("Location:index.php");
}
else{
$message = "Incorrect Username or Password";
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
<?php
session_start();
check if the form was posted and user and password are set
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userID']) && isset($_POST['password'])){
THIS IS ABSOLUTE UNSECURE !!!
check Paths for include and test values of the form!!
include('conn.php');
$theUserID = $_POST['userID'];
$theUserPassword = $_POST['password'];
THIS IS UNSECURE !!!
use at least a $mysqli->real_escape_string($YOUR_VARIABLES) in the query
$query = "SELECT userID, firstName, password FROM user INNER JOIN password ON user.passwordID=password.passwordID WHERE userID='$theUserID' AND password='$theUserPassword'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(mysqli_num_rows($result)>0){
//let them in
$_SESSION['myuser40058058']=$theUserID;
Header("Location:index.php");
}else{
$message = "Incorrect Username or Password";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>
I am creating login in angularjs, in login.phppage i am verify whether user exist or not by number of rows exist or not means using rowCount() in php pdo but it always return 0 result. here is my php file:
<?php
/*
* Collect all Details from Angular HTTP Request.
*/
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;
$user ="root";
$pass ="m2n1shlko";
$dbh = new PDO('mysql:host=localhost;dbname=blog_db', $user, $pass);
$query = $dbh->prepare("SELECT * FROM `signup_tbl` WHERE `email`='$email' AND `password`='$pass'");
$query->execute();
$count = $query->rowcount();
if($count>0){
echo "You have sucessfully login with this Email: ".$count; //this will go back under "data" of angular call.
}else{
echo "Error While Authentication with this Email: " .$count;
}
/*
* You can use $email and $pass for further work. Such as Database calls.
*/
?>
Data from the controller get here I didn't know where i am missing the code. Apreciate if help .. Thanks
You overwrite $pass to database (line 13) and for user (line 8). Change database password to $db_pass.
...
$email = '...';
$pass = $request->password;
...
$db_pass = '...';
...
$dbh = new PDO('mysql:host=localhost;dbname=blog_db', $user, $db_pass); // $pass to $db_pass
Its $query->rowCount(); NOT $query->rowcount();
$count = $query->rowCount();
if($count>0){
echo "You have sucessfully login with this Email: ".$count; //this will go back under "data" of angular call.
}else{
echo "Error While Authentication with this Email: " .$count;
}
Read Manual rowCount
I have done in my local system,it's working good,Try like below example,this is working fine.just follow this example and do your code right way:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "xxx";
// Create connection
$conn = new PDO('mysql:host=localhost;dbname=xxx', $username, $password);
$query =$conn->prepare("select * from testing");
$query->execute();
$count = $query->rowCount();
echo "Counting:".$count;
?>
Output:-
Counting:3
Please anyone solve my problem my code execute automatically. Here it is.
$con=mysql_connect("localhost","root","") or die('Not Connected');;
mysql_select_db("reg");
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['user'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if($fname=='' or $lname=='' or $email=='' or $username==''
or $password=='' or $cpassword==''){
echo "<script>alert('Please Fill Out Blank Fields')</script>";
exit();
}
}
$query="INSERT INTO `form`(`ID`, `fname`, `lname`, `email`, `username`, `password`, `cpassword`)
VALUES (NULL, '$fname','$lname','$email','$username','$password','$cpassword')";
if (mysql_query($query)) {
echo "<script>alert('Registered Successfully')</script>";
}
"Here is my question: Is that when i refresh the page the last code executes automatically" Please check my code.
Thanks.
<?php
function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
First, put the last 3 lines inside the if block. This will ensure that the query only executes if there is a POST request.
To handle the refresh problem, use the Post-Redirect-Get pattern to ensure that the data isn't reposted. If the query executes successfully, redirect to a new page, and show a success message there.
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['user'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if($fname=='' or $lname=='' or $email=='' or $username==''
or $password=='' or $cpassword==''){
echo "<script>alert('Please Fill Out Blank Fields')</script>";
exit();
}
// Run this query only if something was POSTed.
$query="INSERT INTO `form`(`ID`, `fname`, `lname`, `email`, `username`, `password`, `cpassword`)
VALUES (NULL, '$fname','$lname','$email','$username','$password','$cpassword')";
if (mysql_query($query)) {
// Redirect to successpage.php, and print the success message there.
header("Location: successpage.php");
exit();
// echo "<script>alert('Registered Successfully')</script>";
}
}
Alternatively, if you really want to stay on the same page, you could redirect to this page itself, with some query string, and display the appropriate message upon receiving the same:
if (isset($_POST['submit'])) {
...
if (mysql_query($query)) {
// Redirect to the same page, with a query string indicating success
header("Location: thesamepage.php?success=1");
exit();
}
}
// Check if registration was successful
if(isset($_GET['success'])) {
// Display the success message.
echo "<script>alert('Registered Successfully')</script>";
}
I think your code is kinda confuse.
Look:
/
/ connect.php
/ (pagewithform).php
/ (scripttoregister).php
connect.php
<?php
$server = "server";
$user = "user";
$pass = "pass";
$db = "db";
$connect = mysql_connect($server, $user, $pass);
if ( ! $connect ){
echo mysql_error();
exit;
} else{
mysql_select_db("$db", $connect);
}
?>
Creates vars, if not $connect, show erros and exit. Else, select your db.
_
(scripttoregister).php
include('connect.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['user'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if (empty($fname) or empty($lname) or empty($email) or empty($username) or empty($password) or empty($cpassword){
echo "<script>alert('Please Fill Out Blank Fields')</script>";
exit();
} else{
$query= mysql_query("INSERT INTO form(fname, lname, email, username, password, cpassword) VALUES ('$fname','$lname','$email','$username','$password','$cpassword')");
echo "alert('Registered Successfully')";
}
?>
Like this^
You have no need to create another if to just show alert neither set NULL to id, it's auto_increment. (: now you can add any action if(something is empty){} and else{}.
_
OOOOR in case of self-page (your)
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['user'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if (empty($fname) or empty($lname) or empty($email) or empty($username) or empty($password) or empty($cpassword){
echo "<script>alert('Please Fill Out Blank Fields')</script>";
exit();
} else{
$query= mysql_query("INSERT INTO form(fname, lname, email, username, password, cpassword) VALUES ('$fname','$lname','$email','$username','$password','$cpassword')");
// Redirect to a page, 'n print the success message there. (as said John Bupit)
header("Location: page.php");
exit();
// echo "<script>alert('Registered Successfully')</script>";
}
}
i'm creating a simple login system, i has the passwords using sha256 and store a salt using a random number in the database. However when i try to log in, when it goes to compare the hashes it fails. Can anyone see why?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_database = "login";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");
$query = "SELECT password, salt FROM registered_users WHERE username='$username'";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{
echo 'false';
header('Location: index.php');
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
echo 'false';
header('Location: index.php');
}
else
{
echo 'true';
$_SESSION['username']=$row['username'];
}
session_write_close();
Heres how i hash my pass
// hash the password using sha256 a string of 64 characters
$hash = hash('sha256', $password);
// create the salt, random string of characters appened to hash
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
Heres how i insert my data
mysql_query("INSERT INTO registered_users(username, name, email, password,salt)VALUES('$username', '$name', '$email', '$hash', '$salt')");
header("location: index.php?remarks-success");
mysql_close($con);
?>
Make sure you are storing the password in the database the same way you are checking it here.
So to put it in you should create the hash by first hashing the password, then rehashing it with a salt. If they don't match, then there is your problem.
i am having some trouble with some script on my site.
i followed part of a tutorial as i liked the friend adding part but didn't want to change the whole site.
i used his code but obviously had to change some it to work on my site.
the idea is you visit someone else's profile and you can click to either block or send a friend request.
i am not sure where the issue is. i cant see any thing wrong in the php but is is possible i am missing something there as i am no expert, i am even less of an expert with javascript/ajax so this leads me to believe i have broken something in that.
here are my codes.
//Script on the profile.php page
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $username; ?>.");
if(conf != true){
return false;
}
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
_(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
_(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $id; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&id="+id);
}
//php script for the friend_system.php page
<?php
include_once("scripts/checkuserlog.php");
?>
<?php
if (isset($_POST['type']) && isset($_POST['id'])){
$id = preg_replace('#[^a-z0-9]#i', '', $_POST['id']);
$sql = "SELECT COUNT(id) FROM myMembers WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$exist_count = mysqli_fetch_row($query);
if($exist_count[0] < 1){
mysqli_close($db_conx);
echo "$username does not exist.";
exit();
}
if($_POST['type'] == "friend"){
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$id' AND blockee='$logOptions_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$logOptions_id' AND blockee='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count3 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count4 = mysqli_fetch_row($query);
if($blockcount1[0] > 0){
mysqli_close($db_conx);
echo "$user has you blocked, we cannot proceed.";
exit();
} else if($blockcount2[0] > 0){
mysqli_close($db_conx);
echo "You must first unblock $user in order to friend with them.";
exit();
} else if ($row_count1[0] > 0 || $row_count2[0] > 0) {
mysqli_close($db_conx);
echo "You are already friends with $user.";
exit();
} else if ($row_count3[0] > 0) {
mysqli_close($db_conx);
echo "You have a pending friend request already sent to $user.";
exit();
} else if ($row_count4[0] > 0) {
mysqli_close($db_conx);
echo "$user has requested to friend with you first. Check your friend requests.";
exit();
} else {
$sql = "INSERT INTO friends(user1, user2, datemade) VALUES('$logOptions_id','$id',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "friend_request_sent";
exit();
}
} else if($_POST['type'] == "unfriend"){
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
if ($row_count1[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else if ($row_count2[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else {
mysqli_close($db_conx);
echo "No friendship could be found between your account and $user, therefore we cannot unfriend you.";
exit();
}
}
}
?>
i have been looking at it now for a couple of days and am starting to not see the wood for the trees.
When i click on the request as fiend button, i get the dialog box fine, click ok and then it replaces the button with "please wait..." but that is where it stops. i have checked and nothing is being added to the database niether.
any help you could offer would be much apreciated.
thanks
I have provided an example of using jQuery to do this simply.
Here is what your button and response box would look like.
<div id="responsemessage<?php ///YOU USER ID FROM PHP// ?>" style="padding:2px; display:none;"></div>
<input name="" type="button" value="Friend Me" onClick="friendToggle('friend','<?php ///YOU USER ID FROM PHP// ?>')"/>
<input name="" type="button" value="Block Me" onClick="friendToggle('block','<?php ///YOU USER ID FROM PHP// ?>')"/>
This is what your jQuery function would look like. You will need to include the jQuery lib in your header.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>function friendToggle(type,user){
///This is the ajax request via jQuery///
$.ajax({
url: 'friend_system.php?action='+type+'&user='+user,
success: function(data) {
///This is where the response from you php is handled. Sky's the limit//
if(data == 'good'){
$("#responsemessage"+user).html('You now have a friend.');
}else{
$("#responsemessage"+user).html(data);
}
}});
}</script>
</head>
And here is the php to process the requests this would be in your friend_system.php
<?php
include('YOUR CONNECTION DETAILS FILE');
$act = $_REQUEST['action'];
if($act == 'friend'){
$a = mysql_query("SELECT * FROM friends WHERE user1 = '".$_REQUEST['user']."'");
if(mysql_num_rows($a) > 0){
echo 'You are already friends.';
}else{
mysql_query("INSERT INTO friends SET user1 = '".$_REQUEST['user']."', user2 = '', datemade = '".date('d-m-Y H:i')."'");
echo 'good';
}
}
if($act == 'block'){
mysql_query("INSERT INTO blockedusers SET blocker='YOUR ID HERE, HOPE ITS PASSED VIA SESSION' AND blockee='".$_REQUEST['user']."'");
echo 'You have blocked this user.';
}
?>
I hope this helps you... Also be sure to check out http://jquery.com/