-1

I have the following problem, I create a cookie in PHP and then read it in javascript and print it and this happens. I do not know how to correct it. Please help.

I read the cookie in javascript:

var micookie = (document.cookie.indexOf('resultado=') === -1 ? '' : ("; " + document.cookie).split('; resultado=')[1].split(';')[0]);

So he created the cookie in PHP:

setcookie("resultado","success",time() + 1, "/kira");

And it prints like this, as you can see in the image

Cerraste+sessi%C3%B3n 

Code that creates the notification

var i = -1;
var toastCount = 0;
var $toastlast;


var micookie = (document.cookie.indexOf('resultado=') === -1 ? '' : ("; " + document.cookie).split('; resultado=')[1].split(';')[0]);
var micookietipo = (document.cookie.indexOf('tipo_result=') === -1 ? '' : ("; " + document.cookie).split('; tipo_result=')[1].split(';')[0]);
micookietipo = decodeURIComponent((micookietipo + '').replace(/\+/g, '%20'))
var micookiedesc = (document.cookie.indexOf('desc_result=') === -1 ? '' : ("; " + document.cookie).split('; desc_result=')[1].split(';')[0]);
micookiedesc = decodeURIComponent((micookiedesc + '').replace(/\+/g, '%20'))


function alerta() {
  var shortCutFunction = micookie;
  var msg = micookiedesc || '';
  var title = micookietipo || '';
  var $showDuration = $(300);
  var $hideDuration = $(1000);
  var $timeOut = $(2000);
  var $extendedTimeOut = $(500);
  var toastIndex = toastCount++;
  var addClear = $('#addClear').prop('checked');
  toastr.options = {
    closeButton: false,
    debug: false,
    newestOnTop: false,
    progressBar: true,
    positionClass: 'toast-bottom-right' || 'toast-top-right',
    preventDuplicates: true,
    onclick: null
  };
  toastr.options.showEasing = 'swing';
  toastr.options.hideEasing = 'linear';
  toastr.options.showMethod = 'fadeIn';
  toastr.options.hideMethod = 'fadeOut';
  var $toast = toastr[shortCutFunction](msg, title); // Wire up an event handler to a button in the toast, if it exists
  $toastlast = $toast;

  if (typeof $toast === 'undefined') {
    return;
  }
};

if (typeof micookie !== 'undefined' && typeof micookietipo !== 'undefined' && typeof micookiedesc !== 'undefined') {
  alerta();
}

VALIDATE.PHP

    <?php
    $error = $_COOKIE['resultado'];

    if($error == 'error'){
    header("location: ../../index.php");
    } else {
    require_once "../biblioteca.php";
    session_start();

    $db = ConectaDb($dbHost, $dbUser, $dbPass, $dbName);

    $nombre=recoge("nombre");
    $email=recoge("email");
    $password=recoge("password");

    $consulta="SELECT * FROM users WHERE nombre='$nombre' AND email='$email' AND password='$password'";

    $result = $db->query($consulta);

    if (!$result) {
            print "<p>Error en la consulta.</p>\n";
    } 
    elseif ($result->fetchColumn() == 0) {
            setcookie("resultado","error",time() + 1, "/kira");
            setcookie("tipo_result","Datos incorrectos",time() + 1, "/kira");
            setcookie("desc_result","Usuario o contraseña incorrectos",time() + 1, "/kira");
            header("Location: ../../index.php");

    } 
    else {
            $consulta =  "SELECT * FROM users WHERE nombre = '$nombre'";
            $result = $db->query($consulta); 
            if (!$result) {
                print "    <p>Error en la consulta.</p>\n"; print "\n";
            } else {
                $consulta =  "SELECT * FROM users WHERE nombre = '$nombre'";
                $result = $db->query($consulta); 
                foreach ($result as $valor) {
                $tipo_usuario = $valor['tipo_usuario'];
                $foto = $valor['foto'];

                if($tipo_usuario == "admin"){  
                    setcookie("resultado","success",time() + 1, "/kira");
                    setcookie("tipo_result","Bienvenido Administrador $nombre",time() + 1, "/kira");
                    setcookie("desc_result","Has iniciado sessión correctamente",time() + 1, "/kira");
                    $_SESSION['tipo_user'] = 'administrador';
                    $_SESSION['usuario'] = $nombre;
                    $_SESSION['email'] = $email;
                    $_SESSION['fotoperfil'] = $foto;

                                        $carpeta = '../resources/musica/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/voz/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/luz/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/comida/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/foto/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                        header("Location: ../../panelcontrol_admin.php");
                return;
                }
                elseif($tipo_usuario=="user"){
                    setcookie("resultado","success",time() + 1, "/kira");
                    setcookie("tipo_result","Bienvenido Usuario $nombre",time() + 1, "/kira");
                    setcookie("desc_result","Has iniciado sessión correctamente",time() + 1, "/kira");
                    $_SESSION['tipo_user'] = 'usuario';
                    $_SESSION['usuario'] = $nombre;
                    $_SESSION['email'] = $email;
                    $_SESSION['fotoperfil'] = $foto;

                                        $carpeta = '../resources/musica/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/voz/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/luz/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/comida/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                                        $carpeta = '../resources/foto/'.$nombre;
                    if (!file_exists($carpeta)) {
                        mkdir($carpeta, 0777, true);
                    }
                        header("Location: ../../panelcontrol_user.php");
                return;
                }
                }
            }

    }    
        $db = null;
    }
