Flash messages with sessions in PHP - php

I work on a project in PHP which does not use any kind of a framework for PHP. I come from Yii background and I've used:
Yii::app()->user->setFlash('flash_name', 'Flash value');
And checked it with:
Yii::app()->user->hasFlash('flash_name');
To check if it is present and if it exists, and to get the value of it I used:
Yii::app()->user->getFlash('flash_name', 'Default Flash value');
For now, I wrote these functions to set, check and get flash:
function set_flash($flash_name, $value) {
$_SESSION['flashes'][$flash_name] = $value;
}
function has_flash($flash_name) {
return isset($_SESSION['flashes'][$flash_name]) ? true : false;
}
function get_flash($flash_name, $default_value = null) {
if(has_flash($flash_name)) {
return $_SESSION['flashes'][$flash_name];
}
return $default_value;
}
However, when I use it in my post.php like this:
set_flash('success', true);
And check it in my index.php like this:
<div class="container">
<?php if(has_flash('success') && (get_flash('success') === true)): ?>
<div class="alert alert-success">
<h4>Success!</h4>
<hr />
<p>You have successfully posted new content on your website. Now you can edit or delete this post.</p>
</div>
<?php endif; ?>
</div>
whenever I refresh the page, the message would still appear there.
How can I remove the flash after it's been used or invoked?

Add a new line to get_flash:
function get_flash($flash_name, $default_value = null) {
if(has_flash($flash_name)) {
$retVal = $_SESSION['flashes'][$flash_name];
// don't unset before you get the vaue
unset($_SESSION['flashes'][$flash_name]);
return $retVal;
}
return $default_value;
}

Related

Creating a website in PhpStorm and I'm having trouble checking a database variable

I have two functions, one to check whether a user is logged in, and another to check if the user is an admin. I also have a User database with one column named user_lvl, which displays fine if I output all the user data.
The problem I'm having is that with the admin function it doesn't seem read anything.
Here is the two functions code:
define('USER_LEVEL_ADMIN', '1');
// check whether a user session is active, return true if yes, else return no
function isLoggedIn() {
if (isset($_SESSION['userId'])) {
return true;
}
else {
return false;
}
}
// check whether user has required user level to access admin privileges, return true if yes
function isAdmin() {
// check if a user is in a session, then check if the users user_lvl is equal to 'USER_LEVEL_ADMIN
if (isset($_SESSION['userId']) && $_SESSION['userId'] && USER_LEVEL_ADMIN == $_SESSION['userId']['user_Lvl']) {
return true;
}
else { // works if you reverse true and false, else this is broke
return false;
}
}
And here is where it is being called:
<?php if (isLoggedIn() ) : ?>
<?php if (isAdmin() ) : ?>
<div>
Admin Panel
</div>
<?php endif; ?>
<div>
My Account
</div>
<?php endif; ?>
It displays 'My Account' but not 'Admin Panel'. Any help is much appreciated.
This code snippet is ment for testing and identify which function is gives this output
<?php
function isLoggedIn() {
return true;
}
function isAdmin() {
return false; // change it to true to see Admin Panel. You need to check the condition in this function.
}
if (isLoggedIn() ) :
if (isAdmin() ) :
echo '
<div>
Admin Panel
</div>';
endif;
echo '
<div>
My Account
</div>';
endif;
?>
The isAdmin() condition looks fine, You may echo out the session variable and crosscheck.
One of the 3 checks in the if statement is failing (returning false):
isset($_SESSION['userId']) basic isset check
$_SESSION['userId'] not sure what we're looking for here but this needs to result in boolean true
USER_LEVEL_ADMIN == $_SESSION['userId']['user_Lvl'] authorized privilege check
All 3 need to be true for the if to succeed.
if (isset($_SESSION['userId']) && $_SESSION['userId'] && USER_LEVEL_ADMIN == $_SESSION['userId']['user_Lvl']) {
return true;
}
else { // works if you reverse true and false, else this is broke
return false;
}
I suspect the if is false due to this: define('USER_LEVEL_ADMIN', '1'); which creates the named constant USER_LEVEL_ADMIN with a STRING value of '1'. Then, in your if statement you compare it to $_SESSION['userId']['user_Lvl']. Please check the variable type of $_SESSION['userId']['user_Lvl']. You can drop this line in your code to check that:
echo gettype($_SESSION['userId']['user_Lvl']);
It of course would need to match the type of USER_LEVEL_ADMIN which is string.

