簡體   English   中英

PHP 未訪問 Javascript cookie

[英]PHP not accessing Javascript cookie

我正在創建一個小型 CRUD web 應用程序,當他們希望從數據庫中刪除項目時,我需要用戶輸入他們的密碼,我在HTML table的刪除按鈕上有一個onClick() ,它將產品的ID傳遞給將js刪除到function。 當 function 運行時,我希望確認他們確實想刪除產品,然后詢問他們的密碼並將其存儲在 cookie 中。 但它似乎不起作用:(

我正在使用 javascript 設置一個 cookie

document.cookie = 'password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php; 使用這行代碼,當我使用console.log(document.cookie)時,它會向我顯示控制台中的 cookie,例如

password=admin,expires=Sat, 12 Dec 2020 08:40:38 GMT,path=/../includes/delete-product.inc.php; PHPSESSID=3n1l3q6ksqitdpc76hjrero9ja

當我使用window.open()重定向到另一個 PHP 頁面時,我無法訪問此 cookie。

print_r($_COOKIE); <- only shows me the PHPSESSID only print_r($_COOKIE); <- only shows me the PHPSESSID only

當我明確嘗試使用以下行訪問 cookie 時$userPassword = $_COOKIE[password]; 它給了我undefined index 'password'

這是我的代碼。

myproject/admin/view-products.php (這是我嘗試使用javascript設置cookie的頁面)

function deletePrompt(id) {
      const now = new Date();
      const time = now.getTime();
      const expiresIn = time + (50 * 1000);
      now.setTime(expiresIn);
      const path = `../includes/delete-product.inc.php`;

      const intent = confirm("Are you sure you want to delete this products");
      if (intent === true) {
        const userPassword = prompt("Enter password");
        document.cookie = `password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php`;
        console.log(document.cookie);
        return;
        window.open(`../includes/delete-product.inc.php?id=${id}`, "_self");
      }
    }

myproject/includes/delete-product.inc.php (這是我需要訪問 cookie 的 PHP 頁面)

<?php
require_once "./database-connection.inc.php";
require_once "./functions.inc.php";

  if (isset($_SESSION["adminId"])) {
    $productId = $_GET["id"];
    $userPassword = $_COOKIE["password"];    //<- This throws undefined index error
    if (deleteProduct($connection, $productId, $userPassword)) {
      header("location: ../admin/view-products.php?msg=deleted");
      exit();
    }
    else {
      header("location: ../admin/view-products.php?msg=incorrectPass");
      exit();
    }
  }
  else {
    header("location: ../admin/login.php");
    exit();
  }

對於其他面臨此問題的人,解決方案是 cookies 不會跨目錄發送,因此如果您希望跨目錄傳輸 cookies ,則需要將收件人文件放在同一域中,否則將無法正常工作。 例如。 以下模式將起作用

youProject/someDirectory/file1
youProject/someDirectory/file2 

以下將不起作用

youProject/someDirectory/file1
youProject/someOtherDirectory/file2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM