Use of superglobals within a session

Asked

Viewed 130 times

2

index php.

<?php 
    include './db_unifacex.php';
    session_start();
    $_SESSION['contador']=0;
?>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="refresh" content="0.1;URL=http://localhost/geraCode/content.php">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link href="jquery/jquery-3.1.1.min.js" type="text/javascript">
        <link type="text/css" href="style/style.css" rel="stylesheet">
    </head>
</html>


php content.

    <?php 
    include './db_unifacex.php';
    session_start();
?>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link href="jquery/jquery-3.1.1.min.js" type="text/javascript">
        <link type="text/css" href="style/style.css" rel="stylesheet">
    </head>
    <body style="background-image: url(imgs/bk.jpg);">
        <div class="header">
            <img class="logo" src="imgs/cife_logo.png">
            <div class="titulo">
                Gerador de Newslatter
            </div>
            <hr>
        </div>
        <div class="container">
            <div class="col-md-12">
                <div class="col-md-6">
                    <h2> <?php echo $_SESSION['contador']+1;?>º Notícia </h2>
                    <form class="formulario" action="validar.php" method="post">
                        <div class="form-group">
                            <label>Titulo:</label> <input required type="text" name="titulo" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>Mensagem:</label> <textarea required name="mensagem" class="form-control"></textarea>
                        </div>
                        <div class="form-group">
                            <label>Foto:</label><input required type="text" name="foto" class="form-control">
                        </div>
                        <div class="form-group">
                            <input id="enviar" type="submit" name="enviar" class="form-control btn-default" value="Próximo">
                        </div>
                    </form>
                    <form action="fim.php" method="post">
                        <div class="form-group">
                            <input id="enviar" type="submit" name="fim" class="form-control btn-default btn-disable finalizar"  <?php if($_SESSION<4){echo 'disabled';}?> value="Finalizar">
                        </div>
                    </form>
                </div>
                <div class="col-md-6 ">
                    <h2>Pré-visualização: <?php echo $_SESSION['contador']+1;?>º Notícia</h2>
                    <div class="panel panel-defaul">
                        <div class='panel-body'>
                            <?php
                                $row = row($_SESSION['contador']);
                                echo $row;
                                $linha = ultimos();
                                var_dump($linha);
                            ?>
                        </div>
                    </div>
                </div>
            </div>    
        </div>
        <div class="footer">
            <hr>
            <div class="rodape">
                Produzido por Rafael Pessoa
            </div>
        </div>
        <?php fim();?>
    </body>
</html>


validate.php

    <?php
include ('./db_unifacex.php');
session_start();
//Variáveis recebidas do index.php
    $titulo = $_POST['titulo'];
    $mensagem = $_POST['mensagem'];
    $foto = $_POST['foto'];

//Variáveis do banco de dados
    $host = "mysql:host=localhost;dbname=boletim";
    $passwd = "senha";
    $username = "user";
//Conexão com o banco
    try {
        $conn = new PDO($host, $username, $passwd);
    } catch (Exception $exc) {
        echo $exc->getMessage();
    }
//Inserção dos dados
    $stmt = $conn->prepare("INSERT INTO noticia(titulo, mensagem, enderecoUri) VALUES(:tit, :mens, :end)");
    $stmt->bindParam(":tit", $titulo);
    $stmt->bindParam(":mens", $mensagem);
    $stmt->bindParam(":end", $foto);
    $stmt->execute();  
//Soma da sessão
    $_SESSION['contador']++;
    ?><a href="index.php"><button>Voltar</button></a>

I’m wondering if you have how to modify the value of a variable superglobal. I have to pass a variable from one page to another and then go back to the old page added +1.

In other words, I need an accountant superglobal. I was trying to do this to superglobal $_SESSION, but I realized it doesn’t work.

1 answer

1


What you can do with $_SESSION . But since Voce didn’t enter the code, I’ll make an example: page1.php

// inicias as sessoes
session_start();
//verifica se a sessao contador nao existe
if(!isset($_SESSION['contador'])){
//se ela nao existir, inicio ela com o valor padrao 0
$_SESSION['contador']=0;
}
else{
// mas se ela existir, apenas somo +1
$_SESSION['contador']++;
}

Ai na page 2.php It would be the same code:

 // inicias as sessoes
session_start();
//verifica se a sessao contador nao existe
if(!isset($_SESSION['contador'])){
//se ela nao existir, inicio ela com o valor padrao 0
$_SESSION['contador']=0;
}
else{
// mas se ela existir, apenas somo +1
$_SESSION['contador']++;
}

Or the same code in a well summarized way using the ternary operator:

// inicias as sessoes
session_start();
!isset($_SESSION['contador'])?$_SESSION['contador']=0:$_SESSION['contador']++;

For those who do not know, this operator has this syntax

(condition)? here the condition is true : here she is false;

The possible mistake you’re probably having is that you’re not giving session_start() on every page. I hope I’ve helped

  • Dude, that’s pretty much it, but is the value of the $_SESSION['counter'] variable going to stay the same at all? For example, I define it at the beginning of the index template.php. In the index I have a <form> and send it to the validar.php page. On this new page I want to recover the value of $_SESSION['counter'] and add 1 more. This I was not getting.

  • @Rafaelpessoa yes, always will. But remember to give session_start(); on all pages that will use the session

  • It will always hold, and if you want to change it will change, and it will change on every page as well. And if the answer helped you mark as answer :)

  • @Rafaelpessoa an application example would be in a shopping cart, which is used in several pages, or even in login, where store the data of the logged in user, if not already used

  • Well, I’m not able to do that. I start the index and assign 0 to the variable, redirect to another page. On this other page I send a <form> to a third validation page. When validated, I increment the variable $_SESSION['counter']++. After I click the button that returns the previous page the variable has not changed.

  • @Rafaelpessoa makes a test putting exactly as I put, giving an echo in this session on each page, and see if it is working

  • This other page has the start?

  • I just updated the post with the code. I’m doing it this way, as you can see. The intention is that when you go to validate the variable be incremented. But when you go back to the previous page it does not remain 0.

  • Always checking if this session exists, then increment. Remove echo where you do not need to display the value

  • @Rafaelpessoa , Remembering that echo $_SESSION['contador']+1; does not increase another 1 in the variable

  • i know. I just want to anticipate the information. But even the way you spoke continues not to increase.

  • I solved it. The problem that was happening was that you had changed the order on the ternary operator. It should increase if the answer is positive. Also, there was another problem. Because my index is automatically redirected, and my return button was scheduled to forward to the index, every time I came back from validating.php it reset the session.

  • @Rafaelpessoa I repaired, there was even change there, I edited putting the negation sign that I had forgotten. :)

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.