Determinate line file it´s empty in loop for - php

The file called "file_changes.dat", it´s totally empty, no have any informations, and create in server, i use this script for simple show data from this file, the script it´s the next :
$fil_dat_changes=file("file_changes.dat");
$f_changes=fopen("file_changes.dat","w");
for($fh=0;$fh<sizeof($fil_dat_changes);$fh++) {
if(trim($fil_dat_changes[$fh])=="")
{
print "NO DATA";
fputs($f_changes,"".date("dmYHis").""."\n");
}
else
{
print "YES EXISTS LINE";
}
}
fclose($f_changes);
And i don´t know why if file it´s empty, when i put :
if(trim($fil_dat_changes[0])=="")
Don´t show nothing, and also don´t put the line with fputs, i think the result must show NO DATA ans insert the informations, but don´t insert nothing
I don´t understand which it´s the problem because i think if don´t exists any line of informations or data, must insert the line finally in the file
That´s it´s my question, why don´t insert data, thank´s in advance all community, regards

You can check the file contains data using filesize(). BUT as you also open the file for writing in
$f_changes=fopen("file_changes.dat","w");
this will always empty the file and set it for writing. This will clear any data already in the file.
If instead you check if the file is empty and then use file_put_contents() to write to the file, this will only do this if the file is empty...
if ( 0 == filesize( "file_changes.dat" ) ) {
file_put_contents("file_changes.dat", date("dmYHis").PHP_EOL);
}
else {
echo "YES EXISTS LINE";
}

Related

PHP, check if the file is being written to/updated by PHP script?

I have a script that re-writes a file every few hours. This file is inserted into end users html, via php include.
How can I check if my script, at this exact moment, is working (e.g. re-writing) the file when it is being called to user for display? Is it even an issue, in terms of what will happen if they access the file at the same time, what are the odds and will the user just have to wait untill the script is finished its work?
Thanks in advance!
More on the subject...
Is this a way forward using file_put_contents and LOCK_EX?
when script saves its data every now and then
file_put_contents($content,"text", LOCK_EX);
and when user opens the page
if (file_exists("text")) {
function include_file() {
$file = fopen("text", "r");
if (flock($file, LOCK_EX)) {
include_file();
}
else {
echo file_get_contents("text");
}
}
} else {
echo 'no such file';
}
Could anyone advice me on the syntax, is this a proper way to call include_file() after condition and how can I limit a number of such calls?
I guess this solution is also good, except same call to include_file(), would it even work?
function include_file() {
$time = time();
$file = filectime("text");
if ($file + 1 < $time) {
echo "good to read";
} else {
echo "have to wait";
include_file();
}
}
To check if the file is currently being written, you can use filectime() function to get the actual time the file is being written.
You can get current timestamp on top of your script in a variable and whenever you need to access the file, you can compare the current timestamp with the filectime() of that file, if file creation time is latest then the scenario occured when you have to wait for that file to be written and you can log that in database or another file.
To prevent this scenario from happening, you can change the script which is writing the file so that, it first creates temporary file and once it's done you just replace (move or rename) the temporary file with original file, this action would require very less time compared to file writing and make the scenario occurrence very rare possibility.
Even if read and replace operation occurs simultaneously, the time the read script has to wait will be very less.
Depending on the size of the file, this might be an issue of concurrency. But you might solve that quite easy: before starting to write the file, you might create a kind of "lock file", i.e. if your file is named "incfile.php" you might create an "incfile.php.lock". Once you're doen with writing, you will remove this file.
On the include side, you can check for the existance of the "incfile.php.lock" and wait until it's disappeared, need some looping and sleeping in the unlikely case of a concurrent access.
Basically, you should consider another solution by just writing the data which is rendered in to that file to a database (locks etc are available) and render that in a module which then gets included in your page. Solutions like yours are hardly to maintain on the long run ...
This question is old, but I add this answer because the other answers have no code.
function write_to_file(string $fp, string $string) : bool {
$timestamp_before_fwrite = date("U");
$stream = fopen($fp, "w");
fwrite($stream, $string);
while(is_resource($stream)) {
fclose($stream);
}
$file_last_changed = filemtime($fp);
if ($file_last_changed < $timestamp_before_fwrite) {
//File not changed code
return false;
}
return true;
}
This is the function I use to write to file, it first gets the current timestamp before making changes to the file, and then I compare the timestamp to the last time the file was changed.

