Logged in user throughout your site - PHP API

I was trying to find an "easy" way to log in a user and use their information through a website with the Knack database. I was able to workout this code using PHP/AJAX and I hope this will help future developers to implement the same features quickly.

For jquery AJAX lessons: http://www.w3schools.com/jquery/jquery_ref_ajax.asp

For PHP POST lessons: http://php.net/manual/en/reserved.variables.post.php

(many more sites/forums to learn this but these are simple to start).

--

To make this work you need to use "$_SESSION['VAR_NAME'] and attach the POST fields to form/login values (basic html form is good here). I used standard jquery AJAX calls to a PHP page that had the code below, returning the desired results. After the user submits their email and password the PHP POST will verify they're a registered user and return the ID, Token, Email, Status, Full Name, etc. Once returned you can link each of these to a "$_SESSION['VAR_NAME']" which will follow them throughout your site. At any point you can include these sessions in API calls to your database to filter records connected to this specific user (each time the user visits the site they will need to login again to generate working sessions).

For instructions on how to code

Here is my code:

<?php

session_start

();

accessuserArray </span><span>=</span><span> array</span><span>(</span><span> </span><span>'email'</span><span> </span><span>=&gt;</span><span> _POST

[‘your_html_form_email_value’],
‘password’ => $_POST[‘your_html_form_password_value’]
);

$accessuserData

= json_encode($accessuserArray);

$ch

= curl_init();
curl_setopt
($ch, CURLOPT_URL, https://api.knackhq.com/v1/applications/XXXAPP-IDXXX/session);
curl_setopt
($ch, CURLOPT_CUSTOMREQUEST, ‘POST’);
curl_setopt
($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt
($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt
($ch, CURLOPT_POSTFIELDS, $accessuserData);
curl_setopt
($ch, CURLOPT_HTTPHEADER, array(“Content-Type: application/json”));
$returnVal
= json_decode(curl_exec(ch</span><span>));</span><span> _SESSION[“userId”] = returnVal</span><span>-&gt;</span><span>session</span><span>-&gt;</span><span>user</span><span>-&gt;</span><span>id</span><span>;</span><span> _SESSION[“userNameFirst”] = returnVal</span><span>-&gt;</span><span>session</span><span>-&gt;</span><span>user</span><span>-&gt;</span><span>values</span><span>-&gt;</span><span>field_66</span><span>-&gt;</span><span>first</span><span>;</span><span> _SESSION[“userNameLast”] = returnVal</span><span>-&gt;</span><span>session</span><span>-&gt;</span><span>user</span><span>-&gt;</span><span>values</span><span>-&gt;</span><span>field_66</span><span>-&gt;</span><span>last</span><span>;</span><span> _SESSION[“userEmail”] = $returnVal->session->user->values->field_67->email;

curl_close

($ch); ?>