I want to assign a value as 0 by default, then every time that page is hit
I want to increase the value by one and when the value is 4 then I have to do some action on that page and change back the value of that variable to 0.
I want to you use global variables or application variables.
I don't want to use the database to save values. I tried my best to save the value in .env but read somewhere it's not the right way to do. Please guide me the best possible way? Working on Laravel 5.3
Thank you very much.
You can create a file in the config folder and store the option there. For example, in a file named system.php:
<?php
return [
"my_option" => 0,
];
Then you can have access to it calling get method from Config:
$myOption = \Config::get('system.my_option');
More info: https://laravel.com/docs/5.2/configuration
You can use session for this:
$counter = (int) session('counter', 0);
session(['error_pages' => ++$counter]);
if ($counter >= 4) {
// here you do what you want
}
Of course in case you want to use this mechanism not in single user session you can use cookies to store counter value.
You can use the config function, is less overhead than use the session:
config(['shared_variable'=>$value])
Related
I have cookie date stored in a serialized array which I would like to access via the Blade template.
If a cookie value is set matching the current field name, then I want to show it. I am currently using the following code, but I'm not sure how to access the array value.
{{{ Cookie::has('myBookingDetails') ? Cookie::get('myBookingDetails') : old('name') }}}
The value of the myBookingDetails cookie looks like this:
a:4:{s:4:"name";s:13:"Joe Bloggs";s:5:"email";s:29:"joe#domain.co.uk";s:5:"phone";s:11:"0777777777";s:3:"reg";s:6:"123456";}
How can I access the "name" value via Blade?
The data is serialized. You need to use unserialize() function to get the data.
$data = unserialize(Cookie::get('myBookingDetails'));
$name = $data['name']
Check for existence before use.
Don't know if previous answer solved your enigma, but I could give some help.
I fought with a similar case. Seems that in template - in laravel 5.1 - I couldn't access directly to cookies:
Cookie::get('cookiename') simply returns null
cookie('cookiename') returns a Symfony\Component\HttpFoundation\Cookie, but $cookie->getValue() returns (again) null.
The good old $_COOKIE['cookiename'] returns the right cookie, so you could simply go with unserialize( $_COOKIE['myBookingDetails'] )['name']; !
PS: It should be better to handle with cookies in controller and pass a normal variable to the view!
I have created a web app that has 2 control panels. One for the admin and one for the users. I want the users to be able to perform one specific action from their panel only if the admin sets this action "on" (from his panel) and not being able when he sets it "off".
My app also uses a MySql database.
How can I implement it? Is an extra table with only one field a viable solution? Can I do it by reading a file (maybe JSON)?
EDIT: I want the admin to be able to toggle the "on/off" status with a click of a button, so constants are not a solution.
A database query could be used every time the action is used but if it is more general and you are going to be using this a lot, I would look into PHP constants. You could set it in a configuration file like:
Config.php
define('USER_CAN_MODIFY', true);
Other.php
if ((defined('USER_CAN_MODIFY') and USER_CAN_MODIFY === true) { }
Constants have a global scope and cannot be changed once set.
Since you want to store a single value you don't need to use DB. You may simply store this flag in a file as serialized value.
Below is simplified example.
define('PERM_FLAG_FILE', 'perm_flag.dat');
$PERM_FLAG = false;
function loadFlag() {
global $PERM_FLAG;
return file_exists(PERM_FLAG_FILE)? unserialize(file_get_contents($PERM_FLAG)) : false;
}
function saveFlag() {
global $PERM_FLAG;
file_put_contents(PERM_FLAG_FILE, serialize($PERM_FLAG));
}
function setFlag($v) {
global $PERM_FLAG;
$PERM_FLAG = (bool)$v;
}
Please have a look at the following:
foreach($a_Header['Details'] as $i_Detail => &$a_Detail)
{
echo "{$a_Detail['VEH_TREAD_OFF']}\n";
// Make a back-up of the value
$BAK_TREAD_OFF = $a_Detail['VEH_TREAD_OFF'];
// Copy some data from the saved header
foreach(array
(
'POD_QTYORD',
'VEH_TREAD_OFF',
'RPM_SCRM_FIXEDPRICE',
'RPM_TRM_FIXEDPRICE',
'RPM_TRM_COSTPERMM',
'RPM_CTS_CASINGCOST',
'CHARGE_DESC',
'Hide',
) as $s_Column)
{
$a_Header['Details'][$i_Detail][$s_Column] = $a_SavedHeader['Details'][$i_Detail][$s_Column];
}
echo "{$a_Detail['VEH_TREAD_OFF']}\n";
// Now restore our value
$a_Detail['VEH_TREAD_OFF'] = $BAK_TREAD_OFF;
}
You can see that prior to entering the for loop, I have backed up a value which I restore after.
This is because for some reason it is being lost during the loop.
I'm not a PHP guru by any stretch, but this is confusing me no end, as I can't see why modifying one variable would affect another, unless there are wormholes in PHP!
Can someone tell me why this might be happening?
Thanks
$i_Detail => &$a_Detail
Now $a_Detail is a reference to $a_Header['Details'][$i_Detail]. both variables refer to a single value. Do not use & if you do not want that.
Your code sample does not affect $a_detail at all. Are you sure, this is the only reference to this variable? Do you use something like extract()?
I am trying to do a variable_set() when clicking 'Reset default values' on my module's admin page form. This runs through system_settings_form_submit(). The #default_value inside my form is reset, but my module relies on this stored variable to display some data. Clicking reset fills in the form with the default, but does not 'Save' it to recreate the variable in the database, so my module's function breaks. It appears that nothing happens after clicking Reset, other than it deleting the variable from the database. Thanks in advance.
My submit function looks like this:
function faculty_submit(&$form, &$form_state){
if($form_state['values']['op'] == 'Reset to defaults') {
global $faculty_detail_template_default;
variable_set('faculty_detail_template', $faculty_detail_template_default);
}
elseif ($form_state['values']['op'] == 'Save configuration') {
// Clear caches for list and detail pages.
cache_clear_all('faculty_list', 'cache', TRUE);
cache_clear_all('faculty_detail_load', 'cache', TRUE);
}
}
First of all that's what system_settings_form_submit does when you press the Reset to defaults button. It calls variable_del which will delete all your defined variables in the form from the variables table.
Now your form's #default value is probably filled because you do something like this:
global $faculty_detail_template_default;
$form = array (
'#default_value' => variable_get('faculty_detail_template', $faculty_detail_template_default),
);
I don't see why you insist of adding a default value in the variables table. This entire approach is flawed. Just use variable_get($name, $default) wherever your code depends on faculty_detail_template. That's precisely what the second parameter of this function is used for: $default The default value to use if this variable has never been set. So for Drupal, the absence of a variable from the variable table means it's up to the coder how to handle this case (provide a default for example). Default value which is specified using variable_get.
Second, if you used system_settings_form then you already have a submit function, the one mentioned above (system_settings_form_submit) so your faculty_submit won't be called unless you add it specifically to the array of submit callbacks to be executed. Something like this:
$form['#submit'][] = 'faculty_submit';
return system_settings_form($form);
BTW, using global variables is a bad idea (in general) and you should try to avoid using them. That's what variables are used for :) Pieces of information which can be retrieved in different parts of the code. So instead add a .install file to your module and in that file you define these global variables using variable_set. This is a lot cleaner than just magically popping some global variables in the middle of the code.
you need to use &$form_state['values']['yourVariableNameOfForm'] instead of what I have made bold below.
variable_set('faculty_detail_template', $faculty_detail_template_default);
I have a page "bottom1.php" it has 16 select menus, labled rating1-rating16.
When the user submits this form, the next page has a script that looks like this:
//pulling data from post into array.
import_request_variables("p", "form_");
$scores= array($form_rating1,$form_rating2,$form_rating3,$form_rating4,$form_rating5,$form_rating6,$form_rating7,$form_rating8,$form_rating9,$form_rating10,$form_rating11,$form_rating12,$form_rating13,$form_rating14,$form_rating15,$form_rating16);
//putting array into session
$_SESSION['scores']=$scores;
the user is then directed to another page where an additional 16 selections are made, then the same script is ran, only this time the array is stored into the session as "scores2".
The user is shown the output from each array, and then when the user confirms that the values are correct, each member of the scores, and scores2 array is parsed out, put into another variable, and then inserted into a database.
I know this is a primitive way of accomplishing this, but its the only way I know how.
This method worked with php configuration of 5.2.13, but I switched to a server with a configuration of 5.1.6 and now this script wont work. This script is critical to my site. Thanks for your help!
The parsing script looks like this:
$fpage=$_SESSION['scores'];
$spage=$_SESSION['scores2'];
$score1 = $fpage['0'];
$score2 = $fpage['1'];
$score3 = $fpage['2'];
$score4 = $fpage['3'];
$score5 = $fpage['4'];
...
$score31 =$spage['13'];
$score32 =$spage['14'];
$score33 =$spage['15'];
And then I insert $score1 - $score33 into my db..
The way you are doing it isn't exactly safe, for the same reason register_globals() is/was a bad idea. If you happen to prefix one of your internal variables with 'form_', the user could overwrite that value and potentially inject harmful code (depending on how that variable is used).
A better way to do this would be to filter the array directly into a new array using array_filter() or preg_grep().
Oliver A.'s solution only works in the scenario that all of the array keys will be in the form of 'form_rating', but your original script assumed a prefix of 'form_'.
preg_grep could be used as follows:
$keys = preg_grep('/^form_/', array_keys($_POST));
$scores = array();
foreach ($keys as $key) {
$scores[$key] = $_POST[$key];
}
I do not have a php enviroment to test this right now but this should work:
$scores = array();
for($i=1;array_key_exists("form_rating{$i}",$_POST);$i++){
$scores[] = $_POST["form_rating{$i}"];
}
EDIT: I tested and working
If the script does not work when PHP changes version then:
Check the logs to see the errors
Check the PHP Changelog for any function or control structure change that my halt your script.
Just an issue that it happen to me a lot when switching between 5.1 and 5.2 is the Elvis operator ?: which is not recognized in php 5.1.
This is why is important to develop on the same kind of configuration that the server has, or to implement unit-testing and automatic deployments which can detect this problems before reaching production.