Development Tools Using PHP with MySQL Filtering Input for Queries Preparing SQL Statements

Radha Bhambwani
Radha Bhambwani
10,182 Points

When entering invalid sku, I'm not redirected to shirts.php

I was having some troubles when entering invalid sku/product_id like 202, it wasnn't redirecting me to shirts.php. When I entered a valid sku I was getting the corresponding shirt page but when I entered an invalid sku I was getting this error:

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/project02-stage08-shirts4mike/inc/products.php:373) in /Applications/MAMP/htdocs/project02-stage08-shirts4mike/shirts/shirt.php on line 17

So I checked out shirt.php and noticed that the code around line 17 looked right:

if (empty($product)) {
    header("Location: " . BASE_URL . "shirts/");
    exit();
}

After much confusion and debugging, I noticed that in products.php I had a closing php tag. When I removed that closing php tag, somehow it fixed the invalid sku problem and I was directed to the shirts.php page.

My problem is solved but I'm not sure how or why removing the closing tag made any difference at all. If anything, I thought that closing php tags are just good coding practice.

Zachary Green
Zachary Green
16,359 Points

Maybe when you closed you php tag in products.php the server was outputing headers because the php script was explicitly closed. As you already know headers (just like email/postmail) you cant change anything after its sent to the browser. As far as closing php tags I have found a lot of developers dont close tags on a page that has all php code. May be because of this problem.

Hugo Paz
Hugo Paz
15,619 Points

Hi Radha,

Perhaps you had a blank line after a closing php tag ?

This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls.

Since you removed it, you no longer will have this issue. Its one of the reasons developers dont close php tags.

2 Answers

Radha Bhambwani
Radha Bhambwani
10,182 Points

Thanks! that seemed to be the problem indeed. I had 2 blank lines after the closing tag. Once I got rid of those, it worked just fine.

The shirts.php goes to Index of /shirts directory any suggestion .