php-generated 503

How To Return Status Codes In PHP

Status codes, the status of a p[age being requested from a web server can be generated in a number of different ways. Here we show you how this is done in PHP code – a language that can be used to generate HTML web pages directly.

When browsing the internet as a user, you are probably unaware of the secret messaging that is being sent back and forth between where the website is being hosted and your browser.

For example, domain names are actually a series of numerical combinations. Status codes are similar in that they give information about if a page has loaded successfully or not, and the root cause of any errors. PHP is a scripting language that can generate status-code data.

While your content management system, possibly (WordPress) and your web server (possibly Apache) can generate these codes, the scripting language PHP, which is the basis of WordPress, can also generate these codes.

Why use PHP to generate status codes?

PHP is the language that WordPress is built on. If you are thinking of adapting your WordPress theme, or even writing additional pages using PHP, you might want to use status codes to return a positive status code, to redirect the request to another page or site, or to advise that a page is not available. For example, you have deleted a lot of content and you want to provide a special landing page to tell robots and users that this specific content has been removed, and why. Or, you may want to write a simple PHP script to tell users when the site is under maintenance.

Читайте также:  Html css default image

What are Status Codes?

HTTP status codes are a way that servers communicate with clients (browsers). For the most part, the page loads successfully and so an ‘ok’ 2xx code will be generated. In such a case, status codes remain invisible to the user. But status codes are there to cover all eventualities, such as a 404 error or even a 502 bad gateway, which will be visually displayed on the page as an error message.

Understanding status codes will allow you to enhance your user experience, especially if your website visitors are receiving error codes that originate from your server as an example.

As the practice is quite technical, status codes are usually implemented manually by someone who understands coding such as a web developer. However, if your website is on WordPress, then plugins do exist to help you make sense and implement status codes.

Of course, as a website user, you may also come across status codes on other websites too. For example, 403 forbidden can be generated if you try to access a section of a website that you don’t have permission to view.

HTTP Status Code Types – Overview

  • 1xx informational response
  • 2xx success
  • 3xx redirection
  • 4xx client errors
  • 5xx server errors
  • Unofficial status codes

PHP – An Overview

PHP stands for hypertext preprocessor. As you may have noticed, the acronym is a little confusing and that’s because PHP originally stood for personal home page. Remember, the way we develop websites has changed immensely in the short time the internet has existed, so sometimes terms need to be updated to keep up to modern standards.

Whenever you request a URL, a complex chain occurs between the server and the browser. PHP is usually involved in this process, as it’s responsible for interpreting the data. A common example of where you would see PHP in action is a login page. As you enter your credentials, a request to the server is made, and PHP will communicate with the database to log you in.

Essentially, PHP is a scripting language that is embedded into HTML. For a quick example, left click on any webpage and select ‘view page source’. Doing so will bring up the code that makes up that page. It is your browser that interprets the code into the functional version of the website.

With PHP, code can either be processed client side (HTML, Javascript and CSS) or server side (PHP). In essence, the server side of PHP is software that is installed on the server. This software can include Linux, Apache, MySQL and finally PHP. In that order, these 4 elements make up what’s known as a LAMP stack. The PHP is the scripting layer of this combination which websites and web applications run off.

Returning A Status Code In PHP

example 404 page

To return a status code in PHP, the simplest way is to use the http_response_code() function, along with the relevant HTTP status code parameter into your website, followed by the exit() command which stops any more output being set.

This means the likes of 400 bad requests and 404 not found can all be implemented with just one line of code.

Important: The http_response_code and header() commands must be used before any HTML is returned.

Example: Return a 400 bad request status code

http_response_code(400); exit;

Example: Return a 404 not found status code

http_response_code(404); exit;

Example: Return a 301 moved permanently status code

This example php code also requires that you provide the new URL, to which the users browser will automatically redirect. For this you need to use the more details header() function.

http_response_code(301); header('Location: /newlocation.html'); exit;

The exit command means that no other php code or html code will be output from the page.

Here’s example code for a 503 temporary error page that also includes additional information that is shown in the browser.

      This is a 503 error page. 
The error is returned in the HTTP header and this is just simple HTML that is displayed in the browser.

Why Status Codes Matters For SEO

As the name suggests, SEO is all about catering to search engines, so that users are more likely to come across your site. Search engines actively crawl status codes and will determine how your site is indexed as a result.

For example, if your site has plenty of 404 errors that exist from internal or external, links then this can harm your rankings because this will not generate a helpful experience for users. In a nutshell, search engines are looking out for healthy status codes, as this indicates everything is ticking over as it should be.

Further Reading

The above gives a brief overview of returning status codes in PHP. However, given the complex nature of coding it’s impossible to cover everything in just one article alone. So we definitely suggest doing some further reading to increase your understanding.

Resources you may find helpful include the official PHP website. In particular, their Using PHP section covers common errors you may encounter, especially as you get to grips with it.

Remember, when building any code it’s essential to test it. Even a small error or even a bug can disrupt the final result, so it’s good to remember that PHP isn’t just about the writing of the script, but seeing it through to a working page. Plus, looking out for any errors that may occur further down the line.

Источник

header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include , or require , functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.


/* This will give an error. Note the output
* above, which is before the header() call */
header ( ‘Location: http://www.example.com/’ );
exit;
?>

Parameters

There are two special-case header calls. The first is a header that starts with the string » HTTP/ » (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

// This example illustrates the «HTTP/» special case
// Better alternatives in typical use cases include:
// 1. header($_SERVER[«SERVER_PROTOCOL»] . » 404 Not Found»);
// (to override http status messages for clients that are still using HTTP/1.0)
// 2. http_response_code(404); (to use the default message)
header ( «HTTP/1.1 404 Not Found» );
?>

The second special case is the «Location:» header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

header ( «Location: http://www.example.com/» ); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in false as the second argument you can force multiple headers of the same type. For example:

Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the header is not empty.

Return Values

Errors/Exceptions

On failure to schedule the header to be sent, header() issues an E_WARNING level error.

Examples

Example #1 Download dialog

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

// We’ll be outputting a PDF
header ( ‘Content-Type: application/pdf’ );

// It will be called downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );

// The PDF source is in original.pdf
readfile ( ‘original.pdf’ );
?>

Example #2 Caching directives

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:

header ( «Cache-Control: no-cache, must-revalidate» ); // HTTP/1.1
header ( «Expires: Sat, 26 Jul 1997 05:00:00 GMT» ); // Date in the past
?>

Note:

You may find that your pages aren’t cached even if you don’t output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

Note:

You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

Note:

The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

Note:

Most contemporary clients accept relative URI s as argument to » Location:, but some older clients require an absolute URI including the scheme, hostname and absolute path. You can usually use $_SERVER[‘HTTP_HOST’] , $_SERVER[‘PHP_SELF’] and dirname() to make an absolute URI from a relative one yourself:

/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER [ ‘HTTP_HOST’ ];
$uri = rtrim ( dirname ( $_SERVER [ ‘PHP_SELF’ ]), ‘/\\’ );
$extra = ‘mypage.php’ ;
header ( «Location: http:// $host$uri / $extra » );
exit;
?>

Note:

Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

See Also

  • headers_sent() — Checks if or where headers have been sent
  • setcookie() — Send a cookie
  • http_response_code() — Get or Set the HTTP response code
  • header_remove() — Remove previously set headers
  • headers_list() — Returns a list of response headers sent (or ready to send)
  • The section on HTTP authentication
  • Network Functions
    • checkdnsrr
    • closelog
    • dns_​check_​record
    • dns_​get_​mx
    • dns_​get_​record
    • fsockopen
    • gethostbyaddr
    • gethostbyname
    • gethostbynamel
    • gethostname
    • getmxrr
    • getprotobyname
    • getprotobynumber
    • getservbyname
    • getservbyport
    • header_​register_​callback
    • header_​remove
    • header
    • headers_​list
    • headers_​sent
    • http_​response_​code
    • inet_​ntop
    • inet_​pton
    • ip2long
    • long2ip
    • net_​get_​interfaces
    • openlog
    • pfsockopen
    • setcookie
    • setrawcookie
    • socket_​get_​status
    • socket_​set_​blocking
    • socket_​set_​timeout
    • syslog

    Источник

Оцените статью