Skip to content

Instantly share code, notes, and snippets.

@Digiover
Last active January 15, 2022 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Digiover/2e109c1506135fc6f96fb8e0cf08af4f to your computer and use it in GitHub Desktop.
Save Digiover/2e109c1506135fc6f96fb8e0cf08af4f to your computer and use it in GitHub Desktop.
Function to disable PHP script execution for WordPress wp-content/uploads folder
<?php
/**
* Disable PHP script execution for WordPress wp-content/uploads folder.
* - based off the WordPress permalinks rewrite code
*
* - https://www.saotn.org/secure-wordpress-uploads-folder-disable-php-execution/
* - follow me on twitter: @Jan_Reilink
*
* don't allow this file to be loaded directly
*/
if ( ! function_exists( 'add_action' ) ) {
exit;
}
function disable_script_execution() {
global $iis7;
$path = WP_CONTENT_DIR . 'uploads';
$filename = 'web.config';
if ( $is_iis7 ) {
if ( ! file_exists( $path . '/' . $filename ) ) {
$fp = fopen( $path . '/' . $filename, 'w' );
fwrite( $fp, '<configuration/>' );
fclose( $fp );
}
$formatxml = PHP_EOL;
$formatxml .= " <handlers accessPolicy=\"Read\" />";
$formatxml .= PHP_EOL;
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
if( $doc->load( $path . '/' . $filename ) === false ) {
return false;
}
$xpath = new DOMXPath( $doc );
$read_accesspolicy = $xpath->query( '/configuration/system.webServer/handlers[starts-with(@accessPolicy,\'Read\')]' );
if( $read_accesspolicy->length > 0 ) {
return true;
}
$xmlnodes = $xpath->query( '/configuration/system.webServer' );
if ( $xmlnodes->length > 0 ) {
$handlers_node = $xmlnodes->item(0);
}
else {
$handlers_node = $doc->createElement( 'handlers' );
$xmlnodes = $xpath->query( '/configuration/system.webServer' );
if ( $xmlnodes->length > 0 ) {
$system_webServer_node = $xmlnodes->item(0);
$handler_fragment = $doc->createDocumentFragment();
$rule_fragment->appendXML( $formatxml );
$system_webServer_node->appendChild( $rule_fragment );
}
else {
$system_webServer_node = $doc->createElement( 'system.webServer' );
$rule_fragment = $doc->createDocumentFragment();
$rule_fragment->appendXML( $formatxml );
$system_webServer_node->appendChild( $rule_fragment );
$xmlnodes = $xpath->query( '/configuration' );
if ( $xmlnodes->length > 0 ) {
$config_node = $xmlnodes->item(0);
$config_node->appendChild( $system_webServer_node );
}
else {
$config_node = $doc->createElement( 'configuration' );
$doc->appendChild( $config_node );
$config_node->appendChild( $system_webServer_node );
}
}
}
$doc->encoding = "UTF-8";
$doc->formatOutput = true;
$doc->save( $path .'/'. $filename );
return true;
}
}
disable_script_execution();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment