laravel 5 - check if session can be used - php

When a photo is watched on my website, I want to count the views - only if I can block further counting for the current session:
$lp = Session::get('lp',null);
if(!is_null(Request::cookie('laravel_session')))
{
if(is_null($lp) || is_array($lp) && !in_array($pic->id,$lp))
{
$cpic = Popularpic::find($pic->id);
$cpic->hits = $pic->hits + 1;
$cpic->pop_hits = $pic->pop_hits + 1;
$cpic->save();
//increment pic views for showing
$pic->hits = $cpic->hits;
Session::push('lp',$pic->id);
}
}
The problem is, when a user comes directly from another website, the view will not be counted if the cookie is not yet set.
Is there another way to check if I can use Session? ..perhaps like this:
if(i know i can use session)
# count
# session::push
endif
I'm trying to count the first view. Before the cookie is set.. ..if it is possible.

Related

PHP Session Variable - change on page load

I'm trying to get a session variable to alternate between 0 and 1 on each page load.
So first time page loads
$_SESSION['turn'] = 0;
Second time
$_SESSION['turn'] = 1;
Third time
`$_SESSION['turn'] = 0;`
and so on.
Then I can call that variable later in the page.
I can't work out how to do this. I've tried a simple IF function but can't get it to work.
First the session must be started on any page wishing to make use of the session array. session_start()
Next you have to remember that initially the session variable you are using will not exist the first time you attempt to use it
So
<?php
session_start();
if ( !isset($_SESSION['turn']) ) {
// does not exist yet, so create with 0
// you may want to initialize it to 1, thats up to you
$_SESSION['turn'] = 0;
} else {
$_SESSION['turn'] = $_SESSION['turn'] == 0 ? 1 : 0;
}
Try this where the page is loaded.
$_SESSION['turn']=1-$_SESSION['turn'];
code:
<?php
session_start();
echo $_SESSION['turn'];
$_SESSION['turn']=1-$_SESSION['turn'];
?>
Edit : RiggsFolly !isset() is correct. mine misses it and it will give errors in log. and the first value is not 0

Incrementing the value of the post by every repeated form submission

I have a form sender which is posting a value of 6 to another form receiver. What I'm trying to achieve is store the posted value from sender into a variable in the receiverthen increment the variable it every time the sender posts. Then print the updated variable
This is what I have tried to do
$val= $_POST['val'];
$limit = 6 + $val;
echo $limit;
Im getting the result as 12. But what I want is
After first post result = 12
After second post result = 18
On and on...
NB:$_POST['val'] = 6;
session_start();
$limit = 6;
if(!isset($_SESSION['lastLimit'])) {
$_SESSION['lastLimit'] = 0;
}
if(!empty($_POST)) {
$_SESSION['lastLimit'] = $_SESSION['lastLimit'] + $limit;
$postedValue = $_POST['val'] + $_SESSION['lastLimit'];
echo $postedValue;
}
Because the web is stateless i.e. scripts do not remember anything that happened the last time a page/form was executed the receiver script does not remember anything from the last time it was run.
But dont panic, there is a way. Its called a SESSION and you can store data in the session which will then be available the next time this user connects to your site. In PHP you use it like this. The session is linked to this specific connection to a specific user.
receiver.php
<?php
// must be run at top of script, before any output is sent to the new form
session_start();
// did the form get posted and is the variable present
// or replace POST with GET if you are using an anchor to run the script
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['val']) {
if ( isset($_SESSION['limit'] ){
// increment the limit
$_SESSION['limit'] += (int)$_POST['val'];
} else {
// initialize the limit
$_SESSION['limit'] = (int)$_POST['val'];
}
echo 'Current value of limit is = ' $_SESSION['limit'];
} else {
// something is not right
// direct this user to some basic page like the homepage or a login
header('Location: index.php');
}
You need an intermediate layer to store the value.
Available options:
1) Global static value
2) session
3) file
4) database
I would recommend global value or session, as they data you want to store isn't that huge and would meet the requirements easily.
I would not write the syntax to store it in session as a number of people have already mentioned it. I just wanted to clarify the problem scenario and possible solutions.
You can store $limti into global varibale .
global $val;
$val += $_POST['val'];
$limit = 6 + $val;
echo $limit;

