[wp-trac] [WordPress Trac] #41946: Option to delete_with_markers
WordPress Trac
noreply at wordpress.org
Thu Sep 21 18:14:49 UTC 2017
#41946: Option to delete_with_markers
---------------------------+-----------------------------
Reporter: shivi66 | Owner:
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Rewrite Rules | Version: 4.8.2
Severity: normal | Keywords:
Focuses: |
---------------------------+-----------------------------
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;
}
--
Ticket URL: <https://core.trac.wordpress.org/ticket/41946>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list