I want to save order keys in cookies then loop through them.
Firstly I save The order key (which is a random generated key) in a cookie:
saveorderInCookie($OrderKey);
echo $OrderKey;
Save Order Function :
function saveorderInCookie($orderKey)
{
setcookie($orderKey,$orderKey,time()+10000000);
echo '<br>current cookie: '.$_COOKIE[$orderKey];
}
OutPut:
current cookie: e8c5a1587e6de0cfd653ef0adadc9e88
The Echo Gives me a correct result.
But when I try to access it again:
function getPreviousOrders()
{
$counter=0;
for(reset($_COOKIE);$element = key($_COOKIE);next($_COOKIE))
{
$previousOrders[$counter]=$_COOKIE[$element];
$counter++;
}
return $previousOrders;
}
This will gives me another string.
which is always this : i3v90f0nhnactvmgjot4m8lmse1.
Related
Please i'm working on a quiz web app, i'm getting my data randomly from database and i'm saving it in a session array. now i want to check if the id of the retrieved data is in the session array if it is i want to generate a new value if is not in i want to push it to the array i have searched but not being able to figure it out any help will be appreciated thanks in advance.
This is what i did initially but the session exist is always returning true since i'm using same key;
function random()
{
$output=DB::table('questions')->inRandomOrder()->first();
return $output;
}
function checkRandomvalue($stored){
if(session()->exists('question'))
{
random();
}
session()->push('question',$stored);
}
do{
$r=random();
$result=checkRandomvalue($r);
}
while($result);
And this is what i did now checkRandomvalue function but this $question=session('question.0.id',[]); is returning null making the index to be always false
function checkRandomvalue($stored){
$id=$stored->id;
$question=session('question.0.id',[]);
$index=array_search($id,$question);
//dd($index);
if($index==true)
{
random();
}
$question[]=$id;
session()->put('question',$id);
}
I finally solved my problem should incase anybody encounters same problem, i declared 2 session in the constructor one to store array and the second to hold session value not in the array so i can query my database with it
public function __construct()
{
$this->middleware('auth');
$val=[12];
$rand=$val[0];
Session::put('keys',$val);
$value=session('keys');
Session::put('Key2',$rand);
$v_random=session('Key2');
}
then this is method for my logic
function random()
{
$output=DB::table('questions')->inRandomOrder()->first();
return $output;
}
function checkRandomvalue($stored){
global $value;
global $v_random;
$id=$stored->id;
$value=session('keys');
if(array_search($id,$value,true)==true) {
return;
}else if(array_search($id,$value,true)==false){
Session::push('keys',$id);
session()->save();
$value=session('keys');
Session::put('Key2',$id);
//$v_random=session('Key2');
//dd("good", $id, $value);
//dd(session($key));;
}
}
do{
$r=random();
$result=checkRandomvalue($r);
}
while($result);
$v_random=session('Key2');
$output=DB::table('questions')->where('id',$v_random)->get();
I have an HTML page which is has one user input and one button. After clicking on the button, we can fetch other data related to that user from oracle database. i have defined my code in a seperate php page( index2.php ) which looks like below:-
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$userid =$_POST["userid"];
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$userid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
echo json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I am doing this using asynchronous post method my defining a javascript file(script.js)
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
var userid = $("#userid").val();
//$.post("index2.php", {"userid" : userid})
var posting = $.post( 'index2.php', {"userid" : userid});
posting.done(function( res ) {
var response = $.parseJSON(res);
$('#rawResponse').text(response);
});
});
})
I have many data for one user. And output display looks like:
03-SEP-18,softOtpCheck,OTP check passed,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,oamAuth,OAM context cookie collected.,03-SEP-18,softOtpCheck,OTP check passed,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,oamAuth,OAM context cookie collected.
But i want it as :
03-SEP-18,softOtpCheck,OTP check passed,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,oamAuth,OAM context cookie collected.,
03-SEP-18,softOtpCheck,OTP check passed,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,oamAuth,OAM context cookie collected.
How can i display my output in a newline?
I believe you want to change
$('#rawResponse').text(response);
to
$('#rawResponse').html('<pre>' + JSON.stringify(response, null, 2) + '</pre>);
See JSON.stringify and the enclosing pre tags will display the return value nicely.
Alternatively you could also put it into a textarea, it will also display the newlines properly.
If you want to echo the json data, you can returns prettified data with newline characters using JSON_PRETTY_PRINT
echo json_encode($json_array, JSON_PRETTY_PRINT);
I am having some issues with sessions.
In the first function queue, I save the session entries I can print this out from this function, so I can see its being set correctly.
In the function remove, I try and save this entries session into a variable and I get the error that entries is an undefined index.
Does anyone have any ideas what I am doing wrong here?
function queue()
{
session_start();
$status = 'Awaiting Moderation';
$channel = '1';
// Find all entries in 'Gallery' channel with 'Awaiting Moderation' status
$this->EE->db->select('entry_id')
->from('exp_channel_titles')
->where('status', $status)
->where('channel_id', $channel);
$query = $this->EE->db->get();
$entries = $query->result_array();
$entries_count = count($entries);
// Set count
$_SESSION['entries_count'] = $entries_count;
// If entries found
if ($entries_count > 0)
{
// Flatten entry ids array
$entriesFlat = array();
array_walk_recursive($entries, function($a) use (&$entriesFlat) { $entriesFlat[] = $a; });
$entriesSerial = serialize($entriesFlat);
// Save in session
$_SESSION['entries'] = $entriesSerial;
}
}
function remove()
{
session_start();
// Get session data + save into variable
$entries = $_SESSION['entries'];
}
You can only have one session and it should be at the top of your file.
Since your using codeigniter why not use codeigniter session and then autoload library and then you can do code like below.
$this->session->set_userdata('entries_count', $entries_count);
To Get Data
$this->session->userdata('entries_count');
And
$this->session->set_userdata('entries', $entriesSerial);
To Get Data
$this->session->userdata('entries');
// Example
if ($this->session->userdata('entries') > 0)
{
User Guide
CI2 http://www.codeigniter.com/userguide2/libraries/sessions.html
CI3: http://www.codeigniter.com/user_guide/libraries/sessions.html
http://www.codeigniter.com/docs
1st of all, there's not need to declare 'session' again at 'remove()' function..
2ndly to set session contents you have to write :
$this->session->set_userdata('entries_count', $entries_count);
Instead of
$_SESSION['entries'] = $entriesSerial;
Save it in session
To get session contents you've to write:
$entries_count = $this->session->userdata('entries_count');
Get session data + save into variable
Then you can write the condition like:
if ($entries_count > 0) {
}
Similarly, you've to write
$this->session->set_userdata('entries', $entriesSerial);
To save in session instead of
$_SESSION['entries'] = $entriesSerial;
And
$entries = $this->session->userdata('entries');
To Get session data + save into variable
I'm verifying a form input and making sure the user doesn't submit the form twice. I'm doing this with the following class:
<?php
//You can of course choose any name for your class or integrate it in something like a functions or base class
class formKey
{
//Here we store the generated form key
private $formKey;
//Here we store the old form key (more info at step 4)
private $old_formKey;
//The constructor stores the form key (if one excists) in our class variable
function __construct()
{
//We need the previous key so we store it
if(isset($_SESSION['form_key']))
{
$this->old_formKey = $_SESSION['form_key'];
}
}
//Function to generate the form key
private function generateKey()
{
//Get the IP-address of the user
$ip = $_SERVER['REMOTE_ADDR'];
//We use mt_rand() instead of rand() because it is better for generating random numbers.
//We use 'true' to get a longer string.
//See http://www.php.net/mt_rand for a precise description of the function and more examples.
$uniqid = uniqid(mt_rand(), true);
//Return the hash
return md5($ip . $uniqid);
}
//Function to output the form key
public function outputKey()
{
//Generate the key and store it inside the class
$this->formKey = $this->generateKey();
//Store the form key in the session
$_SESSION['form_key'] = $this->formKey;
//Output the form key
echo "<input type='hidden' name='form_key' id='form_key' value='".$this->formKey."' />";
}
//Function that validated the form key POST data
public function validate()
{
//We use the old formKey and not the new generated version
if($_POST['form_key'] == $this->old_formKey)
{
//The key is valid, return true.
unset($_SESSION['form_key']);
return true;
}
else
{
//The key is invalid, return false.
return false;
}
}
}
?>
This is output to the form like this then:
include STYLESHEETPATH . '/formkey.class.php';
$formKey = new formKey();
$formKey->outputKey();
If I echo out the old_formKey and the post form_key they are the exact same and it works in every browser other than Safari. If I check these in Safari, the old_formKey is always different. Why would this be?
I use this class (taken from a blog tutorial) to generate unique keys to validate a form:
class formKey {
//Here we store the generated form key
private $formKey;
//Here we store the old form key
private $old_formKey;
//The constructor stores the form key (if one excists) in our class variable
function __construct() {
//We need the previous key so we store it
if(isset($_SESSION['form_key'])) {
$this->old_formKey = $_SESSION['form_key'];
}
}
//Function to generate the form key
private function generateKey() {
//Get the IP-address of the user
$ip = $_SERVER['REMOTE_ADDR'];
//We use mt_rand() instead of rand() because it is better for generating random numbers.
//We use 'true' to get a longer string.
$uniqid = uniqid(mt_rand(), true);
//Return the hash
return md5($ip . $uniqid);
}
//Function to output the form key
public function outputKey() {
//Generate the key and store it inside the class
$this->formKey = $this->generateKey();
//Store the form key in the session
$_SESSION['form_key'] = $this->formKey;
//Output the form key
// echo "<input type='hidden' name='form_key' id='form_key' value='".$this->formKey."' />";
return $this->formKey;
}
//Function that validated the form key POST data
public function validate() {
//We use the old formKey and not the new generated version
if($_POST['form_key'] == $this->old_formKey) {
//The key is valid, return true.
return true;
}
else {
//The key is invalid, return false.
return false;
}
}
}
Everything in my website goes through index.php first, so I put this in index.php: $formKey = new formKey();
Then, in every form I put this: <?php $formKey->outputKey(); ?>
That generates this: <input type="hidden" name="form_key" id="form_key" value="7bd8496ea1518e1850c24cf2de8ded23" />
Then I can simply check for if(!isset($_POST['form_key']) || !$formKey->validate())
I have two problems. First: I cant use more than one form per page becouse only the last key generated will validate.
Second: Because everything goes through index.php first, if I use ajax to validate the form, the first time will validate but the second time not, because index.php generates a new key but the pages containing the form does't refresh so the form key is not updated..
I have tried several things but I cant get it to work.. Maybe YOU can update/modify the code/class to get it to work?? Thanks!!!
You could put this into a class, but this is needless complexity. Simple security systems are best because they are easier to audit.
//Put this in a header file
session_start();
if(!$_SESSION['xsrf_token']){
//Not the best but this should be enough entropy
$_SESSION['xsrf_token']=uniqid(mt_rand(),true);
}
//$_REQUEST is used because you might need it for a GET or POST request.
function validate_xsrf(){
return $_SESSION['xsrf_token']==$_REQUEST['xsrf_token'] && $_SESSION['xsrf_token'];
}
//End of header file.
The extra && $_SESSION['xsrf_token'] makes sure this variable is populated. Its there to make sure the implementation fails securely. (Like if you forgot the header file doah! ;)
This following html/php goes in any file you want to protect from XSRF, make sure you have the code above in a header file.
if(validate_xsrf()){
//do somthing with $_POST
}
This is all you need to print out the form, again make sure you call session_start(); before you do anything, it doesn't matter if you call it multiple times.
<input type="hidden" name="xsrf_token" id="form_key" value="<?=$_SESSION['xsrf_token']?>" />
Not tested, but it should work.
class formKey {
//Here we store the generated form key
private $formKey;
//Here we store the old form key
private $old_formKey;
//The constructor stores the form key (if one excists) in our class variable
function __construct() {
//We need the previous key so we store it
if(isset($_SESSION['form_key'])) {
$this->old_formKey = $_SESSION['form_key'];
$this->formKey = $this->generateKey();
$_SESSION['form_key'] = $this->formKey;
}
}
//Function to generate the form key
private function generateKey() {
//Get the IP-address of the user
$ip = $_SERVER['REMOTE_ADDR'];
//We use mt_rand() instead of rand() because it is better for generating random numbers.
//We use 'true' to get a longer string.
$uniqid = uniqid(mt_rand(), true);
//Return the hash
return md5($ip . $uniqid);
}
//Function to output the form key
public function outputKey() {
return $this->formKey;
}
//Function that validated the form key POST data
public function validate() {
//We use the old formKey and not the new generated version
if($_POST['form_key'] == $this->old_formKey) {
//The key is valid, return true.
return true;
}
else {
//The key is invalid, return false.
return false;
}
}
}
Edit: changed back to single key. Just call outputkey() to when needed. Don't create more than one instance of this class.