PHP Sessions Var Not Storing... Possible php.ini issues? - session

I'm trying to store information on a form by using sessions in case the validation returns false, then the user doesn't have to refill the form. This how I'm doing this:
PAGE A:
<?
session_start();
$Fname = $_SESSION['FirstName'];
?>
<html>
<input type="text" id="First" value="<? if($Fname){echo $Fname;}?>">
</html>
PAGE B:
<?
$Fname = $_POST['First'];
session_start();
$_SESSION['FirstName'] = $Fname;
//validation is not good then
header('Location: PageA.php');
?>
The issue is that when sent back to page A, nothing is showing up in the inputs, but randomly it will show up or, I'll refresh and it might show up. For most part its just not working and what I don't understand it kind of just started happening when I made a modification of removing one of the session vars and replacing it with a cookie because of other reasons, but decided not to go that route. Still I don't see what I could have done to start causing this issue. Any ideas? I'm thinking its something with the php.ini file because i have a separate form with the same setup and I never touched it, and now its not working when it was the last time i checked.
UPDATE
I just tried the form, I submitted it incorrectly on purpose to trigger the validation and it sent me back with blank inputs as I already mentioned. I clicked on another page and then came back to the form and the inputs appeared. It seems as if its storing but just not being read immediately? Don't know if this helps.

On Page B session_start() should be the first command on the page. I always keep this at the top just to be sure

You do not need SESSION at all ...
PAGE A:
<?
$Fname = isset($_POST['First']) ? $_POST['FirstName'] : '';
?>
<html>
<form method='post' action='PageB.php'>
<input type="text" id="First" value="<? if($Fname){echo $Fname;}?>"/>
</form>
</html>
PAGE B:
<?
//validation is not good then
include 'PageA.php';
exit;
?>

Not sure if it is a typo, but in your input tag you don't have the "name" attribute specified, which would mean an empty $_POST array when you go to page B.

It's difficult (for me at least) to help you without further details, but here are my thoughts:
From the PHP manual: "Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant. "
One solution found in other forums: call session_write_close() before the header redirection: external link
Apparently, header() can sometimes make the redirection BEFORE the session cookie is written. That could explain why sometimes it works and other times it doesn't. But, as I said, not sure that this applies to your code.

I got it working by filling in the things you left out in your example; does it work for you?
PageA.php
note addition of <form action="PageB.php" method="POST"> and change of id="First" to name="First"
<?
session_start();
$Fname = $_SESSION['FirstName'];
?>
<html>
<form action="PageB.php" method="POST">
<input type="text" name="First" value="<? if($Fname){echo $Fname;}?>">
</form>
</html>
PageB.php
(unchanged)
<?
$Fname = $_POST['First'];
session_start();
$_SESSION['FirstName'] = $Fname;
//validation is not good then
header('Location: PageA.php');
?>

Related

Showing notification with AJAX

I have a navbar on my users' panel. A part of the navbar indicates if the user has a new unread message. In this case a badge will appear next to an icon. I've simplified the codes here to make them easier to understand and read.
So this is the simplified HTML code:
<div class="btn-group msg-box">
<i class="fa fa-envelope"></i>
// this is the default state, no badge is shown
</div>
Here is the AJAX request which calls a custom function every 10 seconds:
<script type='text/javascript'>
$(document).ready(function(){
setInterval(checkMsg,10000);
});
function checkMsg(){
$.get('ajax.php',{user_id : <?php echo $user_id; ?>},function(data){
$('.msg-box').html(data);
});
}
</script>
And this is the ajax.php file content:
if(isset($_GET['user_id']){
// a few lines of code here to check if that particular user has any unread message.
// In such case a variable name $newMessage is set to 1. Now ... :
if($newMessage>0){
$data='
<i class="fa fa-envelope"></i>
<span class="badge"><i class="fa fa-info"></i></span>
';
}else{
$data='
<i class="fa fa-envelope"></i>
';
}
echo $data;
}
First of all, I know the way I've written this AJAX request is very rookie, but it works fine anyway, up to one point!
In case the user has a new message, and if they stay on a page, the code runs perfectly and shows the badge. But when the user refreshes the page or goes to another page, even-though they have a new message, that default state is shown again where there's no badge. And I know it's of course because I have specified a default state via HTML codes.
I need to know how I can keep the result of the AJAX request regardless of how many times the user refreshes the page or goes to another page.
UPDATE
I tried storing the query result in a SESSION in my ajax.php file. So instead of $data I wrote $_SESSION['data'].
Back on my HTML I made the following change:
<div class="btn-group msg-box">
<?php
if(!isset($_SESSION['data'])){
?>
<i class="fa fa-envelope"></i>
<?php
}else{
echo $_SESSION['data'];
}
?>
</div>
I made this change because I considered the fact that SESSIONS, by definition, are created and accessed globally within the domain. So once it's set, it can be checked and used on all other pages.
So that only if that SESSION isn't set, the default state should be displayed. But that as well doesn't seem to have my desired result. Still the same thing happens.
Ok, answering my own question now. :)
My UPDATE seemed to be a good idea which I tried.
The problem there was that I had written session_start(); on my main PHP file which was included in all other PHP files of the project.
So I basically thought that when the ajax.php file is called, there's no need to write session_start(); again. Because ajax.php was called inside a PHP file that had session_start(); in it already. So, I was wrong!
Adding session_start(); to the beginning of my code in ajax.php simply fixed the issue.

