Security PHP Beginner

Add a security.txt File

Publish a security.txt file at /.well-known/security.txt so researchers know how to report vulnerabilities to you.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 13 lines
add_action( 'init', function (): void {
	$path = trim( (string) wp_parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ), '/' );
	if ( '.well-known/security.txt' !== $path ) {
		return;
	}

	header( 'Content-Type: text/plain; charset=utf-8' );
	echo "Contact: mailto:security@example.com\n";
	echo 'Expires: ' . ( (int) gmdate( 'Y' ) + 1 ) . "-12-31T23:59:59Z\n";
	echo "Preferred-Languages: en\n";
	echo 'Canonical: ' . esc_url_raw( home_url( '/.well-known/security.txt' ) ) . "\n";
	exit;
}, 0 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

When a security researcher finds a problem with your site, they look for /.well-known/security.txt to find out who to tell. Without it, reports often go nowhere. This snippet serves the file from WordPress, so you don’t need FTP access.

How it works

On init, the snippet checks the requested path. If it’s .well-known/security.txt, it prints a plain-text file in the format defined by RFC 9116 and stops. Every other request carries on as normal.

The Expires field is required. The snippet sets it to the end of next year, so it never goes stale.

Things to watch

  • Change the Contact address to one someone actually reads. You can add more lines, such as a Policy: link to your disclosure policy.
  • Some hosts serve /.well-known/ themselves for SSL certificate checks. If the URL shows a 404 from your web server, upload a real file there instead.

How to test it

Visit yoursite.com/.well-known/security.txt. You should see the four lines in plain text.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only