I have a php mvc website that contain controller - model - view
How I can call a function in flutter.
fo example the login form of the website has:
controller function:
function checkuser()
{
$form= $_POST;
$error=$this->model->checkUser($form);
Model::sessionInit();
$userId=Model::sessionGet('userId');
if ($userId==false )
{
// header('location:'.URL.'login');
echo '<script>console.log("invalid username or password")</script>';
}
else
{
// header('location:'.URL.'userpanel');
echo '<script>console.log("successfull... you are in.")</script>';
}
if ($error !='')
{
echo '<script>console.log("there is some error")</script>';
// $data=['error'=>$error];
// $this->view('login/index',$data);
}
}
and the model is:
function checkUser($form)
{
#$email=$form['username'];
#$password=$form['password'];
#$remember=$form['remember'];
$error='';
$sql= "select * from tbl_users WHERE email=? and password=?";
$params=[$email,$password];
$result=$this->doSelect($sql,$params,1);
if (sizeof($result)>0 and !empty($email) and !empty($password))
{
Model::sessionInit();
Model::sessionSet('userId',$result['id']);
if ($remember=='on')
{
$expiry = time() + (86400 * 7);
setcookie('userIdc',$result['id'],$expiry,'/');
}
}
else {
$error='not found user.';
}
return $error;
}
the link of the controller will be /login/checkuser
I try to send request from flutter with http package but can not give a good result.
please help me about the structure of the code in flutter and how to send the data username and password to server and give feedback from there.
thanks so much.
best regards
try something like below
import 'package:http/http.dart' as http;
import 'dart:convert';
userLogin() async {
Map<String, String?> userData = {
'username': 'username',
'password': 'password'
};
http.Response response = await http.post(
Uri.parse('yourUrl'),
headers: {'youHeader'},
body: json.encode(userData),
);
String jsonStr = (response.body);
try {
final mapData = jsonDecode(jsonStr);
if (mapData is Map) {
// var loginSuccess = await(AfterLogin.updatesAfterLogin(mapData)); //do other stuffs
} else {
return false;
}
} catch (e, trace) {
debugPrint("error $e, ${trace.toString()}");
return false;
}
}
Related
I have login page in Xamarin forms app, the page send request to PHP file and check the username and password ,then response a message ,C# Code :
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using static JiyanUQuran.Models.appuser;
namespace JiyanUQuran.views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
}
private void Signin_Clicked(object sender, EventArgs e)
{
string user = username.Text;
string pass = password.Text;
Navigation.PushModalAsync(new MonthPage());
string response = SendRequest("xxx/api/xxx.php?username=" + user + "&password=" + pass);
if (response == "Welcome")
{
Navigation.PushModalAsync(new MonthPage());
}
else
{
message.Text = response;
}
}
private string SendRequest(string url)
{
try
{
using (WebClient client = new WebClient())
{
return client.DownloadString(new Uri(url));
}
}
catch (WebException)
{
return null;
}
}
}
}
the PHP page is like this :
<?php
$message = "Empty Field not Allowed";
include_once 'DbConnect.php';
$username = $_GET['username'];
$password = md5($_GET['password']);
$testuser = "SELECT * FROM users Where username = '$username'";
$testresult=mysqli_query($connection,$testuser);
$counttest = mysqli_num_rows($testresult);
if ($counttest == 0){
$rigister=mysqli_query($connection,"INSERT INTO users Values ('','$username','$password')");
}
else {
$user = "SELECT * FROM users Where username = '$username' and password = '$password'";
$result=mysqli_query($connection,$user);
$count = mysqli_num_rows($result);
if ($count == 0){
$message= "username or password is wrong";
}
else{
$message ="Welcome";
}
}
echo $message;
?>
When the username or password wrong I received the message correctly but i don't wan to navigate to other page ,but in all response it is navigate to next page ,how can i solve this?
There are two Navigation.PushModalAsync methods in your Signin_Clicked function, the first one will be called directly, the second one will be called when the response equals to "Welcome".
So your problem is caused by the first Navigation.PushModalAsync, remove it and choose whether to navigate to MonthPage by the response.
private void Signin_Clicked(object sender, EventArgs e)
{
string user = username.Text;
string pass = password.Text;
//remove this line
//Navigation.PushModalAsync(new MonthPage());
string response = SendRequest("xxx/api/xxx.php?username=" + user + "&password=" + pass);
if (response == "Welcome")
{
Navigation.PushModalAsync(new MonthPage());
}
else
{
message.Text = response;
}
}
Currently, we are building a project about website blocking and I just have a few questions about php and how phpmyadmin reacts to certain actions. I am using wampserver
signup.php apparently shows no errors when inputting a new account, the username and password is supposed to be saved in the database.
Here it is:
<?php
require_once ("functions.php");
require_once ('config.php');
require_once ('User.php');
require_once ('Session.php');
$default_label = 0;
$error = null;
if($session->isLoggedIn()){
redirectTo("home.php");
}
if(requestIsPost()) {
global $session;
$params = requiredPostParams(['username' , 'password' , 'label'] , $strict=true);
if($params != null){
$default_label = $params['label'];
// put the data into data base and redirect to login
$ouser = User::findByUsername($params['username']);
if($ouser == null) {
try{
$nuser = new User();
$nuser->initialize($params['username'] , $params['password'] , $params['label']);
$nuser->save();
// everything is set, train the recognizer
$faceLIb = new COM($LIB_CLSID);
$nextDir = $unused_face_dir."/s".(string) $default_label;
$nextDirDest = $face_dir."/s".(string) $default_label;
rename($nextDir , $nextDirDest); // move directory into usable faces
$faceLIb->train($face_dir , $rec_path);
redirectTo("login.php");
} catch (InvalidUserData $iud) {
$error = "Invalid user data. Try Again";
} catch (DBQueryException $dbe) {
$error = "Application Error. Try Again";
} catch (DBConnectException $dce) {
$error = "Application error. Try Again";
}
} else {
$error = "Email alredy registered";
}
}
}
?>
<html>
<head>
<title>Signup</title>
</head>
<body>
<?php if($error != null) echo $error; ?>
<form action="" method="post" id = "dataform">
Email: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="hidden" name="label" id = "label" value = <?php echo '"'.$default_label.'"'; ?> >
<input type="button" value="Submit" id="submit_form">
</form>
<!-- the video scanner -->
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480" style = "display:none"></canvas>
<h1 id="status"></h1>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script>
// test if the camera is available
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
// event handlers
$("#snap").on("click" , function(){
train = function(){
$.ajax({
type: "GET",
url: "train.php",
data: "{}",
dataType: 'json',
success: function(result){
console.log(result);
if(result.code == 1) {
$("#label").val(result.label);
$("#status").text("Succesful");
}
else alert("Face detection Failed! Try again");
}
});
}
// send an image to the server, on sucess call recursive. do it 'i' times
send_images = function(i){
if( i === 0 ) {
$("#status").text("submitting ...");
train();
return;
}
$("#status").text(i);
// extract an image from the live camera
context.drawImage(video, 0, 0, 640, 480);
var url = canvas.toDataURL('image/png');
$.ajax({
type: "POST",
url: "upload.php",
//dataType: 'jsonp',
data: {
"url" : url
},
success: function(result){
send_images(i-1);
}
});
}
$.ajax({
type: "GET",
url: "ready.php",
success: function(result){
console.log(result);
}
});
send_images(10);
});
$("#submit_form").on("click" , function(){
var label = parseInt($("#label").val());
if(label < 1) alert("User saved. Use Snap photo to train image.");
else $('form#dataform').submit();
});
</script>
</body>
</html>
<?php
require_once("config.php");
require_once("SQLTable.php");
require_once("Validator.php");
require_once("Texter.php");
require_once("exceptions.php");
class User extends SQLTable{
/**
* #Overridden properties
*/
protected static $tableName = 'users';
protected static $dbFields = array("id" , "name" , "password" , "label");
protected $id;
/**
* #type: SQL.varchar(64)
* Name of the user, should not contain anything other than alpha and whitespace
*/
protected $name; //TODO : TEST what happens while saving if some variable is not set
/**
* #type: SQL.varchar(64)
* Encrypted user password, Real Escaping is done after the encryption
*/
protected $password;
protected $label;
public function __construct(){
parent::__construct();
}
/**
* get functions
*/
public function getId(){
return $this->id;
}
public function getLabel(){
return $this->label;
}
/**
* Sets all the properties of object.
* Must call this function before calling save on this object, if not initialized by find* functions
*/
public function initialize($name=null , $password=null , $label= null){
if(Validator::isValidEmail($name)){
$this->name = $name;
}else {
throw new InvalidUserData("Username is not valid");
}
if(Validator::isValidPassword($password)){
$this->password = Texter::encryptPassword($password);
}else {
throw new InvalidUserData("Password is not valid");
}
$this->label = $label;
}
/**
* #Defination: Reset saved password
* */
public function setPassword($newPass) {
if(Validator::isValidPassword($newPass)){
$this->password = Texter::encryptPassword($newPass);
}else {
throw new InvalidUserData("Password is not valid");
}
return $this;
}
/**
* #Defination: Authenticate user by name and password
* #return: Object of this class if authenticated, null otherwise
*/
public static function authenticate($name = null , $password = null){
if(! Validator::isValidEmail($name) || ! Validator::isValidPassword($password))
return null;
$name = self::escapeValue($name);
/**TODO, find how right is next step ? */
$password = Texter::encryptPassword($password);
$password = self::escapeValue($password);
$sql = "SELECT * FROM ".static::$tableName;
$sql .= " WHERE name = '{$name}' AND ";
$sql .= "password = '{$password}' ";
$sql .= "LIMIT 1";
$resultSet = self::findBySQL($sql);
return !empty($resultSet) ? array_shift($resultSet) : null;
}
public static function findByUsername($name = null){
if(! Validator::isValidEmail($name)) return null;
$name = self::escapeValue($name);
$sql = "SELECT * FROM ".static::$tableName ." WHERE name='{$name}' LIMIT 1";
$resultSet = self::findBySQL($sql);
return !empty($resultSet) ? array_shift($resultSet) : null;
}
}
PS. I might need to upload other codes as well but I'm not sure what it is.
I assume it, config.php is your database file. If yes change the order of file to top and then try.
Below is my script in Dashboard module.
$(function()
{
var o;
$.get('dashboard/xhrgetInsert',function(o)
{
for(var i = 0;i <= o.length; i++)
{
$("#appendHere").append("<div>"+o[i].text+"</div>");
}
},'json');
$("#randomInsert").submit(function()
{
alert("hi");
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url,data,function(o)
{
$("#appendHere").append("<div>"+o+"</div>");
},'json');
return false;
});
});
Supposedly, when I'm in the dashboard page this function(xhrgetInsert) has to return value to be appended in the HTML. Unfortunately, it doesn't append anything and as I checked in the chrome console 'response'..it says method doesn't exist. But If I type the method name in the url, it shows the values returned in json format as I specified so.
Same goes for 'xhrInsert()' function as it doesn't return value to be appended. Database connection is perfect as it can insert and select data from db just unable get back the values..
I'm wondering first, why it says the method doesn't exist, and secondly why doesn't return any value?
My 'Dasboard controller making call to dashboard model'
public function xhrInsert()
{
$this->model->xhrInsert();
}
public function xhrgetInsert()
{
$this->model->xhrgetInsert();
}
Dashboard model contains mysql queries to the database whcih return values in jason format
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
echo json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
echo json_encode($data);
}
Finally, this is my HTML for dashboard
<h1>Dashboard</h1>
<form id="randomInsert" action="<?php echo URL;?>dashboard/xhrInsert" method="post">
<label>Text: </label><input type="text" name="text"/><br/>
<input type="submit"/>
</form>
<div id="appendHere"></div>
Console Screenshot
Function should return the result json data to ajax request so it won't render the whole html page with result.
public function xhrInsert(){
echo $this->model->xhrInsert();
die;
}
public function xhrgetInsert()
{
echo $this->model->xhrgetInsert();
die;
}
Model
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
return json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
return json_encode($data);
}
Im trying to use ajax to submit a form and return type either Business or Admin but I'm getting:
JSON.parse: unexpected end of data
result= JSON.parse(r);
<input type="text" id="signinemail" placeholder="Email" name="signinemail">
<input type="password" id="signinpassword" placeholder="Password"
name="signinpassword">
<script>
$(function() {
$("#signinsubmit").click(function() {
var username = $("#signinemail").val();
$.post("signin.php",
{
signinusername: username, signinpassword: $("#signinpassword").val()
} )
.done( function(r)
{
result= JSON.parse(r);
if(result["user_type"]=="Business")
{
window.location="profile.php";
}
else if(result["user_type"]=="Admin")
{
window.location="requestpage.php";
}
});
});
});
</script>
This is the class that trying to login in with. It firsts takes the post gives it to the authenticate function then returns the result of the connection to the log in function that encodes it
<?php
/**
* Logs the User into Website
*/
class Login
{
private $connection;
private $result_array = array();
private $user_type;
private $id;
public $username;
private $password;
public $loggedIn;
function __construct()
{
$this->username = $_POST['signinemail'];
$this->password = $_POST['signinpassword'];
$this->connection = new mysqli('WolfeboroC.db.10688096.hostedresource.com', 'WolfeboroC', 'Brewster#1', 'WolfeboroC');
$this->authenticate();
$this->logIn($this->authenticate);
}
private function authenticate()
{
$query = "SELECT recid, Admin FROM users
WHERE User = '".$this->$username."'
AND password='".$this->$password."'
AND (verified='y' OR admin = 'y')
LIMIT 1";
$stmt = mysqli_master_query($this->connection, $query);
$this->result_array = mysqli_fetch_array($stmt);
return !empty($this->result_array);
}
private function logIn()
{
if($result_array->num_rows > 0)
{
if($result_array['Admin']=='y')
{
$this->user_type = "Admin";
$this->admin($this->result_array);
$this->loggedIn = true;
}
else
{
$this->user_type = "Business";
$this->business($this->result_array);
$this->loggedIn = true;
}
echo json_encode($this->user_type['user_type']);
}
}
}
?>
echo json_encode($this->user_type['user_type']); is not correct. Your user_type is not an array so don't try to access it like this. You either do a echo $this->user_type and use the result as a string in javascript OR put the value in an array and then json_encode it like this:
echo json_encode(array('user_type' => $this->user_type));
Try using to get json response as,
result.user_type
instead of
result["user_type"]
In login() function: json synatx should be
echo json_encode(array('user_type' => $this->user_type));
instead of,
echo json_encode($this->user_type['user_type']);
I have library for xmpp transactions used jaxl libraries:
class xmpp{
public function register_user($username, $password){
require_once 'JAXL/jaxl.php';
$this->client = new JAXL(array(
'jid' => 'localhost',
'log_level' => JAXL_ERROR
));
$this->username = $username;
$this->password = $password;
$this->client->require_xep(array(
'0077' // InBand Registration
));
$thisClassObject =& $this;
$this->client->add_cb('on_stream_features', function($stanza) use(&$thisClassObject) {
$thisClassObject->client->xeps['0077']->get_form('localhost');
return array($thisClassObject, 'wait_for_register_form');
});
$this->client->start();
return;
}
public function wait_for_register_response($event, $args) {
if($event == 'end_stream') {
return;
}
else if($event == 'stanza_cb') {
$stanza = $args[0];
if($stanza->name == 'iq') {
if($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$this->client->end_stream();
return 'logged_out';
}
else if($stanza->attrs['type'] == 'error') {
$error = $stanza->exists('error');
echo "registration failed with error code: ".$error->attrs['code']." and type: ".$error->attrs['type'].PHP_EOL;
echo "error text: ".$error->exists('text')->text.PHP_EOL;
echo "shutting down...".PHP_EOL;
$this->client->end_stream();
return "logged_out";
}
}
}
}
public function wait_for_register_form($event, $args) {
$stanza = $args[0];
$query = $stanza->exists('query', NS_INBAND_REGISTER);
if($query) {
$form = array();
$instructions = $query->exists('instructions');
if($instructions) {
echo $instructions->text.PHP_EOL;
}
$this->client->xeps['0077']->set_form($stanza->attrs['from'], array('username' => $this->username, 'password' => $this->password));
return array($this, "wait_for_register_response");
}
else {
$this->client->end_stream();
return "logged_out";
}
}
}
these code are same as register_user.php, but implemented in a class;
i use this class in my code in this way:
$xmppObj = new xmpp();
$xmppObj('user','password');
/*
some more code after this
/*
when it execute , create user successfully but it's print a message ('registration successful ...') and application exited and it doesn't execute "some code after this" after the class function, in the other word it doesn't follow the code...
What can I do for solve this problem, a person can help me that familiar with JAXL library.
Looks like you are pretty much using the same code as found inside examples/register_user.php. Once user registration is successful, script closes XMPPStream as evident from this section of the code:
if($stanza->attrs['type'] == 'result') {
echo "registration successful".PHP_EOL."shutting down...".PHP_EOL;
$this->client->end_stream();
return 'logged_out';
}
You MUST instead call $client->send_end_stream(); and not $client->end_stream();. This will make sure underlying XMPPStream makes proper FSM state transition. Also add a callback for on_disconnect event, inside this callback you can again try to connect back with newly registered XMPP account and it should just work fine.
Note: Kindly checkout latest code from the repository. I made some updates which will allow core JAXLLoop to be re-initialized. If you are interested in details, here is the commit log.