Send Data From html5 app to database by ajax and php - ajax

i have start a new application html5 and i need to send from that app the info user_points to the database i have the code that send a fixed amount points.
But Now I need to change the php code to receive ajax request to update is points on database From My html5 app.
what i can change to this php code to receive the ajax variable user_points and store in database?
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
// Retrieve data from database
$result=mysql_query($sql);
//$sql = mysql_query("UPDATE `users` SET points=`points`+5 WHERE user_id='".$_SESSION['user']."'");
$user_id = mysql_real_escape_string($_SESSION['user']);
$sql = mysql_query("UPDATE `users` SET user_points = user_points +'user_points' WHERE user_id = " . $_SESSION['user']);
// close MySQL connection
mysql_close();
?>

assume your php script is called run.php
and assume run.php is called via ajax like this http://yourserver/run.php?user_points=10&userid=12&sessiontan=8162836zqwizß182402834080oio
your script run.php would need to look like this:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_GET['userid']) and isset($_GET['user_points'] and isset($_GET['sessionpin']))) {
$res=mysql_query("SELECT userid FROM sessiontans WHERE user_id=x".dechex($_GET['userid'])" and sessiontan=x".dechex($_GET['sessiontan']));
if($row = mysql_fetch_array($res)) {
$sql = mysql_query("UPDATE `users` SET user_points = user_points + x".dechex($_GET['user_points'])." WHERE user_id = x" . dechex($_GET['userid']));
}
}
// close MySQL connection
mysql_close();
?>
As far as I am aware the session context is not available in ajax called scripts. So security wise that needs to 'simulated' via sessiontans or similar mechanisms. I assumed now, you would follow a sessiontan approach. A session tan be created in your app as soon as the user logs and is via time stamps only valid for a tiny time frame (a couple of minutes/hours). A sessiontan would need to be different from session-IDs.
I personally would add more sophisticated checks on the user-points to make sure that the those are not tricked... Anyway that is more on the 'game logic' side and would require a lot more insight on what this is all about.
Also in terms of performance tuning both statements could become part of a multi query: http://php.net/manual/de/mysqli.multi-query.php
Again this is advanced programming tactics and superexceeds the scope of your question.

Related

How do I allow a 3rd party (twilio) access to current user account in laravel

