dtxw20878 2017-09-25 09:01
浏览 82
已采纳

基于文本文件的顺序URL旋转器无法正常工作

I'm trying to create a text file-based sequential url rotator by using the following code (original source):

<?php
$linksfile ="urlrotator.txt";
$posfile = "pos.txt";

$links = file($linksfile);
$numlinks = count($linksfile);

$fp = fopen($posfile, 'r+') or die("Failed to open posfile");
flock($fp, LOCK_EX);
$num = fread($fp, 1024);
if($num<$numlinks-1) {
  fwrite($fp, $num+1);
} else {
  fwrite($fp, 0);
}
flock($fp, LOCK_UN);
fclose($fp);

header("Location: {$links[$num]}");
?>

After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.

I tried adding the following line of code before the if else statement in order to clear the existing content of pos.txt before updating it.

file_put_contents($posfile, "");

But then error ocurred at the line of redirection saying Undefined index: ...... .

Where could possibly go wrong?

  • 写回答

1条回答 默认 最新

  • doubiankang2845 2017-09-25 09:36
    关注

    I believe your problem comes from the mode you are using. When you say

    After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.

    it points me to the mode usage of fopen.

    The mode you should use is w, as it will "replace" the content of what is inside pos.txt.

    $fp = fopen($posfile, 'w') or die("Failed to open posfile");
    

    Doing so will prevent your from accessing what was in pos.txt. So you need to have something like this:

    $num = file_get_contents($posfile);
    $fp = fopen($posfile, 'w') or die("Failed to open posfile");
    flock($fp, LOCK_EX);
    if($num<$numlinks-1) {
      fwrite($fp, $num+1);
    } else {
      fwrite($fp, 0);
    }
    flock($fp, LOCK_UN);
    fclose($fp);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写