Hey, dev.to community,
I’m working on a PHP-based online shop and encountering a couple of issues in my onlineshop.php
script. I could use some guidance on how to resolve these problems. Here’s a summary of the issues I’m facing:
Context:
-
File Path:
/var/www/html/online_shop/public/onlineshop/onlineshop.php
- Issue: Images aren’t displaying correctly, and I’m receiving PHP warnings about undefined variables.
Code Snippet:
<?php
session_start();
include_once 'db_connect.php';
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Handle logout if logout parameter is set
if (isset($_GET['logout']) && $_GET['logout'] == 'true') {
$_SESSION = array();
session_destroy();
header("Location: onlineshop.php");
exit();
}
// Check if the user is logged in
if (isset($_SESSION['user_id'])) {
$navbar_links = '
<li class="nav-item">
<a class="nav-link" href="profile.php">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="onlineshop.php?logout=true">Logout</a>
</li>
';
} else {
$navbar_links = '
<li class="nav-item">
<a class="nav-link" href="login.php">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="register.php">Register</a>
</li>
';
}
// Fetch products from database
$sql_fetch_products = "SELECT * FROM products";
$result = $conn->query($sql_fetch_products);
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
$user_id = $_SESSION['user_id'];
// Fetch username based on user_id
$sql = $conn->prepare("SELECT username FROM users WHERE id = ?");
$sql->bind_param('i', $user_id);
$sql->execute();
$sql->bind_result($username);
$sql->fetch();
$sql->close();
// Fetch chat messages
$chat_query = "SELECT * FROM chat_messages WHERE sender='$username' OR receiver='$username' ORDER BY timestamp DESC";
$chat_result = $conn->query($chat_query);
// Handle sending chat messages
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['chat_message'])) {
$receiver = 'admin'; // Static value for admin
$message = $_POST['chat_message'];
$sender = $username;
$stmt = $conn->prepare("INSERT INTO chat_messages (sender, receiver, message) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $sender, $receiver, $message);
$stmt->execute();
$stmt->close();
header("Location: onlineshop.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online Shop</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Indonesian Product</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="onlineshop.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.php">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.php">Contact</a>
</li>
<?php echo $navbar_links; ?>
</ul>
</div>
</nav>
<div class="container">
<div class="marquee">
<marquee behavior="scroll" direction="left">Welcome to our Online Shop!</marquee>
</div>
</div>
<div class="container">
<h1 class="mt-4 mb-4">Products</h1>
<div class="card-columns">
<?php
if ($result && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<div class="card">';
echo '<a href="product_detail.php?product_id=' . $row['id'] . '">';
// Image path
$imagePath = '/online_shop/public/' . $row['image'];
echo 'Image Path: ' . $imagePath . '<br>';
// Verify if the file exists
if (file_exists('/var/www/html' . $imagePath)) {
echo 'File exists<br>';
} else {
echo 'File does not exist<br>';
}
// Display the image
echo '<img src="' . $imagePath . '" class="card-img-top" alt="Product Image">';
echo '<div class="card-body">';
echo '<h5 class="card-title">' . $row['name'] . '</h5>';
echo '<p class="card-text">' . $row['description'] . '</p>';
echo '<p class="card-text">Price: ' . $row['price'] . '</p>';
echo '</div>';
echo '</a>';
echo '</div>';
}
} else {
echo '<p>No products found.</p>';
}
?>
</div>
</div>
<!-- Chat Section -->
<div class="card">
<div class="card-header">Chat with Admin</div>
<div class="card-body">
<div class="chat-box" style="height: 300px; overflow-y: scroll;">
<?php while ($chat = $chat_result->fetch_assoc()) { ?>
<div>
<strong><?php echo htmlspecialchars($chat['sender']); ?>:</strong>
<span><?php echo htmlspecialchars($chat['message']); ?></span>
<small class="text-muted"><?php echo $chat['timestamp']; ?></small>
</div>
<?php } ?>
</div>
<form action="onlineshop.php" method="POST">
<div class="form-group">
<label for="chat_message">Message</label>
<textarea class="form-control" id="chat_message" name="chat_message" required></textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
</div>
<script>
$(document).ready(function() {
function checkNewMessages() {
$.ajax({
url: 'check_new_messages.php',
method: 'GET',
success: function(data) {
if (data.new_messages > 0) {
$('#chat-notification-count').text(data.new_messages);
} else {
$('#chat-notification-count').text('');
}
}
});
}
// Check for new messages every 5 seconds
setInterval(checkNewMessages, 5000);
});
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Issues:
Image Path Problem: The image path generated for displaying product images is incorrect. The URL is showing as
/photo_product/photo_product/Screenshot%202024-07-01%20080501.png
, which leads to a404 Not Found
error.PHP Warnings: I’m seeing warnings related to undefined variables and array offsets.
Questions:
- Image Path: How can I correct the image path to ensure that images are displayed properly?
- PHP Warnings: What steps can I take to resolve the warnings related to undefined variables and array offsets?
- Debugging Advice: Any suggestions on effective debugging techniques for these issues?
Any help or insights would be greatly appreciated. Thanks in advance!
Top comments (5)
I can see two things that may be the issue. Your image url's have %20 in them. That usually indicates there's a space in the filename. If your image filenames have spaces in them you may need to remove them (the actual image file names and in the database). I tend to replace all spaces with underscores. Secondly, the image file path begins with photo_product/photo_product. Are your images in a directory structure like that?
Hope that helps.
Hi David Miller,
Thank you for your suggestions. I’ve tried the following steps based on your recommendations:
Renamed Image Files: I replaced all spaces in the filenames with underscores, as you suggested. For example,
Screenshot 2024-07-01 080501.png
is nowScreenshot_2024-07-01_080501.png
. I also updated the filenames in the database to reflect these changes.Directory Structure Check: I verified the directory structure and confirmed that the images are located in
/var/www/html/online_shop/public/photo_product/
, not/var/www/html/online_shop/public/photo_product/photo_product/
. The URL should therefore be/photo_product/Screenshot_2024-07-01_080501.png
.Despite these adjustments, I am still encountering issues:
404 Not Found
error.Here are the details:
http://localhost/photo_product/Screenshot_2024-07-01_080501.png
/var/www/html/online_shop/public/photo_product/Screenshot_2024-07-01_080501.png
404 Not Found
or403 Forbidden
when trying to access the image.I have also checked the file permissions and confirmed that the Apache user (
www-data
) has read access to the directory and files.Do you have any further suggestions or troubleshooting steps I might have missed? I appreciate any additional guidance.
Thanks!
Use vscode and php debug
I used vs code and PHP to debug my project
thank you all for helping me I solve it with change the path to correct path