Overwriting file issue using PHP

I have to write a file, in order to increase a value, but sometimes (when the file is opened two times in a row) it increases only by one instead of two.
This is part of the script executed two times in a row:
include "changevar.php";//declare the changevar function
include $file;//get user's impressions
changevar("impressions",$impressions+1,$file,1);//increase the impressions by 1
And this is the changevar.php file:
<?
function changevar($varname,$newval,$filename,$type)
{
while(!$fp=fopen($filename,"c+"))
{
usleep(100000);
}
while(!flock($fp,LOCK_EX))
{
usleep(100000);
}
$contents=fread($fp,filesize($filename));
ftruncate($fp,0);
rewind($fp);
eval(substr(substr($contents,2),0,-2));
$$varname=$newval;
if($type==0)//avoid reading this, in this case $type equals to 1
{
$u=str_replace("\"","\\\"",$u);
$p=str_replace("\"","\\\"",$p);
$t=str_replace("\"","\\\"",$t);
$d=str_replace("\"","\\\"",$d);
$text="<?\$o=$o;\$u=\"$u\";\$c=$c;\$m=$m;\$p=\"$p\";\$C=$C;\$id=\"$id\";\$t=\"$t\";\$d=\"$d\";\$O=$O;?>";
}
else//true, $type equals to 1
{
$text="<?\$impressions=$impressions;\$clickunici=$clickunici;\$clicknulli=$clicknulli;\$creditiguadagnati=$creditiguadagnati;\$creditiacquistati=$creditiacquistati;\$creditiutilizzati=$creditiutilizzati;?>";
}
fwrite($fp,$text);
fflush($fp);
flock($fp,LOCK_UN);
fclose($fp);
}
?>
As I just said, the script works fine, except if it is executed two times in a row.
I think that the problem is in $contents=fread($fp,filesize($filename));, because it reads the files before it is written.
I already used the flock function, but it doesn't solve this problem.
So, how can I fix the code?
It's not clear what you're doing since you only give bits and pieces of your code, and you don't show the content of the file read; but if you want to increment the value in the file, you should be adding one to a number you read from the locked file-- not writing an argument ($impressions+1) that you pass to changevar() from the outside. Rethink the logic of your code and fix it.

A File Deleting itself? [duplicate]

This question already has answers here:
PHP file that should run once and delete itself. Is it possible?
(4 answers)
Closed 9 years ago.
I am trying to create a self-destruct file. Wht I mean is, if a conditional equates to true, the file deletes itself.
Seems to me the following code should do the trick. However, it does nothing. What am I doing wrong?
<?php
phpinfo();
// The following should be activated when the url is
// selfdestruct.php?delete=1, correct?
if ($_GET['delete']==1) {
$file = 'selfdestruct.php';
unlink($file);
}
?>
Thanks for your hep in advance! I appreciate it! :-)
I usually do it like this: (using your GET)
if ($_GET['delete']==1) {
unlink( __FILE__ ) or die("Please delete this file.");
echo "This file has been deleted.<br />";
}
If the file can't be deleted it exit the script and the last echo won't be shown.
And also, your code should work, a quick test you can do to check if the condition is met, but just unable to delete the file is:
if ($_GET['delete']==1) {
echo "Works!";
}
Have you checked your web server and php log files? Could be a permissions issue or that the web server is keeping the file open so it can't be deleted.
Also, try to pass the entire local path to the file to unlink. You could probably use unlink(_FILE_)
Also, is this on Windows or Linux? They handle "open" files a bit differently. I tested this on Linux and it works fine with
unlink(__FILE__);
Information about OS and running web server etc is probably good to add to a question of this nature.
Check these steps:
Put error_reporting(E_ALL); on the first line
Check your permissions
Put the delete code above anything else, after "error_reporting"
You should do the following:
if (isset($_GET['delete']) && $_GET['delete'] == '1') {
unlink(FILE);
}

Very weird PHP file_exists issue