Codeigniter pass a id to controller from view

I am using codeigniter for this project. I hava a id value in which i pass from controller A to view A. This id value is echo between an anchor tag. When this anchor tag is clicked on, it redirects to another controller B with the id value and processed this id value within controller B. Is there any other way of doing this other than using the uri class? Want to keep the url clean.
I thought of a way of appending hidden input elements when I shift from controller A to view A to controller B, but i realised it can be very messy.
Any clean ways of doing this? Thanks in advance guys!
New to using Stackoverflow See if you could understand my layout:
METHOD 1
Use the URI Class except you have good reasons not to.
From CONTROLLER_A
$data["id"] = ("ID NUMBER");
$this->load->view("VIEW_A", $data);
ANCHOR IN VIEW A
link
IN CONTROLLER_B
$id = $this->uri->segment(3);
.
METHOD 2
USE FORM POST if you want to keep things hidden:
$data["id"] = ("ID NUMBER");
$this->load->view("VIEW A", $data);
ANCHOR IN VIEW A
<form name="myform" id="myform" action="<?php echo base_url() ?>/controllerB/controllerfunction/" method="post">
<input type="hidden" name="id" id="id" value="<?php echo $id ?>" />
<input type="submit" value="See more" />
</form>
You could also use javascript to submit the form here via link if you which:
See more
Tips:You could also use css to hide submit button in the form by setting opacity to 0;
If link is within the form, you could use javascript:this.submit();
OR JQUERY
See more
$('#link').click(function() {
$('#myform').submit();
});
IN CONTROLLERB
$id = $this->input->post("id");
Well hidden inputs will work, and there's may another workaround that once you redirected to the method and use your id value i.e. get data from database, redirect again to another controller method with the clean URL you need , hope this is helpful

PHP session not registering [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP session side-effect warning with global variables as a source of data
I have a problem with a login script that im using. problem is with some of the hosting providers after login the session is not registering. and in php error logs i can see this error
PHP Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively in Unknown on line 0
but in most of the hosting's like bluehost, hostmonster it works fine without any error. can someone point me out what is the wrong thing im doing here? thank you in advanced.
Code:
<?
session_start();
ob_start();
?>
<?php
$err=isset($_GET['error'])?$_GET['error']:"";
if($err=='error'){?>
<div class="errormsgbox">Wrong Username or Password. Please try again.</div>
<?php }
if(!isset($_SESSION['adminuser'])){
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$adminuser=mysql_real_escape_string($_POST['adminuser']);
$adminpassword=mysql_real_escape_string($_POST['adminpassword']);
$gpassword=md5($adminpassword); // Encrypted Password
$sql="SELECT id FROM admin WHERE adminuser='$adminuser' and adminpassword='$gpassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
session_register("adminuser");
header("location:index.php");
}
else
{
header("location:login.php?error=error");
}
}
ob_end_flush();
?>
<form action="login.php" method="post">
<div class="login_input">
<label class="loginlbl" for="adminuser">UserName :</label>
<input type="text" name="adminuser"/>
</div>
<div class="login_input">
<label class="loginlbl" for="adminpassword">Password :</label>
<input type="password" name="adminpassword"/>
</div>
<div class="login_submit">
<input type="submit" id="submit" value=" Login to Admin Contol Panel"/>
</div>
</form>
<?php }else{
header("location:index.php");
}
?>
The use of session_register is deprecated as says in PHP:SESSION_REGISTER
You should use:
//session_register("adminuser"); //deprecated
$_SESSION["adminuser"] = $adminuser;
The manual on session_register:
This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of
PHP 5.4.0.
Just use $_SESSION['adminuser'] as you would use any other variable instead.
Try replacing <? with <?php - it may be your hoster disabled so called short-tags, therefore that part is never executed. It's basically good habit to never use short tags
EDIT
You can disable this warning by adding this:
ini_set('session.bug_compat_warn', 0);
ini_set('session.bug_compat_42', 0);
or fix your code to not use the same name script variable and session key, i.e. this would trigger this warning:
$_SESSION['foo'] = false;
$foo = 0;
a heritage from PHP4 ages...
The problem is that you have a variable that has the same name like a normal variable.
$_SESSION['yourvar'] = null;
$yourvar = 'something';
PHP session side-effect warning with global variables as a source of data
And:
session_register is deprecated use $_SESSION['yourvar'] instead. The function session register causes the error.
Not the answer, but a warning that won't fit in a comment:
You're doing the password processing backwards. You're escaping, THEN md5-ing. This is incorrect. Consider a simple password:
o'brien
which gets escaped to
o\'brien
and then md5'd. That backslash will become PART of the hash value:
o'brien -> 255740509ca6c0e7d86c88fc4d8ddf9d
o\'brien -> afd5c6601a6df7e48d0ce5584b10bf12
note that the hash values are utterly different. This could turn around and bite you if you're comparing hashed values elsewhere and forget the escaping stage.