?>
  • 1
    `time() + 1` means the cookie is destroy after one second – Andreas Mar 09 '19 at 20:14
  • I know, i need this, is working this. Not working text correctly – David Pricop Mar 09 '19 at 20:15
  • Try and set it for longer and see if you can read it in PHP. And include more PHP code. We need to see everything up to the setcookie function – Andreas Mar 09 '19 at 20:16
  • PHP is setting the cookie on a subdirectory. I suspect what you're seeing is a cookie from the root directory because the subdirectory cookie has expired. – Barmar Mar 09 '19 at 20:17
  • The setcookie is up, is all here. the content of cookie is this Cerraste Sesión, but JAVASCRIP read this, print other text, this Cerraste + sessi% C3% B3n – David Pricop Mar 09 '19 at 20:18
  • Unrelated to the problem, but what's the point of `positionClass: 'toast-bottom-right' || 'toast-top-right',`? That's the same as `positionClass: 'toast-bottom-right',` – Barmar Mar 09 '19 at 20:19
  • Make your cookie last for at least an hour while you're debugging. Get yourself the browser extension called Edit This Cookie, available for either Firefox or Google Chrome. Keep in mind that many cookies are "HttpOnly" meaning there's no way for your Javascript to read their values. You can also look at the server response in the Network tab of your browser dev tools. – O. Jones Mar 09 '19 at 20:20
  • jejejej this is true, he escaped me – David Pricop Mar 09 '19 at 20:21
  • Again, please include more of the PHP. Everything until setcookie function. Setcookie is a header function and can't run if you have output prior. So, post the PHP code – Andreas Mar 09 '19 at 20:22
  • Is that the real PHP code? The result you're seeing would come from `setcookie("resultado", "Cerraste sessión");`, not `setcookie("resultado", "success");` – Barmar Mar 09 '19 at 20:27
  • ready new php file – David Pricop Mar 09 '19 at 20:30
  • I still don't see where you're setting the `resultado` cookie to anything other than `success` or `error`. `Cerraste sessión` doesn't appear anywhere in the updated question. – Barmar Mar 09 '19 at 20:34
  • There's an accented character in `setcookie("desc_result","Has iniciado sessión correctamente",time() + 1, "/kira");` is that the cookie that's really giving you problems? – Barmar Mar 09 '19 at 20:36
  • It works in the following way, I send a cookie with the name of the result to collect it in the js of the alert and the content of that cookie, Cerraste Sessión is the value that is sent through the alert. – David Pricop Mar 09 '19 at 20:37

1 Answers1

1

You can decode the string in javascript like so:

var micookie = (document.cookie.indexOf('resultado=') === -1 ? '' : ("; " + document.cookie).split('; resultado=')[1].split(';')[0]);

decodeURIComponent((micookie + '').replace(/\+/g, '%20'))
Salar Bahador
  • 1,433
  • 1
  • 14
  • 26