I am trying to use a visitor count. I have made it so it works without flock, but are trying to make it work with flock. I don't really understand where I should use flock, but have tried implement it in a file called VisitorCount. Now I don't get any result and the website turns blank.
What should I think about when using flock?
<?php
require "visitorCount.php";
incrementVisitorCount();
header("Content-Type: text/plain");
echo getVisitorCount();
?>
<?php
$file = fopen("visitor-count.txt", "w+");
function incrementVisitorCount() {
$visitorCount = getVisitorCount();
if(flock($file, LOCK_EX)) {
file_put_contents("visitor-count.txt", $visitorCount + 1);
fflush($file);
flock($file, LOCK_UN);
} else {
echo "Couldn't get the lock!";
}
fclose($file);
}
function getVisitorCount() {
$visitorCount = trim(file_get_contents("visitor-count.txt"));
return $visitorCount;
}
?>
Related
As you can see in the code below, I'm trying to use flock to prevent other clients to acess the php (actually multiple users will acess this something like 10 times per second, each one), as I've found searching here... But this is not working. My data.txt is getting blank everytime doing this.
<?php
$fileName = $_GET["room"]."/data.txt";
function replaceLine($data){
if (stristr($data, $_GET["player"])){
return $_GET["player"]." ".$_GET["data"]."\n";
}
return $data;
}
$file = fopen($fileName,"r");
if (flock($file, LOCK_EX)){
//ftruncate($file, 0);
///--------------
$data = file($fileName);
$data = array_map("replaceLine", $data);
file_put_contents($fileName, implode('', $data));
echo fread($file, filesize($fileName)+1);
///--------------
fflush($file);
flock($file, LOCK_UN);
} else {
echo "wait";
}
fclose($file);
?>
This is the original code (that I was trying to modify to prevent making the file empty): (It works as I want, but have this file problem...)
<?php
$fileName = $_GET["room"]."/data.txt";
function replaceLine($data){
if (stristr($data, $_GET["player"])){
return $_GET["player"]." ".$_GET["data"]."\n";
}
return $data;
}
$data = file($fileName);
$data = array_map("replaceLine", $data);
file_put_contents($fileName, implode('', $data));
$file = fopen($fileName,"r");
echo fread($file, filesize($fileName)+1);
fclose($file);
?>
Sorry for asking this newbie question, but I have not idea how to fix this and I'm searching and trying different things for weeks! Thanks!
You are opening the file for read only and then you are attempting to write to that same file. Try setting the fopen parameter to read/write.
$file = fopen($fileName,"r+");
I would also use fwrite() instead of file_put_contents() since you already have the file pointer and opening it again will likely be denied by the lock.
when this sample web page loads, it checks cached file from /cache folder. If there is no cached file, it calls ob_start() and creates a .html cache file. Problem is this caching process is working everytime even I have not called ob_start(). Please advise me. Thank you.
// class file
function check_cache($dynamic_url) {
$cache_file = $this->cache_folder.md5($dynamic_url).$this->cache_ext;
if ((file_exists($cache_file)) && (time() - $this->cache_time < filemtime($cache_file))) {
// ob_start('ob_gzhandler');
readfile($cache_file);
ob_end_flush();
exit();
}
else {
//ob_start('ob_gzhandler');
}
}
function create_cache($dynamic_url) {
$cache_file = $this->cache_folder.md5($dynamic_url).$this->cache_ext;
$fp = fopen($cache_file, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}
and I call this class from
$cache->check_cache(get_full_url());
<h1>Today is <?php echo date('Y-m-d h:i:s'); ?></h1>
$cache->create_cache(get_full_url());
I think that your cache is still created because of your create_cache calling fopen no matter what the output buffer is started or not. Therefore, should check your output buffer status before do fopen, as follows:
function create_cache($dynamic_url) {
if (ob_get_level() > 0) {
$cache_file = $this->cache_folder.md5($dynamic_url).$this->cache_ext;
$fp = fopen($cache_file, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}
}
You can use ob_get_level or ob_get_status: http://php.net/manual/en/function.ob-get-status.php
i have a zip file and user can only access the file once they complete their payment and i am using paypal payment gateway,so i have applied the condition that the download link will only be visible to user once they have completed their transaction,but my requirement id this that user must not be able to open this zip file through url,but once they complete their transaction then the user can download the file from the link given by me 1.e
Download Zip, i have hosted my website on godaddy.
<?php
session_start();
if(isset($_SESSION['item_name']) && $_SESSION['item_name']!=''){
if($_SESSION['item_name']=='Android Apps'){
?>
Download Zip
<?php }
} else{
header('Location: abc.com/rrr/form1.html');
}
?>
use the following methods in your code. this way you don't need to redirect the user to the real url of zip file. you can serve the zip from any php script e.g. your payment confirmation page can redirect to a script with a random token which expires after first download/time-
//call this method for sending download file.
function sendDL($filename)
{
header("Content-length:".filesize($filename));
header('Content-Type: application/x-gzip'); // ZIP file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="download.gz"');
header('Content-Transfer-Encoding: binary');
ob_end_clean(); //output buffer cleanup
_readfileChunked($filename);
}
function _readfileChunked($filename, $retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
consider these like utility methods. from any script which doesn't push any other out (ie. no echo) the first method can be used for sending a file to user. call that like this
<?php
$dlToken = $_GET['dltoken'];
$filename = '/path/to/secret.file';
//Check if this dlToken is in database/memcache or not. and if yes its expired or not.
if($yes)
{
sendDL($filename);
}
else
{
sendNack();
}
function sendNack()
{
echo '___DATA_NOT_FOUND___'; //NOTICE this is the only echo in this script. and it means we are not sending the file after all.
//header("HTTP/1.0 404 Not Found");
exit();
}
//put the two methods there
function sendDL($filename)
{
//...
}
function _readfileChunked($filename, $retbytes=true)
{
//...
}
?>
At the page/script where you give the download link. generate a random unique token. you can use uniqid or mt_rand or both. save this in database along with a timestamp value (which you can use in download script mentioned above to check if the token has expired). create a download url with that token as something like following
download.php?file=test.zip&token=the_unique_token×tamp=unix_timestamp
I have a form from which I save the given input into a textfile,
but I have trouble reading from the saved file:
while(!feof($fileNotizen)) {
$rawLine = fgets($fileNotizen);
if($rawLine==false) {
echo "An error occured while reading the file";
}
$rawLine seems to be always false, even though I use this function before, to fill the textfile:
function addToTable($notizFile) {
fwrite($notizFile, $_POST["vorname"]." ".$_POST["nachname"]."#");
$date = date(DATE_RFC850);
fwrite($notizFile, $date."#");
fwrite($notizFile, $_POST["notiz"].PHP_EOL);
}
And after I submit the form and get the error message, if I check the textfile, everything is there, so the function works correctly.
If it is of value, I open the file with this command:
$fileNotizen = fopen("notizen.txt", "a+");
Could the problem be that the pointer is already at the end of the file and thus returns false?
$fileNotizen = fopen("notizen.txt", "a+");
a+ opens for read/write but places file pointer AT THE END. So you must fseek() to the beginning first or look into fopen() flags and choose more wisely based on your needs.
Use fseek($fileNotizen, 0, SEEK_SET); to rewind the file.
To read/get content of the file try this function:
function read_file($file_name) {
if (is_readable($file_name)) {
$handle = fopen($file_name, "r");
while (!feof($handle)) {
$content .= fgets($handle);
}
return !empty($content) ? $content : "Empty file..";
} else {
return "This file is not readable.";
}
}
and if you want to see content of the file displayed on separate lines then use <pre></pre> tag like this:
echo "<pre>" . read_file("notizen.txt") . "</pre>";
and if you want to write/add content to the file then try this function:
function write_file($file_name, $content) {
if (file_exists($file_name) && is_writable($file_name)) {
$handle = fopen($file_name, "a");
fwrite($handle, $content . "\n");
fclose($handle);
}
}
and you can use it like this:
$content = "{$_POST["vorname"]} {$_POST["nachname"]}#" . date(DATE_RFC850) . "#{$_POST["notiz"]}";
write_file("notizen.txt", $content);
I want to make movement such as the tail command with PHP,
but how may watch append to the file?
I don't believe that there's some magical way to do it. You just have to continuously poll the file size and output any new data. This is actually quite easy, and the only real thing to watch out for is that file sizes and other stat data is cached in php. The solution to this is to call clearstatcache() before outputting any data.
Here's a quick sample, that doesn't include any error handling:
function follow($file)
{
$size = 0;
while (true) {
clearstatcache();
$currentSize = filesize($file);
if ($size == $currentSize) {
usleep(100);
continue;
}
$fh = fopen($file, "r");
fseek($fh, $size);
while ($d = fgets($fh)) {
echo $d;
}
fclose($fh);
$size = $currentSize;
}
}
follow("file.txt");
$handle = popen("tail -f /var/log/your_file.log 2>&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer\n";
flush();
}
pclose($handle);
Checkout php-tail on Google code. It's a 2 file implementation with PHP and Javascript and it has very little overhead in my testing.
It even supports filtering with a grep keyword (useful for ffmpeg which spits out frame rate etc every second).
$handler = fopen('somefile.txt', 'r');
// move you at the end of file
fseek($handler, filesize( ));
// move you at the begining of file
fseek($handler, 0);
And probably you will want to consider a use of stream_get_line
Instead of polling filesize you regular checking the file modification time: filemtime
Below is what I adapted from above. Call it periodically with an ajax call and append to your 'holder' (textarea)... Hope this helps... thank you to all of you who contribute to stackoverflow and other such forums!
/* Used by the programming module to output debug.txt */
session_start();
$_SESSION['tailSize'] = filesize("./debugLog.txt");
if($_SESSION['tailPrevSize'] == '' || $_SESSION['tailPrevSize'] > $_SESSION['tailSize'])
{
$_SESSION['tailPrevSize'] = $_SESSION['tailSize'];
}
$tailDiff = $_SESSION['tailSize'] - $_SESSION['tailPrevSize'];
$_SESSION['tailPrevSize'] = $_SESSION['tailSize'];
/* Include your own security checks (valid user, etc) if required here */
if(!$valid_user) {
echo "Invalid system mode for this page.";
}
$handle = popen("tail -c ".$tailDiff." ./debugLog.txt 2>&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer";
flush();
}
pclose($handle);