【问题标题】:Changing url inside file_get_contents everytime the php file being accessed每次访问 php 文件时更改 file_get_contents 中的 url
【发布时间】:2018-12-04 05:59:46
【问题描述】:

我需要帮助来创建简单的 php |每次访问 php 文件时更改 file_get_contents 中的 url

首次加载

<?php
$homepage = file_get_contents('http://www.example.com/page=1');
echo $homepage;
?>

每次页面加载时 url 都会发生变化(在这种情况下是页码 + 1)

第二次加载

<?php
$homepage = file_get_contents('http://www.example.com/page=2');
echo $homepage;
?>

第三次加载

<?php
$homepage = file_get_contents('http://www.example.com/page=3');
echo $homepage;
?>

等等

谁能帮帮我?

【问题讨论】:

  • 将之前的计数器值存储在.txt 文件中。从.txt 文件中读取计数器并将其递增。然后点击file_get_contents。最后fwrite当前计数器值再次出现在同一个文件中。
  • 你能给我这个场景的 php 代码示例吗?
  • 这个页面是否一次可以被多人访问?如果是这样,使用文本文件将不起作用,因为多个进程可能试图同时写入同一个文件。如果只有一个人访问它,那么你会没事的。
  • 如果该页面一次被多人访问,还有什么办法?

标签: php url file-get-contents


【解决方案1】:

您可以通过在txt 文件中维护计数器来实现此目的。在运行此过程之前创建一个目录(根据我的示例命名计数器)和一个空文件 c.txt。我们可以检查文件是否不存在,然后创建一个文件。但是在您的情况下,它似乎被更频繁地调用,因此可以避免在这里进行额外的处理。

这里是代码sn-p,

// File where counter will be maintained. Change the path to the one desired
$filename = "/root/Desktop/counter/c.txt";
$handle = fopen($filename, "r"); // Open the file in read mode
$counter = fread($handle, filesize($filename)); //Read the file
fclose($handle); // Close file object

// Increment the counter if available else set it to 1
$count = !empty($counter) ? (int)$counter+1 : 1;

$homepage = file_get_contents("http://www.example.com/page=$count");
echo $homepage;

$handle = fopen($filename, "w"); // Open the file in write truncate mode
fwrite($handle, $count); // Store the counter in the file
fclose($handle); // Close file object

【讨论】:

  • 感谢您的回答,但是当我访问 php 时,它在 c.txt 1 1 中的每一行都放置了相同的数字
  • 你太棒了。谢谢你
  • 不客气。如果有帮助,请投票并接受答案。快乐编码:)
  • 我尝试支持投票,但它显示“声望低于 125 的投票已记录,但不要更改公开显示的发布分数。”再次感谢您。
  • 谢谢。但请注意@ryantxr cmets 也涉及单个或多个用户。我提供了解决方案,记住它是一个进程/cron。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多