Creating hit Counter

I am trying to create a hit counter for my website and I have developed the following code for it. I have included the following code only in Codeigniter's main controller for my home page.
At first I thought the code was working fine but I just found that if I don't keep on browsing the pages then again go to the home page it doesn't update the data. I mean for example: If I go to my homepage for the first time then it updates the data, but after 10 seconds if I refresh the page it does't update the data. But if I keep refreshing it for 10 seconds then it works.
So could you please tell me how to get it update the data without having to keep on browsing the pages or refreshing the home page?
Thanks :)
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout')) {
$out = time() + 10; // I will change it to $out = time() + 60*60; later
$this->session->set_userdata('timeout', $out);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat+1
WHERE id = '1'");
} else {
$timeout_time = $this->session->userdata('timeout');
if (time() > $timeout_time) {
$this->session->set_userdata(array('timeout' => ''));
$this->session->sess_destroy();
}
}
}
edit
What I am trying to achieve is when an user visits the webpage for the first time, I want to update my database. Within 10 seconds (for example purpose), if the visitor again visits the home page, the database will not be updated. But after 10 seconds if he again visits the home page, I want to update my database.
Thanks :)
Your code says "if there is no timeout in the session, update the count". You want it to say "if there is no timeout in the session, or there is but it's old, update the count".
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout') || $this->session->userdata('timeout') < time()) {
$this->session->set_userdata('timeout', time() + 10);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat + 1 WHERE id = 1");
}
}
I'm not a CodeIgniter user, so I am assuming that you used its session facilities correctly; I just used them the same way.

Very strange $_SESSION behaviour

I have a Session which I am using to hold items in a form that are accumulated up by the user until the user wants to proceed to checkout. Its a bit like a Shopping cart where items can be added from the form.
Logical breakdown of code:
Page loads, session starts
If $_SESSION['set'] is not set then set it to TRUE.
Display rest of page and form.
User hits "Add another item" button.
Page data gets posted to itself
Page checks that $_SESSION['set'] = True and $_POST['add_item'] is set.
Page creates a session variables in an array, and adds posted values to those sessions.
Page increments $_SESSION['tariff_count'] if more needs to be added
The problem is that my code is not behaving as it should. When I click "Add new tariff" button the first time it does not get caught by my if function. This should be immediately caught. However when I go and press the button again, it finally works and adds an item to my session.
Here is the code:
//start a session to remember tariff items
session_start();
//testing the session array
print_r($_SESSION);
//destroy session if this character is found in URL string
$des = $_GET['d'];
if($des == 1)
{
session_destroy();
}
//checks to see if session data has been set
//if a session variable count is set then
if ($_SESSION['set'] == TRUE)
{
//perform a check to ensure the page has been called by the form button and not been accidently refreshed
if(isset($_POST['add_tariff']))
{
//if user clicks Add another tariff button then increase tariff count by one
//temp variable set to the current count of items added
$count = $_SESSION['tariff_count'];
$_SESSION['tariff_name'][$count] = $_POST['tariff_name'];
$_SESSION['tariff_net'][$count] = $_POST['tariff_net'];
$_SESSION['tariff_inclusive'][$count] = $_POST['tariff_inclusive'];
$_SESSION['tariff_length'][$count] = $_POST['tariff_length'];
$_SESSION['tariff_data'][$count] = $_POST['tariff_data'];
//increment tariff count if more data needs to be added to the sessions later.
$_SESSION['tariff_count']++;
}
}
//if no session data set then start new session data
else
{
echo "session set";
$_SESSION['set'] = TRUE;
$_SESSION['tariff_count'] = 0;
}
The code seems to be fudging my arrays of Sesssion data. All my added items in the session are displayed in a table.
However if my table shows six items, if i do a print_r of the session it only shows there are 4 items in the array? I have tested it to make sure I am not reprinting the same instances in the array.
Here is a print_r of the array that shows six rows but there are only four rows in this array?
[tariff_count] => 5 [tariff_name] => Array (
[0] => STREAM1TARIFF [1] => STREAM1TARIFF [2] => CSS [3] => CSS [4] => CSS
)
I have take a screenshot as well to show this strange problem
http://i.imgur.com/jRenU.png
Note I have echoed out "True Value =6" but in the print_r of the session it is only 5, so my code is missing out one instance (n-1).
Here is my code that prints all the instances in the session arrays, I have a feeling part of the problem in mismatch is caused by the "<=" comparison?
if(isset($_SESSION['tariff_count']))
{
for ($i = 0; $i <= $count; $i++)
{
echo "<tr>";
echo "<td>".$_SESSION['tariff_name'][$i]."</td>";
echo "<td>".$_SESSION['tariff_net'][$i]."</td>";
echo "<td>".$_SESSION['tariff_inclusive'][$i]."</td>";
echo "<td>".$_SESSION['tariff_length'][$i]."</td>";
echo "<td>".$_SESSION['tariff_data'][$i]."</td>";
echo "</tr>";
}
}
Paste bin of php page - http://pastebin.com/petkrEck
Any ideas, why my If statement is not catching the event when the user presses "Add another tariff" button the first time it is pressed, but then detects it afterwards?
Thanks for your time
Merry Christmas!
The problem is your code flow. In simplified pseudo-code, you're doing this:
if (session is not initialized) {
set = true
count = 0;
} else {
add posted data to session
}
On the first 'add item' call, the session is not set up, so you set up the session. AND THEN IGNORE THE POSTED DATA.
The code flow should be:
if (session is not initialized) {
set = true;
count = 0;
}
if (posting data) {
add data to session
}

