dongyi5570 2015-10-06 07:09
浏览 80

如何在没有并发问题的情况下替换php中文件的内容

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');
?>  
  • 写回答

3条回答 默认 最新

  • dongzuo7166 2015-10-06 07:30
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?