I want to append an HTML attribute id="active" for a link of left.php
left.php should have only one link with id="active"
The below code is actually working as per my requirement, but after a while the content of left.php is totally missing due to concurrency issues.
How can I resolve the issue?
I think we can have a java script solution for this to handle at client side. Please let me know the best solution with example.
Thank you all.
<?php
$searchF1 = ' id="active"';
$replaceW1 = '';
$searchF = basename(__FILE__).'"';
$replaceW = $searchF.' id="active"';
$myfile = fopen( 'left.php', 'rt' );
flock( $myfile, LOCK_SH );
$file = file_get_contents( 'left.php' );
fclose( $myfile );
$file = str_replace( $searchF1, $replaceW1, $file );
$file = str_replace( $searchF, $replaceW, $file );
file_put_contents('left.php', $file);
include('left.php');
?>
I think you are trying to set the link of the current page as active. In this case you are doing it wrong. All the logic must be inside the left.php
file. You can do it like this:
$pages = array(
'firstPage.php' => 'First Page',
'secondPage.php' => 'Second Page',
'thirdPage.php' => 'Third Page',
);
$currentParsedUrl = parse_url("http://$_SERVER[SERVER_NAME]$_SERVER[REQUEST_URI]");
$currentPath = ltrim($currentParsedUrl['path'], '/');
foreach ($pages as $path => $name) {
echo '<a href="/' . $path . '"';
echo $currentPath == $path ? ' id="active"' : '';
echo '>' . $name . '</a>';
}
Now all you have to do is to include the left.php
file wherever you want to display those links.
instead of file_put_contents and include try eval. Then you'll skip writting the file and use it as a template.
In the next version please try to use procedures or OOP.
I did it with client side by adding the below script at the end of my left.php.
It is working, I think it is a good solution for the best performance. Thank you.
<script>
var name = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
var pattern = /.php/;
var exists = pattern.test(name);
if(exists){ $('a[href$="'+name+'"]').css('font-weight', 'bold');}
else{ $('#left').find('a:first').css('font-weight', 'bold');}
</script>