I run into a very weird situation with file_exists function. The hosting company said their php was configured in CGI mode instead of PHP mode. below is the code. It checks the existence of the file called test.txt in data folder on the fly during 50 seconds or so when loading the page containing the code. If file found, display "File exists" and exits the while loop. If no file found in 50 seconds, display "File does not exist" and breaks the loop too finishing loading the page.
Strange thing 1: it was not working as expected, can find the file only first time loading the page when file is there. It continues displaying "File exists" even after test.txt got removed when I refresh the page. If test.txt is not in the data folder at all, it displays "file not exists" even after I move back test.txt in the folder.
Strange thing 2: If I put a bigger file say over 170K in size, it looks working well, small files not though, especially under 40 bytes. I have tried many different ways to check file existence including absolute path, still no luck.
Thanks for any clue!
loading page...
$counter= 1;
while ($counter++) {
sleep(5);
if (file_exists("data/test.txt")) {
echo "File exists";
break;
}
if ($counter>10){
echo "File does not exist";
break;
}
}
PHP caches the results. Use clearstatcache(); before you use file_exists().
Since you are checking the existence of this file multiple times in a loop, you might need to consider caching as an issue here.
Taken from the documentation of file_Exists() -
Note: The results of this function are cached. See clearstatcache() for more details.
Perhaps you should try modifying your script to something like this -
while ($counter++) {
sleep(5);
clearstatcache();
if (file_exists("data/test.txt")) {
echo "File exists";
break;
}
...
}

How to display a message if file already exists

I have a javascript function in one page and in another page I have a php script which concentrates on file uploading. At the moment my files are uploading successfully which is great news. My question though is that I want to use the php to check if a file already exists in the folder but I want to use the javascript function to display an message to state file already exists if this is true. How can this be done?
Below is the php code which checks if file exists:
if (file_exists("upload/" . $_FILES["fileImage"]["name"]))
{
}
Below is the Javascript function when file stops uploading. at moment if file doesn't upload it displays a message stating there is an error while uploading file and it displays a message if file is successfully uploaded, but I want an extra message where if file doesn't upload but this is because the file already exists, then I want it to display a message stating file already exists.
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
}
P.S Please no one put in their answer why don't I just put an echo in the php code, I don't want to do it like that because the user never actually navigates to the php script.
In yours PHP code that checks if file exists do
else{
echo 2;
}
In yours JS code in else clausule do
if(success == 2){
result = '<span class="emsg">File already exist!</span><br/><br/>';
}
That is a quick solution, but it gives You a way to do more complex file handling via JS/PHP. For example. When PHP returns a data 1, then everything is ok, when 2 then file exists, when 3 then file is too large, when 4 then file with bad extension, when 5 then something else, and so on.
This method I have encountered when learning C/C++(in C this way is like a standard thing). This way You can give info how some parts of code went.
Still, I would generete a a random name for file, if the name is irrelevant, and if name of file is important then wold use AJAX to check it, and display info about it, or maybe append a number after file name (file(1).xyz, file(2).xyz, file(3).xyz). That depends on what You are trying to achieve.
You say.
P.S Please no one put in their answer why don't I just put an echo in
the php code, I don't want to do it like that because the user never
actually navigates to the php script.
you need to execute some php code anyway. so you will have to do this one way or another. then , display the information to the user using whatever way you want.
since we dont have all the code i assume you have a input[type=file] in the html code , so you need to use ajax with the value of the input. send it to your server , check if the filename already exists , then respond with true or false with ajax from php and execute the code in javascript that will tell the user if the file exists or not. you can use jQuery to do that :
$("#myInput").on("change",function(event){
$.getJSON("checkFileService.php",{filename:$(event.currentTarget).val()},
function(datas){
if(datas.exists === true){
doSomething();
else{
doSomethingElse();
}
}
}
Check the jQuery ajax api for more infos
you'll have to write a php script that outputs some json string like {"exists":true} in order for the client script to work.
#safarov Can you show me an example of a function to see if file already exists, then write different name for new uploaded file?
Save/upload a simple text file named "filenamecounter.txt",
containing only text 1 in it.
<?php
//Get the original name of file
$tmp_name = $_FILES["filename"]["tmp_name"];
//Get/Read File Name Counter
$filenamecounter = file_get_contents('filenamecounter.txt');
//If it is less than 10, add a "0"/Zero to make it like 01,02,03
if (strlen($filenamecounter) <= 1){
$filenamecounter = str_pad($filenamecounter, 2, '0', STR_PAD_LEFT);
}
//Assign Filename + Variable
$name = "filename".$filenamecounter.".txt";
//Save file with new name
move_uploaded_file($tmp_name, $name);
//write quotecounter to file.
$filenamecounter++;
file_put_contents("filenamecounter.txt", $filenamecounter);
?>

Categories