Codeigniter - return an anchor() from function

probably a newb question here, but how do I return a CI anchor() call from within a function. I want to "hide" a button if a variable is set to a certain value.
CI's URL helper documentation: https://www.codeigniter.com/user_guide/general/helpers.html
A pseudo example that won't work (can't return the URL helper anchor('',''):
$prevAvailCompID = 0;
function hideButton($prevCompID)
{
if($prevCompID == 0)
{
return anchor('/getcomps/getSpecificComp/'.$prevCompID , 'PREV COMP');
//I've also tried return echo anchor(...)
}
}
further down on the page:
<div id="prevBtnContainer"><? hideButton($prevAvailCompID); ?></div>
You don't need to return the anchor() function. You can just use as this
UPDATED CODE
public function test(){
?>
<h1>test H1</h1>
<div id="prevBtnContainer"><?php $this->hideButton(0); ?></div>
<div id="1prevBtnContainer"><?php $this->hideButton(1); ?></div>
<?php
}
private function hideButton($prevCompID)
{
if($prevCompID == 0)
{
echo anchor('/getcomps/getSpecificComp/'.$prevCompID , 'PREV COMP');
}
}
I've tested this in my CodeIgniter and its working.

Sending a variable to the view which is used in controller with phalconPHP

I have a small issue i have declared a variable of type Boolean in my controller.
$done=False
Now there is a trigger in the controller that would turn it to True and it is at this point i would like to send it to the corresponding view with this controller .. i have used the following.
$done=True;
$this->view->setVar("done", $done);
Now when i try to call it in the corresponding view it does not know anything of this varible.
if($done==True)
{
echo'
<div class="alert alert-success">
Add Another Here!
</div>
';
}
It gives me the following:
Notice: Undefined variable: done in >C:\xampp\htdocs\Blueware\app\views\addNewSkill\index.phtml on line 36
Now is there a better way of sending this varible through to the view or am i making a mistake?
Full Controller/Action Code:
<?php
class addNewSkillController extends \Phalcon\Mvc\Controller{
public function indexAction(){
}
public function confirmAction(){
$this->view->disable();
$done=False;
if($this->request->isPost()) {
$dataSent = $this->request->getPost();
$skill = new Skills();
$skill->technology = $dataSent["technology"];
$skill->skillName = $dataSent["skillName"];
$skill->description = $dataSent["description"];
$savedSuccessfully = $skill->save();
if($savedSuccessfully) {
$done=True;
$this->view->setVar("done", $done);
} else {
$messages = $skill->getMessages();
echo "Sorry, the following problems were generated: ";
foreach ($messages as $message) {
echo "$message <br/>";
}
}
} else {
echo "The request method should be POST!";
}
}
}
Full View Code:
<?php
if($done==True)
{
echo'
<div class="alert alert-success">
Add Another Here!
</div>
';
}
?>
if($savedSuccessfully) {
$done=True;
$this->view->setVar("done", $done);
} else {
You should be setting the variable there, But setting in the view after seems that its not saving and therefore not passing the variable on
similar to
if($savedSuccessfully) {
$done=True;
} else {
...later in code ...
$this->view->setVar("done", $done);
or even just
$this->view->setVar("done", $savedSuccessfully);

Zend flash messenger

I have a form and the submit button check if true or false.
If it's true redirect to another page.
If it's false stay on the same page and print the error message.
The error message is print out with a flash messenger.
But, in some case it doesn't print in the first try when submit is false, it always print out on the second click.
Did I did something wrong?
And also, is there a way to set difference flash messenger name? Because, on my others pages that have flash messenger, print out the error when page is refreshed.
Here's the code:
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
$this->view->messages = $this->_helper->flashMessenger->getMessages();
}
}
HTML:
<center>
<div style="color:red">
<?php if (count($this->messages)) : ?>
<?php foreach ($this->messages as $message) : ?>
<div id="field_name">
<strong style="text-transform:capitalize;">Email </strong>
- <?php echo $this->escape($message); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</center>
flashmessenger is really designed to be used on a redirect of some kind, so any message you see probably comes from the prior action's execution. Your current code would not flash any message during the first 'post'.
you may have some luck if you try something like:
public function init()
{
//This will catch any messege set in any action in this controller and send
//it to the view on the next request.
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
}
public function someAction()
{
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
//will redirect back to original url. May help, may not
$this->_redirect($this->getRequest()->getRequestUri());
}
}
}
Here's an action I coded that demonstrates what you seem to be attempting.
public function updatetrackAction()
{
//get the page number
$session = new Zend_Session_Namespace('page');
$id = $this->getRequest()->getParam('id');
//get the entity object
$model = new Music_Model_Mapper_Track();
$track = $model->findById($id);
//get the form
$form = new Admin_Form_Track();
$form->setAction('/admin/music/updatetrack/');
//test for 'post' 'valid' and update info
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$newTrack = new Music_Model_Track($data);
$update = $model->saveTrack($newTrack);
//add message
$this->message->addMessage("Update of track '$update->title' complete!");
//redirects back to the same page number the request came from
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
} else {
//if not post display current information
//populate() only accepts an array - no objects -
$form->populate($track->toArray());
$this->view->form = $form;
}
}