PHP session not working with JQuery Ajax?

Update, Solved:
After all this I found out that I was calling an old version of my code in the update ajax.
'boardControl.php' instead of 'boardUpdate.php' These are the kinds of mistakes that make programing fun.
I'm writing a browser gomoku game. I have the ajax statement that allows the player to play a piece.
$(document).ready(function() {
$("td").live('click',function(){
var value = $(this).attr('id');
$.get('includes/boardControl.php',{play: value, bid: bid});
});
});
value = board square location
bid = board ID
Before creating a user login for player identification, the server side php had a temporary solution. It would rotate the piece state for the squares when clicked instead of knowing what player to create them for.
After creating login stuff I set a session variable for the player's ID. I was hoping to read the session ID from the php during the ajax request and figure out what player they are from there.
session_start();
...
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
For some reason when I run the full web app, the pieces still cycle though, even after I deleted the code to make them cycle.
Furthermore, after logging in If i manually load the php page in the browser, it modifies the database correctly (where it only plays pieces belonging to that player) and outputs the correct results.
It seems to me that the session is not being carried over when used with Ajax. Yet Google searches tell me that, sessions do work with Ajax.
Update: I'm trying to provide more information.
Logging in works correctly. My
ID is recognized and I printed it
out next to the board to ensure that
I was retrieving it correctly.
The ajax request does update the
board. The values passed are
correct and confirmed with firebug's
console. However instead of placing
pieces only for the player they
belong to it cycles though the piece
states (0,1,2).
When manually browsing to
boardUpdate.php and putting in the
same values sent from the Ajax the
results seen in the echo'ed response
indicates that the corresponding
piece is played each time as
intended.
Same results on my laptop after
fresh load of firefox.
Manually browsing to
boardUpdate.php without logging in
before hand leave the board
unchanged (as intended when no user
is found in the session).
I've double checked the that
session_start() is on the php files
and double checked the session ID
variables.
Hope this extra information helps, i'm running out of ideas what to tell you. Should I load up the full code?
Update 2:
After checking the Ajax responce in fire-bug I realized that the 'play' request does not get a result, and the board is not updated till the next 'update'. I'm still looking into this but I'll post it here for you guys too.
boardUpdate.php
Notable places are:
Refresh Board(line6)
Place Piece(line20)
function boardUpdate($turnCount) (line63)
<?php
session_start();
require '../../omok/dbConnect.php';
//*** Refresh Board ***
if(isset($_GET['update']))
{
$bid = $_GET['bid'];
$Query=("SELECT turn FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
if($_GET['turnCount'] < $turnCount) //** Turn increased
{
boardUpdate($turnCount);
}
}
//*** Place Piece ***
if(isset($_GET['play'])) // turn order? player detect?
{
$squareID = $_GET['play'];
$bid = $_GET['bid'];
$Query=("SELECT turn, boardstate FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
$boardState=mysql_result($Result,0,"boardstate");
$turnCount++;
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
// if($newPiece != 0)
// {
$oldPiece = getBoardSpot($squareID, $bid);
$oldLetter = $boardState{floor($squareID/3)};
$slot = $squareID%3;
//***function updateCode($old, $new, $current, $slot)***
$newLetter = updateCode($oldPiece, $newPiece, $oldLetter, $slot);
$newLetter = value2Letter($newLetter);
$newBoard = substr_replace($boardState, $newLetter, floor($squareID/3), 1);
//** Update Query for boardstate & turn
$Query=("UPDATE board SET boardState = '$newBoard', turn = '$turnCount' WHERE bid = '$bid'");
mysql_query($Query);
// }
boardUpdate($turnCount);
}
function boardUpdate($turnCount)
{
$json = '{"turnCount":"'.$turnCount.'",'; //** turnCount **
$bid = $_GET['bid'];
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
$json.= '"boardState":"'.$Board.'"'; //** boardState **
$json.= '}';
echo $json;
}
function letter2Value($input)
{
if(ord($input) >= 48 && ord($input) <= 57)
return ord($input) - 48;
else
return ord($input) - 87;
}
function value2Letter($input)
{
if($input >= 10)
return chr($input += 87);
else
return chr($input += 48);
}
//*** UPDATE CODE *** updates an letter with a new peice change and returns result letter.
//***** $old : peice value before update
//***** $new : peice value after update
//***** $current : letterValue of code before update.
//***** $slot : which of the 3 sqaures the change needs to take place in.
function updateCode($old, $new, $current, $slot)
{
if($slot == 0)
{// echo $current,"+((",$new,"-",$old,")*9)";
return letter2Value($current)+(($new-$old)*9);
}
else if($slot == 1)
{// echo $current,"+((",$new,"-",$old,")*3)";
return letter2Value($current)+(($new-$old)*3);
}
else //slot == 2
{// echo $current,"+((",$new,"-",$old,")";
return letter2Value($current)+($new-$old);
}
}//updateCode()
//**** GETBOARDSPOT *** Returns the peice value at defined location on the board.
//****** 0 is first sqaure increment +1 in reading order (0-254).
function getBoardSpot($squareID, $bid)
{
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
if($squareID %3 == 2) //**3rd spot**
{
if( letter2Value($Board{floor($squareID/3)} ) % 3 == 0)
return 0;
else if( letter2Value($Board{floor($squareID/3)} ) % 3 == 1)
return 1;
else
return 2;
}
else if($squareID %3 == 0) //**1st spot**
{
if(letter2Value($Board{floor($squareID/3)} ) <= 8)
return 0;
else if(letter2Value($Board{floor($squareID/3)} ) >= 18)
return 2;
else
return 1;
}
else //**2nd spot**
{
return floor(letter2Value($Board{floor($squareID/3)}))/3%3;
}
}//end getBoardSpot()
?>
Please help, I'd be glad to provide more information if needed.
Thanks in advance =)
From the small snippet of code we have, it's difficult to tell what your problem might be. What I can say is that session_start should be one of the first things you do on each page where you're expecting to use the session. After that, I would just immediately do a var_dump of $_SESSION to see that the data is in there (put a die right after that). It is quite possible that your true problem lies somewhere else, and that the session is in fact working. Is there a problem with your login code, for example, that is causing it to wipe out the session?
You can use Firebug to look at the raw results of your AJAX calls, which should be helpful, since your script appears to work if you directly visit the page.
Cases where I've seen sessions not work as expected have generally been that session_start is being called too often or too late. The other possibility is that you have an insanely short timeout, but that sounds unlikely.
Finally, you can make sure that your PHP install is set to use cookie sessions. It's very unlikely at this point that it wouldn't be, but you could look.
One potential problem in this code is the use of $.get - it is cached by IE, so your server code doesn't run every time. Try using $.ajax with cache set to false:
$.ajax({
type: 'GET',
url: 'includes/boardControl.php',
cache: false,
data: {play: value, bid: bid}
});
Just happened to me, in my case was that i was importing a config file with the session_start and since i had deactivated errors i couldn't see that the import was never happening. Just triple check this, I know it's the basic.

Categories