Had googled this but maybe I'm not a good googler. My ultimate goal is to have a view more button that will read the next 6 files from a directory but before I do that I need to figure out this problem:
at the top of my index.php i have this:
<?php
if(session_id() == '') {
session_start();
$_SESSION["count"] = 0;
}
?>
lower down I have this:
<?php
function album() {
$_SESSION["count"]=$_SESSION["count"]+10;
echo $_SESSION["count"];
}
?>
when the user clicks a button its supposed to print the session variable + 10 on each click.. so 10 20 30 40 ..ect. But it keeps printing 10, it's not updating.
Always start session at the top of the page like
<?php
session_start();
if(session_id() == '') {
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] += 10;
echo $_SESSION["count"];
}
?>
You need to first do session_start() and then ask for $_SESSION.
<?php
session_start();
if(empty($_SESSION['count'])){
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] = $_SESSION["count"] + 10;
echo 'Count: '.$_SESSION["count"];
}
album();
?>
This I just tested it and it works fine.
Related
I am using the session to show some text. The result I want is After 10s of logging it should echo some text.
I tried:-
Functions.php
function LoginSessionExpired() {
if(!isset($_SESSION['first_visit']))
{
$_SESSION['first_visit']=time();
}else{
$login_session_durations = 10;
if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){
if(((time() - $_SESSION['first_visit']) > $login_session_durations)){
return true;
}
}
}
}
Dashboard.php
session_start();
include("functions.php");
if(isset($_SESSION["user_id"])) {
if(LoginSessionExpired()) {
echo "Ok";
}
}
But it echoes only when the page is refreshed, I want the auto show without refreshing.
I am working on something that i want to use in a project.
i am to redirect the current page to itself using php and session. The idea is that:
if my `$_session['insert']= true; then refresh the page to itself;`
Here is the code:
sess_page1.php
session_start();
$_SESSION["insert"] = 1;
$_SESSION["test"] = "Page refreshed";
?>
Click here to go to the next page
sess_page2.php
<?php
session_start();
if (isset($_SESSION["insert"]) && ($_SESSION["insert"]==1)) {
header('location:'.$_SERVER['PHP_SELF']);
print $_SESSION["test"];
}
else
{
echo "Impossible to execute.";
exit();
}
?>
But the page does not redirect to itself...The whole idea is the page should refresh one time.
What i did wrong here? Can somebody help?
Try this:
sess_page1.php
session_start();
$_SESSION["stopper"] = 0;
$_SESSION["insert"] = 1;
$_SESSION["test"] = "Page refreshed";
?>
Click here to go to the next page
sess_page2.php
<?php
session_start();
if (isset($_SESSION["insert"]) && ($_SESSION["insert"]==1) && ($_SESSION["stopper"]==0)) {
$_SESSION['stopper']=1;
header('location:'.$_SERVER['PHP_SELF']);
print $_SESSION["test"];
}
else
{
echo "Impossible to execute.";
exit();
}
?>
I Initialized a $_SESSION variable = 1 and I want to increment/decrements its value when a link is click. And the links will reload the page then echo the value of the $_SESSION. I was given a hint redired using header() but I still can't figure it how.
<?php
if (isset($_SESSION['count'])) {
$count = $_SESSION['count'];
} else {
$count = '';
}
?>
Increment
Decrement
<?php if (isset($_SESSION['count'])): ?>
<?php echo $count ?>
<?php endif ?>
header("Location: index.php") is a php redirect. In this case if the code above is in the index.php file already, there's no need to redirect the user.
<?php
session_start();
if(!isset($_SESSION['count']) { // first time opening the page
$_SESSION['count'] = 0; // initializing the counter
} else { // counter already have a value
if(isset($_GET['inc'])) { // increasing
echo ++$_SESSION['count']; // no need for extra variable (preincrement to echo immediately)
}
if(isset($_GET['dec'])) { // decreasing
echo --$_SESSION['count']; // no need for extra variable (predecrement to echo immediately)
}
}
?>
Increment
Decrement
<?php
session_start();
if(!isset($_SESSION['count'])
$_SESSION['count'] = 0;
$counter = $_SESSION['count'];
$counter = (int)$counter;
if (isset($_GET['inc'])==TRUE) {
$counter++;
$_SESSION['count'] = $counter;
header("Location: index.php");
}
if (isset($_GET['dec'])==TRUE) {
$counter--;
$_SESSION['count'] = $counter;
header("Location: index.php");
}
?>
Also You may need to cast $counter to int..
This is a simplified version of what I want to accomplish:
In my script I want a static variable x to be incremented every time the submit button is pressed.
<?php
function IncX(){
static $x = 0;
$x++;
echo $x;
}
?>
<body>
<form>
<input type="submit" name="submit" class="next btn btn-primary" value="Submit" />
</form>
</body>
But it initializes to x=0 on every page reload after submit.
You're loading the variable afresh every time the page loads, so it's always going to be the same.
The solution is to store it in a session and then increment it there. Include a conditional to create the variable if it doesn't already exist.
<?php
session_start();
if (!isset($_SESSION['x'])) {
$x = $_SESSION['x'];
} else {
$x = 0;
}
$x++;
echo $x;
$_SESSION['x'] = $x;
?>
<?php
session_start();
$x = 0;
if (isset($_SESSION['x'])) {
$x = $_SESSION['x'];
$x++;
} else {
$_SESSION['x'] = $x;
}
// /$x++;
echo $x;
$_SESSION['x'] = $x;
?>
Apache doesn't keep track of variables in php scrips between clicks, you would have to store it somewhere, be it the $_SESSION or a database.
Moreover, the static keyword doesn't do what you seem to think it does. It would work for successive calls of the function in a single run of the script, but not between clicks.
in any event, you can use the ternary operator to achieve this, would you happen to put it in the session. I've also added a check to make sure the variable is actually a viable count number:
session_start();
$_SESSION['x'] = isset($_SESSION['x']) && is_int($_SESSION['x'])
? $_SESSION['x'] + 1
: 1;
echo $_SESSION['x'];
I'm making a mini shopping cart for my project. Im storing the number of items chosen by the user, I don't understand that when i add one to my session variable I always get this error on the first go
Undefined index: cart_1 in D:\wamp\www\MiniCart\cart.php on line 100
And when I add again or refresh the same page it works fine. Why could this error be coming up? I removed the +=1 from the statement and it worked fine, apparently there is no syntax error too.
Cart.php
<!DOCTYPE>
<html>
<head></head>
<body>
<?php
session_start();
//The page where to jump to after adding/editing cart.
$page = 'mini_cart_index.php';
$link = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
echo "Error:".mysqli_connect_error();
echo "<br/>";
} else {
echo "Connected to SQL<br/>";
}
//==================================================
if(isset($_GET['add']))
{
$obt=$_GET['add'];
$quantity_limit = 'SELECT id,quantity FROM products WHERE id='.mysqli_real_escape_string($link,(int)$_GET['add']);
$quantity = mysqli_query($link,$quantity_limit);
while($quantity_row=mysqli_fetch_assoc($quantity))
{
if($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']])
{
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
/*
echo 'id='.$obt.' '.'next<br/>';
echo 'Now storing info into session variable and adding one<br/>';
echo $_SESSION['cart_'.$_GET['add']];
echo '<br/>';
echo 'info stored<br/>';
*/
}
//***************************************************
function products()
{
GLOBAL $link;
$get ="SELECT id,name,description,price FROM products
WHERE quantity > 0 ORDER by id ASC";
if($result=mysqli_query($link,$get))
{
echo "Data Selected to be displayed<br/>";
} else {
echo "Error:".mysqli_error($link);
}
if(mysqli_num_rows($result)==0)
{
echo "There are no products to display!<br/>";
} else {
while($get_row=mysqli_fetch_assoc($result))
{
echo '<hr/><br/>';
echo 'displaying data from database<br/>';
echo '==================================';
echo '<p>'.$get_row['name'].'<br/>'.
$get_row['description'].'<br/>'.
number_format($get_row['price'],2).
' Add'.'</p>';
echo '<hr/><br/>';
}
}
}
echo 'outside'.$_SESSION['cart_1'];
?>
</body>
</html>
Mini_cart_index.php
<?php require 'cart.php';?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php products() ?>
</body>
</html>
That code is filled with SQL injection vulnerabilities, you should use PDO and prepare your statements.
PHP is warning you because it has to read the current value and add to it, but the first time you try to access it doesn't exist.
You could suppress the warning with:
#$_SESSION['cart_'.$_GET['add']]+='1';
A better way to do it though would be checking if it exists first
$name = 'cart_'.$_GET['add'];
if(isset($_SESSION[$name]) {
$_SESSION[$name] = 1;
} else {
$_SESSION[$name] += 1;
}
The problem is caused by the fact that...
$var['abc'] += 1
...is the same as
$var['abc'] = $var['abc'] + 1
So if you've got a clean session and $var['abc'] doesn't exist, you're going to get a warning because you're trying to read a non-existant value in order to add 1 to it.
While it's true that 0 + 1 = 1
...what's actually happening here is undefined + 1 = 1 with a warning.
As other answers have mentioned - to fix the issue, you can explicitly check that the array index exists before trying to increment it.
I'd do that with the ternary operator like this:
$key = 'card_' . $_GET['add'];
$_SESSION[$key] = (isset($_SESSION[$key]) ? $_SESSION[$key] : 0) + 1;
This is effectively saying
$val = ($val if it exists, otherwise 0) + 1;
Change your if statement to check if it's empty too:
if (!isset($_SESSION['cart_'.$_GET['add']])) {
$_SESSION['cart_'.$_GET['add']] = 1;
} elseif ($quantity_row['quantity'] != $_SESSION['cart_'.$_GET['add']]) {
$_SESSION['cart_'.$_GET['add']] += 1;
}