如何在不并发问题的情况下替换PHP文件的内容


how to replace content of a file in php with out concurrency issues

我想添加一个HTML属性id="active"用于left.php

left.php应该只有一个链接id="active"

下面的代码实际上是按照我的要求工作的,但是过了一会儿,由于并发问题,left.php的内容完全丢失了

如何解决这个问题?

我认为我们可以有一个java脚本解决方案来处理这个在客户端。请用例子告诉我最好的解决方案。

谢谢大家。

<?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');
?>  

我认为你正在尝试将当前页面的链接设置为活动。在这种情况下,你做错了。所有的逻辑必须在left.php文件中。你可以这样做:

$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>';
}

现在你所要做的就是在你想要显示这些链接的地方包含left.php文件

代替file_put_contents并包含try eval。然后,您将跳过编写文件并将其用作模板。

在下一个版本中,请尝试使用过程或OOP。

我在客户端添加了下面的脚本在我的left.php的末尾。

它正在工作,我认为这是一个很好的解决方案,最好的性能。谢谢你。

<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>