I wanted to create a forgot password page. To avoid mailing the user with his details, I decided to display his details in an alert box, although I know that it is much less secure!
So, here's my code in the php file "forgotdetails.php".
//Here are my database details, which I can't show.
$conn= mysql_connect($dbhost, $dbuser, $dbpass);
// Check connection
if(!$conn){
die('Could not connect'.mysql_error() );
}
$db_selected = mysql_select_db('users');
if(!$db_selected){
die('wrong'.mysql_error() );
}
$post_username = $_POST['email']; // the ajax post username
$query = "SELECT * FROM users WHERE id='". $post_username. "'";
$results= mysql_query($query);
$row=mysql_fetch_assoc($results);
$username=$row['id'];
$password=$row['pass'];
if(mysql_num_rows($results)==0)
{
echo "pass= " . $password;
echo "You haven't registered yet! Go to the Home-Page to Register!";
/*$query = "SELECT * FROM users WHERE id='$post_username' AND pass='$post_password'";*/
}
else
{
echo $password;
echo "Your Login details are-:"."\nUser ID- ". $username . "\nPassword- ". $password . "\nLogin to your account, to change your password. ";
}
And here's my ajax function (inside the html file) which is getting called as the forgot password button is clicked-:
<script lang="javascript" type="text/javascript">
function ajaxFunction1() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function ()
{ if (ajaxRequest.readyState == 4)
{ var ajaxDisplay = document.getElementById('results');
alert (ajaxRequest.responseText);
ajaxDisplay.innerHTML = "<br/><br/><h2><font color='#18E618'>"+ajaxRequest.responseText+"</font></h2>"; } }
// Now get the value from user and pass it to
// server script.
var email = document.getElementById('email').value;
//var bitsmailid = document.getElementById('bitsmailid').value;
if ( email== "" || email== null || email== '') {
alert("BITS ID Not Filled");
exit();
}
/*if ( bitsmailid== "" || bitsmailid== null || bitsmailid== '') {
alert("BITS Mail ID Not Filled");
exit();
}*/
var queryString = "?email=" + email;
ajaxRequest.open("POST", "forgotdetails.php" +queryString, true);
ajaxRequest.send(null);
}
</script>
My query is that, the I need to check whether the query returned through SQL in the PHP File ($results) is empty or not and then I need to perform the functions as i have mentioned in my code. I have used mysql_num_rows($results)==0 condition (which I got to know after reading similar posts on Stack Overflow). Although it doesn't seems to evaluate correctly. It evaluates true always, even though there are entries in the database.
I have read all the posts concerning this type of questions on Stack Overflow, and after 12+ hours of testing the code with many different possibilities, still I am still unable to solve my query. I have provided all the details necessary for my query, however If anyone needs anything, I will provide them with you.
I am a newbie into Web Development, so please help me to solve my query. Thank You in advance for your Help!
I am sorry if you feel that this question has already been answered earlier, however I posted this again because those posts sadly couldn't help me. I have read all of them. Sorry!
It should be
$sql = "SELECT * FROM users WHERE id='". $post_username. "'";
$result = mysql_query($sql, $conn);
if ($result && (mysql_num_rows($result) > 0)) {
// user exists
// here you get row
$row = mysql_fetch_assoc($result);
}
I know it is without pdo and it is insecure.
Related
I have a PHP login script that I want to execute with ajax. The PHP script takes the user to a page if successful but according to the ajax request I am using, the header location also loads in the $('.logresult') div how do I do it such that it goes to the header location when successful and shows the error in the $('logresult') if not. Below are my codes:
Ajax Request
$('#submit_log').click(function(e) {
e.preventDefault();
var data = $('#loginForm').serialize(),
form = $('#loginForm');
$.post($(form).attr("action"), data, function(data) {
$('.logresult').html(data);
})
});
PHP Login Script
session_start();
require_once ("db.php");
$db = new MyDB();
if(isset($_POST['log_name']) && isset($_POST['log_password'])) {
$username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['log_name']);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['log_password']);
$sql = $db->prepare("SELECT * FROM users WHERE uname = ?");
$sql->bindParam(1, $username, SQLITE3_TEXT);
$ret = $sql->execute();
$count = $db->prepare("SELECT COUNT(*) as COUNT FROM users WHERE uname = ?");
$count->bindParam(1, $password, SQLITE3_TEXT);
$count_ret = $count->execute();
if (count($count_ret) == 1)
{
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$id = $row['userid'];
$regas = $row['regas'];
$uemail = $row['uemail'];
$pword = $row['pword'];
if (password_verify($password, $pword))
{
$_SESSION['log_id'] = $id;
$_SESSION['log_name'] = $username;
$_SESSION['regas'] = $regas;
$_SESSION['uemail'] = $uemail;
header("Location: index.php?log_id=$id");
exit();
}
else
{
echo "Information incorrect";
exit();
}
}
}
}
I am guessing the issue is $('.logresult').html(data); but don't really know how to fix this (am new to ajax generally). Thanks
simply don't use ajax if you want to change the location. ajax usage is mostly when you don't want a page reload. in most cases ajax response is a json and handle the response with javascript.
If you want to change the location of the page after success, it is doable via your ajax, I do it all the time. It is also not unusual to have a site use ajax and redirect on success, I have seen it a lot. In your php, instead of doing:
header("Location: index.php?log_id=$id");
exit();
To keep it simple to work with your existing script, you can send back javascript:
die("<script>window.location='http://www.example.com/index.php?log_id={$id}';</script>");
If I were to redo what you have, I would receive json instead in the form of actions/instructions from the PHP and have the javascript in the success interpret the instructions, but that is more complex.
I'm a beginner of PHP coding which I face this problem and I tried to fix it.
I have search through stackoverflow for answers but it stills no good.
This is my Login form.php file
<form name = 'LoginForm' method = 'POST' action = 'verifyUser.php'>
<br />
E-MAIL: <input type = "Textbox" Name = "App_Email"><br><br>
PASSWORD: <input type = "password" Name = "App_Password"><br><br>
<input type = 'Submit' name = 'Login' value = 'Log in'><br><br>
</form>
This form will goes to verifyUser.php and these are codes
include ('DBconnect.php');
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if($username=='' || $pass=='') {
header("Location:login.php?id=Some fields are empty");
}
$result = mysql_query("SELECT * FROM applicant_acct ");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if ($username==$row['App_Email']) {
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.html?id=$username");
} else {
header("Location:login.php?id=username or your password is incorrect. Please try again");
}
}
}
And final DBconnect.php
<?
$dbc = mysql_connect('localhost','root','root') OR die('Wrong Connection!!!!!!!');
mysql_select_db('onlinerecruitment') OR die ('Cannot connect to DB.');
?>
I really have no idea why it shows "Query Failed: No database selected"
I think the problem is in verifyUser.php but have no idea where.
And another thing, after I logged in how can I generate the text "Welcome - "Username"" and provide them the logout button?
Please help.
Thank you.
Generally you may want to research a graphical user interface such as XAMPP or MySQL workbench until you are more comfortable with Database systems.
Here it seems like most of the improvements can be made in you DBConnect.php file. You are beginning and I can appreciate that. Consider something along the following lines that incorporates additional the security of PDO:: static calls.
<?php
public function _dbconnect($hostpath, $database, $username, $password){
try {
$this->conn = new PDO("mysql:host = {$hostpath};
dbname - {$database};
charset = utf8",
$username,
$password);
} else { exit(); }
?>
If this particular code block doesn't help I would highly recommend that you continue by investigating PDO:: calls.
<?php
include ('DBconnect.php');
if(isset($_POST['Login'])){
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if(empty($username) || empty($pass) || ctype_space($username) || ctype_space($pass)){
header("Location:login.php?error=1");
} else {
$result = mysql_query("SELECT * FROM applicant_acct");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.php?id=$username");
} else {
header("Location:login.php?error=0");
}
}
?>
I have a lot to say about your code.
Use isset function . This function check if something was done.
Check your database details again. Maybe you wrote something
wrong (misclick or something)
Use $_GET['error'] to get errors. I set 1 = for empty characters and 0 for 0 match between database and inputs.
Use sessions for after login message. You can also use Session to handle your errors.
EDIT: I recommend you to start to learn MySQLi or PDO.
I have sent two pieces of data to my PHP with this bit of AJAX:
function ajax_post(){
// Create our XMLHttpRequest object
var request = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "php/addUser.php";
var username = document.getElementById("newUserName").value;
var password = document.getElementById("newUserPass").value;
var newUsername = "user_name="+username;
var newPassword="password="+password;
request.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
document.getElementById("output").innerHTML = return_data;
}
};
// Send the data to PHP now... and wait for response to update the status div
request.send({newUsername,newPassword}); // Actually execute the request
This is the PHP code that is supposed to take these two pieces of data and plug it into my mysql database.
//Connect to the database
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
$userName=$_POST['newUsername'];
$userPassword=$_POST['newPassword'];
$query="INSERT INTO users(user_name,password)
VALUES('$userName','$userPassword')";
if ($connection->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $connection->error;
}
$connection->close();
When the AJAX is run, it runs with no errors and sends the data to my PHP code on my server. The PHP code then runs and completes with no errors but then when I check my database the new user is inserted into the database but it is empty. I'm pretty sure it's something in my PHP code, but I haven't figured it out yet.
The argument to request.send() should be a URL-encoded string, not an object.
request.send(newUsername + '&' + newPassword);
Note that you should also use encodeURIComponent when setting the variables, in case they contain special URL characters.
var newUsername = "user_name=" + encodeURIComponent(username);
var newPassword = "password=" + encodeURIComponent(password);
Also, your object syntax was incorrect. The syntax for objects is
{ prop1: value1, prop2: value2, ... }
{ var1, var2 } should have given you a syntax error.
You're also using the wrong $_POST keys. The keys should match the parameter names before =, not the IDs of the form fields.
$userName = $_POST['user_name'];
$userPassword = $_POST['password'];
You should also use a prepared statement in the PHP instead of variable substitution, to prevent SQL injection problems.
$query = "INSERT INTO users (user_name, password) VALUES (?, ?)";
$stmt = $connection->prepare("ss", $userName, $userPassword);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $stmt->error;
}
$connection->close();
You post user_name and password with ajax. But in your PHP code you used $_POST['newUsername'] and $_POST['newPassword']. You can change either the ajax or PHP.
Example:
$userName = $_POST['user_name'];
$userPassword=$_POST['password'];
And your request from ajax should be
request.send(newUsername+"&"+newPassword);
Following code is from a login page. I want to update the image of user when user fill username onkeyup. Image path is to get through PHP. Script code is given below:
function showUserPic(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// document.getElementById("img").innerHTML=xmlhttp.responseText;
x = document.getElementById("img");
x.src = 'users/'+xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
HTML Code is given below:
<input type="text" class="inputLabel1" style="margin:5px;" name="userText" onkeyup="showUserPic(this.value)" />
PHP file code is given below:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$user = intval($_GET['q']);
$conn = mysqli_connect("localhost","root","","pharmacy");
if (!$conn) {
die('Could not connect: ' . mysqli_error($con));
}
$query = "SELECT * FROM users WHERE username = '$user';";
$result = mysqli_query($conn, $query);
$userdata = mysqli_fetch_array($result);
mysqli_close($conn);
echo $userdata['image'];
?>
</body>
</html>
First of all a suggestion: $query = "SELECT * FROM users WHERE username = '$user';";is better to be $query = "SELECT image FROM users WHERE username = '$user';"; since there is no need to return all the columns from the table.
Then you should consider turning to PDO instead of deprecated mysql and mysqli extentions.
Then your issue is here:
$userdata = mysqli_fetch_array($result);
mysqli_close($conn);
echo $userdata['image'];
$userdata is an array. So you can't just echo it. You should consider to do:
foreach($userdata as $temp){
echo $temp['image'];
}
And also, as others are saying remove all the leading html from your php file and just echo image name.
As #dan-klasson stated - you need to return from server only image path. Your HTML and JS can stay AS-IS, but you need to change your PHP markup to just:
<?php
$user = intval($_GET['q']);
$conn = mysqli_connect("localhost","root","","pharmacy");
if (!$conn) {
die('Could not connect: ' . mysqli_error($con));
}
$query = "SELECT * FROM users WHERE username = '$user';";
$result = mysqli_query($conn, $query);
$userdata = mysqli_fetch_array($result);
mysqli_close($conn);
echo $userdata['image'];
?>
Your actual code are returning:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
example_image.jpg
</body>
</html>
and your script are inserting all of this into your image tag, so it will be:
<img src="users/%3C!DOCTYPE%20html%3E%0A%20%20%20%20%3Chtml%3E%0A%20%20%20%20%3Chead%3E%0A%20%20%20%20%3C%2Fhead%3E%0A%20%20%20%20%3Cbody%3E%0A%20%20%20%20example_image.jpg%0A%20%20%20%20%3C%2Fbody%3E%0A%20%20%20%20%3C%2Fhtml%3E"/>
It's probably not what you want :) Just change your PHP code.
EDIT:
One additional mistake in your code is that you have intval on your request parameter (which tries to be username):
$user = intval($_GET['q']);
Change it to:
$user = $_GET['q'];
You are passing username as string but getting variable using intval(). This will not work.
Print your response with this line of JS:
console.log(xmlhttp.responseText);
Or you can also inspect your image tag <img src="" /> with firebug and confirm whether you are getting the correct image name. If all is fine, check the file permissions of the user image folder and also the user image.
I do not have any other option, but to ask here again... and problem is killing me for the past 5 hours. I got button that call javascript function, and then javascript opens another php page and does insert in MySQL database.
HTML code:
<ul>
<li id="ConfirmButton" name="Insert" onclick="GetAllIDs()"><a>Potvrdi</a></li>
</ul>
Javascript code:
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
http.open('get', 'insert.php?MatchID='+MatchID+'&TipID='+TipID+'&UserID=' + 1,true);
http.send(null);
PHP code:
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$userID = $_GET['UserID'];
// Escape User Input to help prevent SQL Injection
$MatchID = mysql_real_escape_string($matchID);
$TipID = mysql_real_escape_string($tipID);
$UserID = mysql_real_escape_string($userID);
$insertTicket_sql = "INSERT INTO
betslips(DateTime,MatchID,TipID,UserID)
VALUES(".$MatchID.",".$TipID.",'".date("Y-m-d H:i:s")."',".$UserID.")";
$insertTick= mysql_query($insertTicket_sql) or die(mysql_error());
So after I run this code and I use break point I see in my php code all parameters I sent over forms normally and it's all there, but when I reach code $insertTick I get error
web server exited unexpectedly, restarting new instance.
Has anyone seen this problem before, and how can I deal with it?
Thanks
did anyone seen this problem before?
Not me, I dont use the mysql_* functions.
Your INSERT query parameter and values dont match.
So ive ported your example code to PDO perhaps its some interest:
<?php
//PDO Connect
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=yourDB','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
//Check that the variables are set
if(isset($_GET['MatchID']) && isset($_GET['TipID']) && isset($_GET['UserID'])){
//Prepare your query
$query = $con->prepare("INSERT INTO betslips (DateTime,MatchID,TipID,UserID)
VALUES ('".date("Y-m-d H:i:s")."', :matchID, :tipID, :userID)");
//Bind your values with the placeholders
$query->bindParam(":matchID", $_GET['MatchID']);
$query->bindParam(":tipID", $_GET['TipID']);
$query->bindParam(":userID", $_GET['UserID']);
//Execute
$query->execute();
die('Success!');
}else{
die('Error: Parameter not set.');
}
?>