-2

I have this php script (test.php) which checks whether the page exists in mysql and it should return 404 status header but it returns 200 OK status. This causes soft 404 errors in console.

I tried to fix but it is simply not working. Here is my .htaccess. I migrated my site to SSL few months ago and i am redirecting all traffic to https from port 80.

RewriteEngine On
ErrorDocument 404 /404.shtml

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

RewriteEngine on
RewriteRule ^([0-9]+)-([0-9]+)-([0-9]+)/pressrelease([0-9]+)\.htm$ test.php?pressid=$4 [L]

and here is my test.php

<?php 
include_once('dbc.php');       

$pid = strip_tags(mysql_real_escape_string($_GET['pressid']));

$rs_dirs = mysql_query("select id,name from categories order by name") or die(mysql_error());

$rs_press = mysql_query("select *
                             from press 
                             where id = '$pid'
                             and approved='1'
                             ") or die(mysql_error());;

$total = mysql_num_rows($rs_press);


if (mysql_num_rows($rs_press) == 0) {

header("HTTP/1.1 404 Not Found");
include '404.shtml';
die();
}

What is the problem here and how do i fix it?

shushu304
  • 1,506
  • 1
  • 7
  • 15
pbu
  • 2,982
  • 8
  • 44
  • 68
  • 1
    [**Please, don't use `mysql_*` functions in new code**](https://stackoverflow.com/q/12859942). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://uk.php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which. – Machavity Dec 08 '17 at 19:16

2 Answers2

2

You are not setting the actual status code to 404.

See usage of the header function:

http://php.net/manual/en/function.header.php

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

Your code should be:

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);

There is also an alternative function:

https://secure.php.net/manual/en/function.http-response-code.php

http_response_code(404);

I prefer to use the above function instead. As it's more verbose as to what your intention way.

Reactgular
  • 52,335
  • 19
  • 158
  • 208
0

Use this code in your code:

if (mysql_num_rows($rs_press) == 0) {
   http_response_code(404);
   //and another staff here
}
Javid Karimov
  • 435
  • 5
  • 22