Magento: Category Lock/Warning or T&C

I wonder if there is a way to add a Warning/Advisory or Terms & Conditions (preferably) to a category or a landing page to warn users about adult content. On the shop I'm working on there is an "Adult Section" Category for Erotic Toys, Lingerie, cosplay, etc. and I need to warn users about such content before they access the section in case they're less than 18.
I've searched the web and only found paid extensions which I cannot afford. Does anyone know how to do this?
I'm using Magento CE 1.7.
Thanks,
EDIT:
Ok, so I've been trying to figure out how to do this and I just figured that the best way to do it would be to just create a Category Landing Page and adding a java script for T&C redirect to the page I want it to.
This is the code I would use for the Category Landing Page with blank content would be this.
<?php $_categories = $this->getCurrentChildCategories() ?>
<?php $_collectionSize = $_categories->count() ?>
<div>
<?php $i=0; foreach ($_categories as $_category): ?>
<?php
$layer = Mage::getSingleton(‘catalog/layer’);
$layer->setCurrentCategory(Mage::getModel(‘catalog/category’)->load($_category->getId()));
$helper = Mage::helper(‘catalog/category’);
?>
Then I found a code snippet that would redirect the user to a page of my liking after clicking accept but I'm not sure how to implement it and/or if this is the best choice. Here's the code.
<form action="url-to-go-to" method="GET" onsubmit="return checkCheckBox(this)">
I accept: <input type="checkbox" value="0" name="agree">
<input type="submit" value="Continue">
<input type="button" value="Exit" onclick="document.location.href='BACKTOWHAT.html';">
</form>
<script type="text/javascript">
<!--
function checkCheckBox(f){
if (f.agree.checked == false )
{
alert("Please tick the box to continue");
return false;
} else
return true;
}
-->
</script>
Now I was thinking that it would be best to just create a simple CMS page and point the category on the top menu to that page and once they have agreed and clicked on continue, they could be taken to the actual category by simply pointing the 'onclick' to the URL of the actual category.
Not sure if this is the best way but it's the only way I could come up. The other way I thought of would've required me to take the "agreements" during checkout that already comes with magento and make an extension that would allow me to place it on any page and call the "Agreement ID" from the Sales/Terms and Conditions tab but I don't know how to actually do that, it was just a thought.
If anyone has a better solution, I'd be happy to hear it.
I would add some sort of JavaScript that shows a div over the top of the whole page, that will create a session cookie when you accept to watch the category. Otherwise, make a back() in the history navigation. This way you don't need another page, just JS.
On another note, could you please post the extensions you found that do this?

Update multilingual content with AJAX in Yii

Refer to my code below, when user click on en button, the content will be changed to English, while clicking tw button, the content will be changed to Chinese.
However, the page will be refreshed each time when user click either en or tw button. I want to ask how can I implement AJAX content update in this case?
The result is when user click either en or tw button, the page won't be refreshed to change the content language.
Thanks
I have refer to Yii docs here, but seem that it is not appropriate for my case
C:\wamp\www\website\protected\views\site\index.php
<?php
$lang = isset($_GET["lang"]) ? $_GET["lang"] : "en_uk";
$lang = $lang == "en" ? "en_uk" : "zh_tw";
Yii::app()->setLanguage($lang);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input type="submit" value="en" name="lang" />
<input type="submit" value="tw" name="lang" />
</form>
<div class="main">
<?php echo Yii::t(Yii::app()->controller->id, "Causeway Bay"); ?>
</div>
Best practice is to reload the page in these cases, because usually you have to update so much, that it is just not worth it.
That said, CHtml's ajaxSubmitButton is the cleanest way to implement this, because you can map every event of your call very easily. It looks something like this:
<?php
echo CHtml::ajaxSubmitButton('en', CHtml::normalizeUrl(array('site/changeLanguage')),
array(
'error'=>'js:function(){
alert("error");
}',
//if you add a return false in this, it will not submit.
'beforeSend'=>'js:function(){
alert("beforeSend");
}',
'success'=>'js:function(data){
alert("success, data from server: "+data);
}',
'complete'=>'js:function(){
alert("complete");
}',
//'update'=>'#where_to_put_the_response',
)
);
?>
You don't have to use every parameter of course. The update parameter can update a HTML tag instantly.
EDIT:
This can be done easily if you use the controller's renderPartial method, for instance in your site controller if you have the action responsible for the index.
public function actionIndex(){
//get variables, etc
if(Yii::app()->request->isAjaxRequest) {
$lang = $_POST['nameOfSubmit'];
}else {
//...
}
//if the 3rd parameter is true, the method returns the generated HTML to a variable
$page = $this->renderPartial('_page', array(/*parameters*/ ), true);
echo $page;
}
And then, in your view file you can simply have
<?php echo CHtml::ajaxSubmitButton('en', CHtml::normalizeUrl(array('site/index')),
array('update'=>'#content_div',));?>
and
<?php echo CHtml::ajaxSubmitButton('tw', CHtml::normalizeUrl(array('site/index')),
array('update'=>'#content_div',));?>

Resources