So basically my question is simple.
Imagine situation when you a making a login or register form. With jquery.post i make ajax call
$.post( "pages/form_handle.php", name: $.(".username").val(), pass: $.(".pass").val() , function( data ) {
$( ".result" ).html( data );
});
it's simple call(i belive so)...
How to make it secure?
So if user look in my source code he or she know where i send my data in example pages/form_handle.php also he or she know what data i send to this page.
One of idea what i have simple send all ajax calls to one page ajax.php adding extra variables who will call right php function for ajax call...
But does it is the right way? Or maybe there is some better way to make it secure?
Stick to basics, and keep salting your passwords.
AJAX is not server side language, its a javascript plugin that does the same thing as forms, actions, etc... just in background as a new request.
Your ajax is not in danger, but your php files are, you can use jquery-validate.js to check on users input, but also you should make validation check in your ajax.php.
Here is a simple ajax login request:
function loginUser() {
var process = "loginUser";
var data = $("form").serializeArray();
data[1].value = data[1].value; // data to ajax.php page
data = JSON.stringify(data);
$("#loginButton").html('Login');
$.ajax({
type: "POST",
url: "ajax.php",
data: {"process": process, "data": data},
success: function(data) {
if (data.response.state == "success") {
// if ajax.php returns success, redirect to homepage or whatever
} else {
// if ajax.php returns failure, display error
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
// error handling
},
dataType: "json"
});
}
And the simple ajax.php login:
<?php // ajax.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])){
$un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username='$un_temp'";
$result = mysql_query($query);
if (!$result) die("Database access failed: " . mysql_error());
elseif (mysql_num_rows($result)){
$row = mysql_fetch_row($result);
$salt1 = "qm&h*";
$salt2 = "pg!#";
$token = md5("$salt1$pw_temp$salt2");
if ($token == $row[3]) echo "$row[0] $row[1] :
Hi $row[0], you are now logged in as '$row[2]'";
else die("Invalid username/password combination");
} else die("Invalid username/password combination");
}else{
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function mysql_entities_fix_string($string){
return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string){
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
?>
Related
I'm submitting a form using MySQL command inside a PHP file. I'm able to insert the data without any problem.
However, I also, at the same time, want to display the user a "Thank you message" on the same page so that he/she knows that the data has been successfully registered. On the other hand I could also display a sorry message in case of any error.
Therein lies my problem. I've written some lines in Javascript to display the message in the same page. However, I'm stuck on what (and how) should I check for success and failure.
I'm attaching my code below.
Can you please help me on this with your ideas?
Thanks
AB
HTML Form tag:
<form id="info-form" method="POST" action="form-submit.php">
form-submit.php:
<?php
require("database-connect.php");
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
return false;
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
submit-logic.js:
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
if(e.target === document.getElementById("info-form"))
{
$.ajax(
{
type:this.method,
url:this.action,
data: $('#info-form').serialize(),
dataType: 'json',
success: function(response)
{
console.log(response);
if(response.result == 'true')
{
document.getElementById("thankyou_info").style.display = "inline";
$('#please_wait_info').hide();
document.getElementById("info-form").reset();
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
$('#please_wait_info').hide();
}
}
}
)};
});
}
Per documentation: http://api.jquery.com/jquery.ajax/
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
You are explicitly setting this to json but then returning a string. You should be returning json like you are telling the ajax script to expect.
<?php
require("database-connect.php");
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die(json_encode(array('result' => false, 'message' => 'Could not enter data: ' . mysql_error()));
}
echo json_encode(array('result' => true, 'message' => 'Entered data successfully'));
mysql_close($conn);
?>
I also added code to sanitize your strings, although mysql_* is deprecated and it would be better to upgrade to mysqli or PDO. Without sanitization, users can hack your database..
Nevertheless, returning json properly will ensure that your response in success: function(response) is an object, and response.result will be returned as expected, and you can use response.message to display the message where you want.
I need one help session store using PHP and Angular.js . i have one login app.When user will logged in successfully the session will store and when user will redirect to next page the session data will be fetched.I am explaining my code below.
login.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_pass=$request->user_pass;
$connect = mysql_connect("localhost", "root", "*****");
mysql_select_db('go_fasto', $connect);
$selquery = "SELECT * FROM db_Admin_Master WHERE user_name='".$user_name."' and password='".$user_pass."'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0){
$result=mysql_fetch_array($selres);
$_SESSION["user_name"]=
$_SESSION["user_type"]=
$_SESSION["email_id"]=
$result['msg'] = 'Login successfull...';
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = 'You entered wrong username/password';
}
echo json_encode($result);
?>
In this page i need to set up the session data(i.e-user_name,email_id,user_type).The user will redirect to the next page after successful login and the controller file of that redirected page is given below.
dashboardController.js:
var dashboard=angular.module('Channabasavashwara');
dashboard.controller('dashboardController',function($scope,$http){
$http({
method: 'GET',
url: 'php/Login/session.php',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
})
In this page the user will get the respective session data inside success function and if session data is not present some message will return to error call back function.Please help me.
I think you need to create one separate function for that.
For example
$selquery = "SELECT * FROM db_Admin_Master WHERE user_name='".$user_name."'
and password='".$user_pass."'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0){
$result=mysql_fetch_array($selres);
getSession($result);
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = 'You entered wrong username/password';
}
/*May be in separate function file.*/
function getSession($result){
if (! isset ( $_SESSION )) {
session_start ();
}
if( isset($result['user_id'])){ //or Whatever
// Declare your session and return variable
}
}
And call getSesson() function wherever you need to check session.
<?php
$con = mysqli_connect("localhost", "root", "", "" ) or die("Neuspjelo spajanje");
function InsertUser(){ global $con;
if(isset($_POST['sign_up'])){
$name = mysqli_real_escape_string($con, $_POST['u_name']);
$pass = mysqli_real_escape_string($con,$_POST['u_pass']);
$email = mysqli_real_escape_string($con,$_POST['u_email']);
$country = mysqli_real_escape_string($con,$_POST['u_country']);
$gender = mysqli_real_escape_string($con,$_POST['u_gender']);
$b_day = mysqli_real_escape_string($con,$_POST['u_birthday']);
$date = date("m-d-Y");
$status = "unverified";
$posts = "No";
$get_email = "select * from users where user_email='$email'";
$run_email = mysqli_query($con, $get_email);
$check = mysqli_num_rows($run_email);
$insert = "insert into users (user_name, user_pass, user_email, user_country, user_gender, user_b_day,
user_image, register_date, last_login, status, posts) values
('$name','$pass', '$email', '$country', '$gender', '$b_day', 'default.jpg',
'$date', '$date', '$status', '$posts')";
$run_insert = mysqli_query($con, $insert);
$result = mysql_query($insert);
if($result){
echo "<script>alert ('You're successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}
}
}
?>
You can't echo javascript and run it in a page that's already loaded. This would need to be the result of an ajax call on the client side with your redirects occuring from your ajax callbacks.
If you're ok with ditching the alert, you can just issue a redirect from php:
header('Location: home.php');
To do it ajaxy:
$.ajax({
type: "GET",
url: "your_insert_user.php"
}).success(function(xhr) {
alert ("You're successfully registered!");
window.open('home.php', '_self');
}).fail(function (jqXHR, status, errorThrown) {
//something else here
});
But, why would you want to issue an ajax call just to redirect?
Additionally, you need to issue the appropriate responses from your insert script:
if ($result) { echo ""; } //issues a "200 OK"
else { header("HTTP/1.1 422 Unprocessable Entity"); } //fires the failure callback in ajax
I would pass a conditional GET or POST paramater to home.php with some value flag and display your message there.
Based on what you post above, you are dealing with two separate issues here.
You say "it inserts" so I'm assuming that means that the mysql query to insert the new row into your database completes successfully. Then you send some HTML code, containing a (somewhat mangled) Javascript snippet, to the browser, which is supposed to issue a redirect request to the client's web browser, which doesn't have the desired result, seeing as you write that it "won't redirect".
Keep in mind that redirection is performed by the browser, is dependent on the browser's capabilities and/or settings, and requires proper javascript in the first place.
How do properly request a redirect from the browser has been discussed before on SO.
First of all,remove this line $result = mysql_query($insert); then modify your code and add this, hope it will work:
$run_insert = mysqli_query($con, $insert);
if($run_insert){
echo "<script>alert ('You\'re successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}
I have a problem, how can i select data from my database (Microsoft SQL Server) from my javascript by an AJAX request.
I know I need a "server language", but it seems that PHP cannot do this !
How can I do ?
Thank you !
PHP is a server side language. Drivers are created for thee PHP package that allow them to interface with several different types of database architecture systems. In this case, the SQL Server would be connected to through the sqlsrv drivers for PHP.
A simple query to the database looks like the following:
-- query.php --
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Person";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$name = sqlsrv_get_field( $stmt, 0);
echo $name; //maybe the name is "George"
This establishes the connection, and then attempts to query the database. As we're just retrieving one row, we use sqlsrv_fetch() to attempt to populate the $stmt variable. If it works, then we'll get $name as a return from the row at column with index 0. This will return the value of $name to the success function of our ajax call (as illustrated below)
The $.ajax() is simple. Figure out what element is going to fire the ajax call, then just do it..
$('element').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'query.php',
type: 'GET',
success: function(data){
console.log(data); //will show George in the console
//otherwise it will show sql_srv errors.
}
});
});
Resources
sqlsrv_connect()
sqlsrv_query()
$.ajax()
For connecting to SQL Server... You can use this code...
public function connect() {
$dsn = "Driver={SQL Server};Server=xxxxx;Port=1433;Database=yyyy";
$data_source='zzzz';
$user='dbadmin';
$password='password';
// Connect to the data source and get a handle for that connection.
$conn=odbc_connect($dsn,$user,$password);
if (!$conn) {
if (phpversion() < '4.0')
{
exit("Connection Failed: . $php_errormsg" );
}
else
{
exit("Connection Failed:" . odbc_errormsg() );
}
}
return $conn;
}
Please note, here I have created a data source. This code is using ODBC as you can see. ;)
And this connection is using Sql Authentication.
Hope this helps...
Asp.net
Client Side Code
$.ajax({
url: "ViewData.aspx/GetTransitNameById",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"Transitid":"' + id + '"}',
success: function (result) {
// You got the required data in result.d
var finalresult = result.d;
}
});
Server Side Code
[WebMethod]
public static string GetTransitNameById(int Transitid)
{
string name = "";
try
{
oohMonitoringManager om = new oohMonitoringManager();
name = om.GetTransitNameByTransitId(Transitid);
// here you got what you needed.
// name contains the data that you have to return back to the javascript ajax function
}
catch (Exception a1)
{ }
return name;
}
Im trying to do a recover password system with jQuery messages and Im having a problem.
The code below is working fine, when I click in the button to recover my username and password I get the message <p class="sucess">Email sent with your data..</p>.
But I want to put the email of the user in the message. Like this:
<p class="sucess">Email sent with your data for email#example.com!</p>
Im trying like this in my php
else {
echo 'sucess'; //here I show the jQuery message
echo $result['email']; //and then I want to show my $result['email']
return;
}
I already try like this:
echo 'sucess'.$result['email'].'';
But I have always the same problem, Im entering here in my jQuery:
else
{
alert('Error in system');
}
And if I dont put this echo in $result['email'] the sucess message works fine, but when I try to echo my $result['email'] Im always entering in this jQuery condition.
Somebody there have any idea why this is happening?
My php:
switch ($action){
case 'recover':
$email = $_POST['email'];
if($email == ''){
echo 'errorempty';
}else{
$searchEmail = $pdo->prepare("SELECT * FROM admins WHERE email=:email");
$searchEmail->bindValue(":email", $email);
$searchEmail->execute();
$num_rows = $searchEmail->rowCount();
$result = $searchEmail->fetch(PDO::FETCH_ASSOC);
if($num_rows <=0 )
{
echo 'erroremail';
return;
}
else {
echo 'sucess';
echo $result['email'];
return;
}
}
break;
default:
echo 'Error';
}
}
My jQuery:
$('#recover').submit(function(){
var login = $(this).serialize() + '&action=recover';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer== 'erroempty'){
$('.msg').empty().html('<p class="warning">Inform your email!</p>').fadeIn('slow');
}
else if (answer == 'erroemail'){
$('.msg').empty().html('<p class="error">Email dont exist!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
$('.msg').empty().html('<p class="sucess">Email sent with your data..</p>').fadeIn('slow');
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
you can simple echo the $email like this
$email=$result["email"];
echo $email;
then in ajax success function
if(answer.email)
{
$('.msg').empty().html('<p class="sucess">Email sent with your data..'+answer.email+'</p>').fadeIn('slow');
}
The problem is, that you server side is returning just unstructured data and the client side part will just receive a plain string like sucessdummy#example.com in the answer variable.
This answer variable is compared with strings that do not match thought your script ends in the error case. I would go for a solution by returning some kind of structured data like json.
Your server side code could look something like
$result = array('msg'=>'success','mail'=>$result['email']);
header('Content-type: application/json');
echo json_encode($result);
You have to pass the dataType:'json' option in your jquery ajax call to make it work and can access the data in the call back function like answer.msg, answer.mail