Да, я знаю, что подобный вопрос задавался уже > 1000 раз, и тем не менее я столкнулся с проблемой, когда сессия пропадает после вызова header();
.Я прочитал множество решений, но ни одно из них не помогло (например: https://stackoverflow.com/questions/17242346/php-session-lost-after-redirect ) Я делаю простенькую корзину, которая после нажатия Купить, заносит в сессию id товара и снова загружает страницу. Я перепробовал огромное количество вариантов, но ни один не помог.
Все файлы в кодировке UTF-8.
Нет echo
.
session_start();
в начале php-файла.
index.php
<?php
session_start();
//ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//echo "path: ".ini_get('session.cookie_path');
//include_once $_SERVER['DOCUMENT_ROOT'] . '/test_cart/includes/magicquotes.inc.php';
$items = array(
array('id' => '1', 'desc' => 'Item 1', 'price' => 24.95),
array('id' => '2', 'desc' => 'Item 2', 'price' => 1000),
array('id' => '3', 'desc' => 'Goldfish (2 CD)', 'price' => 19.99),
array('id' => '14', 'desc' => 'JavaScript (SitePoint)', 'price' => 39.95));
if (!isset($_SESSI0N['cart'])) {
//echo "Init Cart";
$_SESSION['cart'] = array();
}
if (isset($_POST['action']) and $_POST['action'] == 'Buy') {
array_push($_SESSION['cart'], $_POST['id']);
header('Location: .');
die();
exit();
}
if (isset($_POST['action']) and $_POST['action'] == 'Claer') {
unset($_SESSION['cart']);
session_regenerate_id(true);
header('Location: .');
exit();
}
if (isset($_GET['cart'])) {
session_start();
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id) {
foreach ($items as $product) {
if ($product['id'] == $id) {
$cart[] = $product;
$total += $product['price'];
break;
}
}
}
include 'cart.html.php';
exit();
}
include 'catalog.html.php';
catalog.html.php
<?php
session_start();
function html($text) {
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text) {
echo html($text);
} ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Catalog</title>
<style>
table {
border-collapse: collapse;
}
td, th {
border:1px solid;
}
</style>
</head>
<body>
<p>Cart:<?php
echo count($_SESSION['cart']); ?> items.</p>
<p><a href="?cart">View Cart</a></p>
<table border="l">
<thead>
<tr>
<th>Info</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td><?php htmlout ($item['desc']); ?></td>
<td>
$<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<form action="" method="post">
<div>
<input type="hidden" name="id" value="<?php htmlout($item['id']); ?>">
<input type="submit" name="action" value="Buy">
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
cart.html.php
<?php
session_start();
//ob_start();
function html($text) {
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text) {
echo html($text);
} ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cart</title>
<style>
table {
border-collapse: collapse;
}
td, th {
border:1px solid black;
}
</style>
</head>
<body>
<h1>My Cart</h1>
<?php if (count($cart) >0): ?>
<table>
<thead>
<tr>
<th>Info</th>
<th>Price</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Total:</td>
<td>$<?php echo number_format($total, 2); ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach ($cart as $item): ?>
<tr>
<td><?php htmlout ($item['desc']); ?></td>
<td>
$<?php echo number_format($item['price'], 2); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>Cart empty!</p>
<?php endif; ?>
<form action="?" method="post">
<p>
<a href="?">Continue shopping</a>
<input type="submit" name="action" value="Empty cart">
</p>
</form>
</body>
</html>
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
Виртуальный выделенный сервер (VDS) становится отличным выбором
Есть форма поиска: