【问题标题】:COOKIE created in php is misread in JAVASCRIPT在 php 中创建的 COOKIE 在 JAVASCRIPT 中被误读
【发布时间】:2019-07-31 13:35:45
【问题描述】:

我有以下问题,我在 PHP 中创建了一个 cookie,然后在 javascript 中读取它并打印它,这就会发生。我不知道如何纠正它。请帮忙。

我在 javascript 中读取了 cookie:

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

于是他用 PHP 创建了 cookie:

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

如您在图片中看到的那样,它的打印方式是这样的

Cerraste+sessi%C3%B3n 

创建通知的代码

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;
    }
?>

【问题讨论】:

  • time() + 1 表示cookie在一秒后销毁
  • 我知道,我需要这个,正在工作。无法正确处理文本
  • 尝试将其设置更长的时间,看看您是否可以在 PHP 中阅读它。并包含更多 PHP 代码。我们需要查看 setcookie 函数之前的所有内容
  • PHP 正在子目录中设置 cookie。我怀疑您看到的是根目录中的 cookie,因为子目录 cookie 已过期。
  • setcookie 已启动,都在这里。 cookie 的内容是这个 Cerraste Sesión,但是 JAVASCRIP 读取这个,打印其他文本,这个 Cerraste + sessi% C3% B3n

标签: javascript php cookies


【解决方案1】:

您可以像这样在 javascript 中解码字符串:

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

decodeURIComponent((micookie + '').replace(/\+/g, '%20'))

【讨论】:

  • 我现在试试。谢谢你
  • 欢迎您。如果此答案是您所寻求的,请将其标记为最佳答案。谢谢@DavidPricop
  • 这和它有什么关系?问题不在于编码,而是值完全错误。
  • @Barmar 不,值没有错。我对其进行了测试,结果发现它与编码有关。因为大卫使用的是普通英文字母以外的其他字符
  • cookie 应该包含success。里面有什么特殊字符?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-25
  • 2015-07-13
相关资源
最近更新 更多