Twitter Bootstrap and CodeIgniter's Validation_Errors

I am using Twitter Bootstrap to style validation_errors for a registration page:
<?php
echo "<div class='alert alert-error span4'>";
echo validation_errors();
echo "</div>";
?>
The validations work and show up but part of the styling is always present (the div tag has a red background). Is there a way to have the styling show up ONLY when the validation_errors are present. I have tried a few things (embedding html in php tags and enclosing the php in div tags) but the result is the same.
The reason that the div structure still appears is because it's echoing without regard to whether there are errors or not.
You could set the value of a variable to the result of your validation_errors() function in your Controller, then only display the alert div in your View if you've actually got an error...
Your controller would assign the variable to hold the (potential) error:
$this->data['reported_error'] = validation_errors();
$this->load->view('view_name', $this->data);
Then your view would only display the alert div if there was an error:
if ( isset($reported_error) )
{
echo "<div class='alert alert-error span4'>".$reported_error."</div>";
}
This requires your validation_errors function to only return a value if there is an error.
You can try something like this it works for me.
<?php if(validation_errors()):?>
<div class='alert alert-error span4'><?php echo validation_errors(); ?></div>
<?php endif;?>
I use the following construct to put the errors with special classes next to the fields that they reference:
<div class="<?php echo my_error_class('fieldname') ?>">
<input type="whatever" name="fieldname" />
<span class="whatever"><?php echo my_error_msg('fieldname') ?></>
</div>
with the following functions in a CI helper:
<?php
if ( ! function_exists('my_error_class')) {
function my_error_class($field, $error_class = "error") {
if (FALSE === ($OBJ =& _get_validation_object())){
return '';
}
if(isset($OBJ->_field_data[$field]['error']) && !empty($OBJ->_field_data[$field]['error'])) {
return $error_class;
}
else {
return '';
}
}
}
if ( ! function_exists('my_error_msg')) {
function my_error_msg($field,$default = '') {
if (FALSE === ($OBJ =& _get_validation_object())){
return $default;
}
if(isset($OBJ->_field_data[$field]['error']) && !empty($OBJ->_field_data[$field]['error'])) {
return $OBJ->_field_data[$field]['error'];
}
else {
return $default;
}
}
}
I was having the same issue. I assigned validation_errors() to a variable in my controller and passed it to the view.
Going off James' solution, I had to change:
if ( isset($reported_error) )
to:
if (!empty($reported_error))
Once I did this, the alert block only displayed when there was an error.
I didn't find this in the guide but apparently validation_errors takes two optional args for a prefix and suffix... so you can do:
validation_errors('<p class="text-warning">', '</p>');

Categories