WordPress.org

Make WordPress Core

Opened 2 years ago

#41946 new enhancement

Option to delete_with_markers

Reported by: shivi66 Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 4.8.2
Component: Rewrite Rules Keywords:
Focuses: Cc:
PR Number:

Description

I was trying to develop a plugin for adding speed optimisation code to htaccess using builtin functions . I happened to find options to insert_with_markers and extract_with_markers. But I found there was not a direct option to delete_with_markers. I tried searching as much as possible and finally came out with delete_with_markers myself which I have used in my plugin (which I will be submitting in a day for review).I have refered the insert_with_markers and extract_with_markers to retain the WP style. I thought to share , if this could be integrated in WP as well for it could be of use to many.

function delete_with_markers( $filename, $marker ) {

if ( ! file_exists( $filename ) ) {

if ( ! is_writable( dirname( $filename ) ) ) {

return false;

}
if ( ! touch( $filename ) ) {

return false;

}

} elseif ( ! is_writeable( $filename ) ) {

return false;

}



$start_marker = "# BEGIN {$marker}";
$end_marker = "# END {$marker}";


$fp = fopen( $filename, 'r+' );
if ( ! $fp ) {

return false;

}


Attempt to get a lock. If the filesystem supports locking, this will block until the lock is acquired.

flock( $fp, LOCK_EX );


$lines = array();
while ( ! feof( $fp ) ) {

$lines[] = rtrim( fgets( $fp ), "\r\n" );

}


if ( $markerdata = explode( "\n", implode( , file( $filename ) ) ));

{

$state = false;
foreach ( $markerdata as $markerline ) {

if (strpos($markerline, '# BEGIN ' . $marker) !== false)

$state = true;

if (! $state )
$result[] = $markerline;

if (strpos($markerline, '# END ' . $marker) !== false)

$state = false;


}

}



Generate the new file data

$new_file_data = implode( "\n", array_merge(

$result
) );


Write to the start of the file, and truncate it to that length

fseek( $fp, 0 );
$bytes = fwrite( $fp, $new_file_data );
if ( $bytes ) {

ftruncate( $fp, ftell( $fp ) );

}

fflush( $fp );

flock( $fp, LOCK_UN );

fclose( $fp );


return (bool) $bytes;

}

Attachments (1)

remove_with_markers.patch (2.4 KB) - added by sergiosanchez 4 months ago.
Added function remove_with_markers

Download all attachments as: .zip

Change History (1)

@sergiosanchez
4 months ago

Added function remove_with_markers

Note: See TracTickets for help on using tickets.