From time to time problems appear. mySQL server crashes, some error in a sql query might think it’s time to show her ugly face and in top of all that, the all mighty Google comes to index your page. And when he does, he indexes a page that presents an error or a blank page. How can we stop him from indexing that page? With a header 500 error.
The header 500 error or “Internal Server Error” means that the server has a nasty indigestion and the search engine should come back later to see the page in all it’s splendor. And that’s exactly what it will do. So, how do we trigger that error?
Most scripts use the mysql_query(“some sql”)or die(mysql_error()) sintax. Well, that’s ok because in case of an error, the script stops and the error appears so the debug process can begin. The only problem is that if some error appears, it will be indexed by search engines.
The solution is to use instead of mysql_error() a custom function like the one below.
1 2 3 4 5 6 7 8 9 10 11 | function generate_error($sql='',$debug=false) { header("HTTP/1.0 500 Internal Server Error"); if($debug) { echo "<p>"; echo mysql_error(); echo "<br />".$sql; echo "</p>"; } } |
… and the usage would be something like
1 2 3 4 5 6 7 8 9 10 | $server='localhost'; $user='root'; $password=''; $database='test'; mysql_connect($server,$user,$password) or die(generate_error()); mysql_select_db($database)or die(generate_error()); $sql="SELECT * FROM some_table"; mysql_query($query)or die(generate_error($sql)); |
The only thing you have to be careful about is where exactly in your page you put your mysql_…() functions. If any output is sent to the browser before the error header is triggered, the header will be 200 OK and a headers already sent error will appear. As a consequence to that, your page will be indexed and you’ll be back from where you started. If you want to avoid that, you either put all the queries before any output is sent to the browser or use the ob_start() function on the first line of your document.






1 comment
Excellent! just what I needed, its pretty easy to do when using a MVC pattern and custom Exception handling.
Leave a comment