Though after reading explanations about setting cookie and not working for first time i find it difficult to resolve the below problem as am new to php and cookies.
I have a webpage with for (e.g) cp.php, login.php, header.php, maindata.php , bottom.php. Whenever i login to the webpage cp.php will be processed from there 1.header.php will be called first 2.maindata.php will be called and 3.bottom.php will be called.
So am setting my cookie at maindata.php and the code is like,
<?php
$cid = $_GET["id"];
$XmlPath = $_GET["path"];
$numpath = $_GET["numpath"];
$finepath =$_GET["finepath"];
$Tech =$_GET["tech"];
$read_str="";
function read($Path)
{
$temp="";
if(file_exists($Path))
{
$library = new SimpleXMLElement($Path,null,true);
foreach($library->children("SAS") as $info){
foreach($info->children("SAS") as $attributes){
$nameVal = $attributes->Name."=".$attributes->Value;
$str_temp .=$nameVal."#";
}
}
}else
{
$str_temp ="NA";
}
return $str_temp;
}
$arrpath =explode(",",$XmlPath);
/*Reading and storing arrpath[0] has the path of xml to be parsed*/
$strG=read($arrpath[0]);
$strC=read($arrpath[1]);
$strB =read($arrpath[2]);
setcookie($cid.'strE',$strG);
setcookie($cid.'comstr',$strC);
setcookie($cid.'basstr',$strB);
(....)
in the same file am reading the cookie using the below code,
$read_str =$_COOKIE[$cid.'strE'].$_COOKIE[$cid.'comstr'].$_COOKIE[$cid.'basstr'];
after this process is done bottom.php will be called and for the first time loading is completed.As i said for the first time am not getting any value in $read_str, but if i refresh the page and do all the process again i am getting the value.
As SETCOOKIE will return TRUE incase of successfully setting cookie i tried putting it in an if-loop and it returned false even for the first time.
kindly assist me in finding where the problem exists!
Make use of isset to check if a cookie exists and then try setting one.
Something like this.
if(!isset($_COOKIE['yourcookie'])) {
setcookie('yourcookie', 'Some data !');
$_COOKIE['yourcookie'] = 'Some data !';
}
echo $_COOKIE['yourcookie'];
I arrived here looking for an answer as well. Here's the deal.
When you set a cookie it can only be accessed on the next page load, that is why you can't access it after you set it. If you really need to work with the cookie data right away, you could set the value directly in global cookie such as:
$_COOKIE['my_cookie'] = 'i am a cookie';
Use setcookie()just the same so you can set expiration, domain, etc..
Related
I'd like to store a datetime variable into different tables by using two functions. I use constraint in CI but still have no luck.
This is the constraint:
$date_now = date("ymdhis");
define('TODAY_DATE',$date_now);
These are the functions:
public function save_activity_m(){
foreach($details as $rows){
$stock_in = $rows['product']."_".TODAY_DATE;
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
public function save_notifikasi(){
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran."_".TODAY_DATE;
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
How to make the datetime is the same for $data['STOCK_IN'] and $data['note_date']?
Since the web is stateless, no data in a PHP variable will be held from one page (or load) to another; essentially you're booting the application from scratch each time.
The only way around this is to use some sort of semi-persistent storage such as a cookie or session variable (or persistent storage like the database) - setting a constant, e.g. define('TODAY_DATE',$date_now); will only make that data constant for the current execution of the script(s).
This is a basic example using session storage ($_SESSION):
<?php
// crank up the session
// you may well have one running already,
// in which case ignore this
session_start();
// store the execution time for this script
// as a session variable if it's NOT already set
// i.e. don't overwrite it
if(empty($_SESSION['time_now'])) $_SESSION['time_now'] = date("ymdhis");
public function save_activity_m() {
foreach($details as $rows) {
$stock_in = $rows['product'] . "_" . $_SESSION['time_now'];
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
/**
* Assuming this is the last thing you want to
* do with 'time_now' you should unset it here
*/
public function save_notifikasi() {
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran . "_" . $_SESSION['time_now'];
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
// since we're done with the 'time_now' session
// variable we need to unset it...
unset($_SESSION['time_now']);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
// just to be on the safe side unset the 'time_now' session var
// if it's older than 1 minute - otherwise future calls to this
// script, by the same user, during the same session will use
// the stored value from $_SESSION['time_now']
if(isset($_SESSION['time_now'])) {
$sessionTime = DateTime::createFromFormat('ymdhis', $_SESSION['time_now']);
$oneMinuteAgoTime = new DateTime('-1 minute');
if($sessionTime < $oneMinuteAgoTime) {
unset($_SESSION['time_now']);
}
}
The caveat is that because you've stored the time in a session variable, unless you update or unset it, it will always be there (for the current session) - so if the user runs the script again it'll just use the stored time from the session.
I've put in a couple of unset() calls to try and work around this.
See PHP: define. It's a constant and it should have the same value if the two functions executed in the same time the script is running.
this is the script im using for a login function. But if i want to add a timer to the session, it ignores it. I have tried it on 10 seconds, or 1 minute. But it does not seem to work. Someone has an idea of what is going wrong?
this is the line of code im using for the timer : session_set_cookie_params(3600,"/");
Thanks in forehand.
public function login($username, $password) {
$salt="";
$this->user_id=0;
$this->status=0;
$salt_query=$this->mysqli->query(
<<<EOT
SELECT salt
FROM xxxxx
WHERE username="{$username}"
EOT
);
$salt_query = $salt_query->fetch_row();
$salt = $salt_query[0];
$hash = hash('sha512', $password.= $salt);
$result = $this->mysqli->query(
<<<EOT
SELECT werknemer_id,status
FROM xxxxx
WHERE username="{$username}" AND password="{$hash}"
EOT
);
$rij =$result->fetch_row();
if ((empty($rij)) || (empty($rij[0]))) return(1);// Invalid combination
if (($rij[1]<1) || ($rij[1]>2)){
return(2); // Inactive account
}
$this->user_id=intval($rij[0]);
$this->status=intval($rij[1]);
session_regenerate_id();
$_SESSION['werknemer_id']=$this->user_id;
session_set_cookie_params(3600,"/");
return(0); // login
}
From the manual. I havent used it but it does say that you have to use it in every script. Also, you have to do it before start_session. I think that on of these is your problem.
Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.
Reference.
I am using Zend framework 1 and I need to change the session id at runtime with a predefined prefix, however I am getting the following error "The session has already been started. The session id must be set first." The issue is that the session state still remains started even after calling the destroy and writeclose. I also tried using the php methods unset & destroy but still same issue.
$oldSession = new Zend_Session_Namespace();
Zend_Session::destroy();
Zend_Session::writeClose();
$sessId = "dskjfghdsjfhsdkf"; //Random hash
Zend_Session::setId("myprefix".$sessId);
$newSession = new Zend_Session_Namespace();
foreach($oldSession as $idx => $data){
$newSession->$idx = $data;
}
Looks like it is not possible,
Snippet from Zend_Session.php:
if (!self::$_unitTestEnabled && defined('SID')) {
/** #see Zend_Session_Exception */
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception('The session has already been started. The session id must be set first.');
}
I am stuck, I can't find any reference to this problem. It shouldn't be happening. The global variable $assignmentInfo is passed into the function, manipulated, and returned as a different variable.
BUT, the local manipulations within the function are propagated to the global variable, so that the next time the function gets called, $assignmentInfo has been changed. I want to pass in the same, unchanging version of $assignmentInfo each time I call the function.
Any suggestions?
function studentScores($submissionInfo, $assignmentInfo){
//********************************** Add submission data to assignment data ****************************************************************************
foreach($assignmentInfo as $assignmentGroup){
foreach($assignmentGroup->assignments as $assignment){
foreach($submissionInfo as $submission){
if(isset($assignment->id) and isset($submission->assignment_id) and $assignment->id == $submission->assignment_id){
if (isset($submission->score)){$assignment->score = $submission->score;}
if (isset($submission->submitted_at)){$assignment->submitted_at = $submission->submitted_at;}
if (isset($submission->workflow_state)){$assignment->workflow_state = $submission->workflow_state;}
break;
}
}
}
}
$studentScores = $assignmentInfo;
return $studentScores;
}
$studentScores = studentScores($submissionInfo->submissions, $assignmentInfo);
I am trying to read some code here (not my own) and make changes. So far what I can get from reading it is that if a variable named $cuid is NOT set, it sends a user to a splash page. If it IS set, it sets the cookie to the $cuid variable (which is actually not happening, the cookie isn't updated when you come with a new CUID in GET)
Here's the code:
if (!$cuid || $reset)
{
$cuid="";
if( $cuid_demo!="samplecu" && $cuid!="75541953" )
setcookie("cuid","",time() - 31536000); //DELETES COOKIE
$query="UPDATE cusucceed SET kkc_visits=kkc_visits+1 WHERE id = '$cuid'";
$result=dbquery($link, $query) or die("error: ".dberror() );
include("splash.php");
}
else
{
setcookie("cuid","",time() - 31536000); //DELETES COOKIE
setcookie("cuid",$cuid,time()+604800); //1 week.
select_db($link) or die("error: ".dberror() );
if($admin_id)
{
$cuid=$cuid;
$id=$cuid;
}
$query="UPDATE cusucceed SET kkc_visits=kkc_visits+1 WHERE id = '$cuid'";
$result=dbquery($link, $query)or die("Database Server Error 2");
include("index_main.php");
Am I reading that correctly? The else part of the if statement should be setting the cuid cookie to $cuid, if $cuid is set, yes?
If $cuid is unassigned (more explicity, has a false result [albeit 0, false, empty]) or it should be $reset,
- Force-empty the cookie (assuming it's not [what appears to be] a test account)
- Display the splash page.
If $cuid is set (and it's not a $reset),
- Re-declare the cuid cookie, and make it last for a week. Then also display the main page.
In both instances,
- Increment the number of times the found $cuid has visited the page.
Although to be honest, it looks like the author wasn't really sure what they were doing based on duplicated code and that they feel the need to empty a cookie before re-declaring it.