I am making an application using laravel and twilio that gets feedback about student performance. The logic as follows.
A user, in my case the Student(called resident) logs in and uses a
web page form to send an eval request to a teacher (called
attending). This step starts a session and saves teacher info and
student info.
A random question is picked from a database and saved to the session.
The phone number of the teacher is pulled from a database and the random question is pulled from session and sent to the teacher on SMS using twilio.
The teacher responds with yes, no, or DNS (did not see) via Twilio SMS.
The teacher's response along with the student name, the teacher name and the question asked are saved to a database.
My application works up until step 5. The problem is that a new session is being started when the teacher responds via SMS. So everything after the response is saved to a new session. I can't get access to the original session. I think I need a way to automatically grant the teacher access to the student(ie. user's account). This seems to be a problem with it being a 3rd party application. Can this be done or is there another way to accomplish this?
Below is the code I am using for the response. It is not able to access the session that contains the residentName, the firstQuestion, or the attending_name data. It puts null for those values and uploads null to the database. How do I get access to the initial session in this situation?
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Session;
use Twilio\Rest\Client;
use Twilio\Twiml;
use App\Question;
use App\Answer;
class AskFirstQuestionsController extends Controller
{
public function qOneResponse(Request $request) {
$responderNumber = $request->input('From');
session()->put('responderNumber', $responderNumber);
session()->save();
$responderAnswer = strtolower($request->input('Body'));
$residentName = session::get('residentName');
$firstQuestion = session::get('first_question');
$attending_name = session::get('attending_name');
if (strpos($responderAnswer, 'yes') !== false) {
$answer = new
Answer(['attending'=>$attending_name,'resident_name'=>$residentName,'question_body'
=>$firstQuestion, 'answer_yes'=>1]);
$answer->save();
$smsResponse = "Great! Please help us reinforce this action by providing specific feedback
to the resident about what they did. Thank You for teaching!";
} else if (strpos($responderAnswer, 'no') !== false) {
$answer = new
answer::create(['attending'=>$attending_name,'resident_name'=>$resident_name,'question_body'
=>$firstQuestion, 'answer_no'=>1]);
$answer->save();
$smsResponse = "Ugh, ok...we will work on this. If you feel comfortable, please help us by
providing specific feedback to the resident about what they need to work on. Thank You for
teaching!";
} else if (strpos($responderAnswer, 'dns') !== false) {
$answer = new
answer::create(['attending'=>$attending_name,'resident_name'=>$resident_name,'question_body'
=>$firstQuestion, 'answer_dns'=>1]);
$answer->save();
$smsResponse = "How about trying a different question?";
} else {
$smsResponse = 'Please answer yes, no or dns.';
}
return response($this->respond($smsResponse))->header('Content-Type', 'application/xml');
}
public function respond($smsResponse) {
//get responderNumber and use it below
$responderNumber = session::get('responderNumber');
$response = new Twiml();
$response->message($smsResponse, ['to' => $responderNumber]);
return $response;
}
Do I need to do some type of multiauth approach and somehow grant the teacher automatic access to the student's account (user account)? Or do I have to re-write the logic so that the response-request lifecycle closes and then try to write to the database (maybe it will then use the original session data?)? Or is there a simpler way? Please help. I have been stuck for more than a week.
Twilio developer evangelist here.
I'm not a Laravel developer, but session objects in web application frameworks like this are normally tied to a cookie that either stores the contents of the session or an ID for the session which points to the contents in a database in order to add state to a user's session within a browser.
When Twilio receives an incoming SMS message the webhook that is sent to your server is not connected to the browser session that the user is part of, so you cannot access the same data.
Instead of using the session, you should store this as part of your actual database so that you can look up the details from the database when you receive the SMS.

Save complete model in session - Codeigniter

I want to save complete model in session, so I can use data easily in entire application.
After successful login in application I am saving model in session and session save in database in ci_session table.
Code I tried:
$loginSuccess = $this->login_model->doLogin($username, $password);
if($loginSuccess) {
$this->login_model->initialize(); // this will set value in private variable
$serializelogin = serialize($this->login_model);
$this->session->set_userdata('userprofile', $serializelogin);
}
This code gives me an error:
Error Number: 2006
MySQL server has gone away
Update: I change user_data column of table ci_session from text to longtext
U need to start by creating a session.
//Destroy old session
$this->session->sess_destroy();
//Create a fresh, brand new session
$this->session->sess_create();
//Set session data
$this->session->set_userdata($row);
Basically $row is an array.
$row = $serializelogin->row_array();
or
$this->session->set_userdata(array('active_flag' => false, 'active_status' => 0));
make sure the data which has been returned from the model is in row_array format.

How to Check if Session is set in Laravel 5.7

<?php
$request = request();
// if (empty($request)) return false; .// That does not work
$loggedUserAccessGroups = $request->session()->get('loggedUserAccessGroups');
$logged_user_ip = $request->session()->get('logged_user_ip');
In my Laravel 5.7 application, I want to check if the user has the right access level in the session. It works ok but I made automatic tests and got the error:
local.ERROR: Session store not set on request.
I added checks to see if the session is set and it fails to return false.
Which is the correct way? Thanks!
You may also use the global session PHP function to retrieve and store data in the session as outlined here:
// Retrieve a piece of data from the session with the global session helper...
$loggedUserAccessGroups = session('loggedUserAccessGroups');
$logged_user_ip = session('logged_user_ip');
// Store a piece of data in the session...
session(['key' => 'value']);
For more information look at the section of The Global Session Helper in the official documentation.

symfony 3 time when log in and log out

I'm pretty much new in symfony 3, so how I could get time when user log in and log out.. I know i should create entity for time.. that entity would have id,userID startTime, endTime.. and user should have a connection(many to many, that lot of user could have lot of log in.. ) with this entity.... I'd like to store in database this information. I tried to search on google but I found nothing in common.
I'd like to activate time startTime when this button is pressed
Sign
in
and code in controller
#Route("/login", name="authentication_login")
public function loginActionAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('AppBundle:uzduotis:login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
then for endTime
/**
* #Route("/logout", name="logout")
* #Method({"GET"})
*/
public function logoutAction(Request $request)
{
$session = $this->$request->getSession();
$session = $this->get('session')->clear();
return $this->render('AppBundle:uzduotis:login.html.twig');
}
For this answer I assume you store the users in the database. If not, please show how you do it.
First of all please have a look at the doctrine documentation on how to connect entities to each other. In your case this should help:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional
There's also a pretty good tutorial on this subject in the Symfony documentation: http://symfony.com/doc/current/doctrine/associations.html
In the controller you can fetch the currently logged in user by executing $user = $this->get('security.token_storage')->getToken()->getUser();. That will return the database entity of the user that you can modify immediately. E.g. by adding a new record to the time table (example code):
$time = new TimeLog();
$time->setUser($user);
$time->setType('login');
$time->setTimestamp(time());
In case saving does not work, try with the persist and flush methods of $this->get('doctrine')->getManager(). There's lots of documentation about this, too.

select the right database according to input login field

I have 3 login fields (name, pass, company id). Now when user clicks "Log me in" button CI should select and work with database according to company id (and check user in this database and when he is logged in, work with this database over whole session /each company has its own database/).
How can I do this?
I found this but it looks like it is not the right solution.
Many thanks
CodeIgniter: Connection to your Database
Maybe the link above will help you out.
You have to set a new db connection for the specific company. In CodeIgniter it is really simple.
Combine it with THIS PROBLEM to get access to the database settings setted in the database-config.
Example:
<?php
$config = array();
$config['hostname'] = $this->db->hostname;
$config['username'] = $this->db->username;
$config['password'] = $this->db->password;
$config['database'] = 'companydb';
$config['dbdriver'] = $this->db->dbdriver;
$companydb = $this->load->database($config);
$companydb->query('SELECT ... FROM ... WHERE ...');
?>

Resources