Server Memory full - fclose missing - php

I have a PHP-Code like:
$timestamp = time();
echo time();
echo "<br>";
$datenbank = "timestamp.txt";
$datei = fopen($datenbank, "w") or die("Unable to open file!");
fwrite($datei, $timestamp) or die("Unable to write file!");
but I forget fclose(). Now, I have no more memory on the server. Could this be the reason?

Unlikely. It is not good practice to leave files open like that, but PHP will close the file when your script ends.

Related

Bug fread in a txt file, read only one time

I'm creating a code to display the name of a server with enterprise rules, So for don't use Mysql i try a new things (for me) use php to read and rewrite files, that work perfectly for one part of my code and work perfectly but for the second he only read one time, and when i do a f5 the code don't increment.
He rewrite correctly because my file was at 000 and become 001
I try to use file() but he is disable since 7.0, try to use SplFileObject but it don't want to display anything and i don't like it because i understand nothing when i use it so i come back to fopen(),fread() and fwrite() and that don't work. I'm inPHP 7.3.1
The code that works :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$nom = "./config.txt";
$filez = fopen($nom, "r") or die("Unable to open file!");
$i = fread($filez,filesize($nom));
$year = getdate();
$idy = substr($year[year], 2);
$fichier = fopen("./resultsrv.txt", "w") or die("Unable to write file!");
for ($z; $z<$_POST['nbr']+1 ; $z++) {
$id = sprintf("%04d", $i+$z);
$nome = $_POST['type'].$_POST['OS'].$idy.$id."<br>" ;
echo $nome;
$nomewout = str_replace("<br>", ";", $nome);
fwrite($fichier,$nomewout);
}
$handle = fopen("./config.txt", "w") or die("Unable to write file!");
fwrite($handle,$id);
fclose($fichier);
fclose($handle);
}
?>
and the one that doesn't work because he doesn't increment :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$fileName = 'confchass.txt';
$read = fopen($fileName,"r");
$fn = fopen($fileName,"w+");
$i = fread($read,filesize($fileName));
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $_POST['Marque'].$_POST['DC'].$id;
echo "</div>";
fwrite($fn,$id);
fclose($read);
fclose($fn);
}
?>
I want he output a thing like XXXXXX001 and when i refresh or do a new POST from my forms he output XXXXXX002 and XXXXXX003 .... But he actualy output only XXXXXX001
The problem is that you open the file for reading and then for writing. But from the manual...
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
So this will blank out the file before you read the value from it.
To fix this (using your current method, you should read the value, then open it for writing and write the new value...
$read = fopen($fileName,"r");
$i = fread($read,filesize($fileName));
fclose($read);
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $id;
echo "</div>";
$fn = fopen($fileName,"w+");
fwrite($fn,$id);
fclose($fn);
You could shorten this by using file_get_contents() and file_put_contents().

creating a custom redirecting page

I want to make a page like
www.example.com/redirect.php
above page must redirect to another page like
www.google.com
But whenever I open www.example.com/redirect.php?changeurl=www.yahoo.com
from now onwards www.example.com/redirect.php
page should start redirecting to yahoo.com
if changeurl=youtube.com
from now onwards
the page www.example.com/redirect.php must star redirecting to youtube.com
How can I do that without using SQL database, only by using a single file "redirect.php"
Please ask if you need more information about this question
First off you should at least have some code already written.
But try using this:
redirect.php:
<?php
if(!file_exists("redirect_url.txt")) {
$createfile= fopen("redirect_url.txt", "w") or die("Unable to open file!");
$txt = "https://www.google.com";
fwrite($createfile, $txt);
fclose($createfile);
}
if(isset($_GET['changeurl'])) {
$editfile= fopen("redirect_url.txt", "w") or die("Unable to open file!");
$txt = $_GET['changeurl'];
fwrite($editfile, $txt);
fclose($editfile);
header("Location: " . $_GET['changeurl']);
} else {
$myfile = fopen("redirect_url.txt", "r") or die("Unable to open file!");
$url = fgets($myfile);
fclose($myfile);
header("Location: " . $url);
}
?>
Also make sure in the ?changeurl You always use http:// or https://, Since you are not using a database you can use a .txt file.

File handling with PHP over local network

Hi I am using fopen php function to maintain log. I can write to the file within my own computer. But how to make PHP able to write file over the local network. Other computer in the network access my computer PHP application through IP but fails with permission when writing to the log file. My code is:
function hotellog($txt) {
date_default_timezone_set("Asia/Kathmandu");
$newfile = '\\localhost\gandaki/wp-content/hotel_log.json';
if (file_exists($newfile)) {
$myfile = fopen($newfile, "a") or die("Unable to open file!");
$txt = date("Y-m-d h:i:s") . "\r\t\t" . $txt . "\n\n\n";
fwrite($myfile, $txt);
fclose($myfile);
} else {
$myfile = fopen($newfile, 'w') or die("Can't create file");
$txt = date("Y-m-d h:i:s") . "\r\t\t" . $txt . "\n\n\n";
fwrite($myfile, $txt);
fclose($myfile);
}
}
Other computers over networks get the error as 'permission denied'.
PHP can not (well, should not) be able to write files over the network onto your computer under normal circumstances. You would be better off writing the log file on your local computer and then scripting a file transfer via sftp, or something similar, from your local computer to the remote one.

How can I make the PHP write to the file automaticly?

I want to save a web page to a text file automatically or at least every second. So I wrote a PHP file like that :
<?php
$homepage = file_get_contents('www.example.com');
echo $homepage;
$myfile = fopen("file.txt", "w") or die("Unable to open file!");
while(true) {
fwrite($myfile, $homepage);
}
fclose($myfile);
?>
But it did not work
The file will not be written until the while loop will stop.
Can someone help me with that ? I need the PHP to run all the time or at least for a few minute. How can I do that ?
I'd go for something like this (not tested though)
<?php
header("Refresh:30"); // The page will be refreshed every 30 seconds
// To avoid max_execution_time errors
$myfile = "file.txt";
for ($i=0; $i < 30; $i++) {
$homepage = file_get_contents("http://www.example.com");
echo $homepage;
file_put_contents($myfile, $homepage);
sleep(1); // Do it every second
}
If a second is too much time, you could use usleep instead
That's because you don't close the file in the loop. And you should add some delay too. Change it to this:
<?php
$homepage = file_get_contents('www.example.com');
echo $homepage;
while(true) {
$myfile = fopen("file.txt", "w") or die("Unable to open file!");
fwrite($myfile, $homepage);
fclose($myfile);
sleep(1);
}
?>
Note that if you're running this on a webserver, it will exceed the time limit.
First off, maybe you should consider using sleep inside your loop to minimise performance impact. After every write you should invoke flush to persist data onto disk. There is also a risk of overloading target site in a form of DOS attack, so you should be mindful of the consequences.
This is not tested but should word... But honestly your better of using Ajax with a timer to do this.
header("Refresh:60");
function writeToPage($page,$file){
$content = file_get_contents($page);
file_put_contents($file,$content);
}
$page = "www.example.com";
$file = "file.txt";
$write = true;
while( $write === true ) {
sleep(5);
writeToPage($page,$file);
}

Start-Job PHP Script Not Working in Powershell?

I have a PHP script that looks like:
if(file_exists("temp.txt")){
$myfile = fopen("temp.txt", "a") or die("Unable to open file!");
}
else{
$myfile = fopen("temp.txt", "w") or die("Unable to open file!");
}
date_default_timezone_set("America/New_York");
$date = date('m/d/Y h:i:s a', time());
$text = $date . PHP_EOL;
fwrite($myfile, $text);
fclose($myfile);
When I run the above script in Powershell using
php myscript.php
A text file is created and written into.
If I try to run the same file with
Start-Job ScriptBlock {php myscript.php}
I'll get a response like
But my text file is never written into. It seems like Start-Job never starts my PHP script.
How do I get Start-Job to start running PHP scripts?
Ok I'll write an answer about all of this:
From test (with your script as origin) I added some echo to get something in Receive-Job in powershell.
It was obvious the script was running as intended, but not in the expected directory.
So I added a getcwd() within an echo and this show me the working dir for the job (or scriptblock) is my documents directory) and I found the file there wihtin my home\documents.
Here the final script I eneded with:
echo "I'm running in ".getcwd()." !\n";
if(file_exists("temp.txt")){
$myfile = fopen("temp.txt", "a") or die("Unable to open file!");
}
else{
$myfile = fopen("temp.txt", "w") or die("Unable to open file!");
}
echo "Ok, file was opened: \n".print_r(fstat($myfile),1)."\n";
date_default_timezone_set("America/New_York");
$date = date('m/d/Y h:i:s a', time());
$text = $date . PHP_EOL;
$r=fwrite($myfile, $text);
echo "Write in file returned $r \n";
fclose($myfile);
echo "File closed\n";
And that is the output is with Powershell:
Start-Job -ScriptBlock { D:\wamp\bin\php\php5.4.3\php.exe D:\wamp\bin\php\php5.4.3\test.php }
Id Name State HasMoreData Location Command
-- ---- ----- ----------- -------- -------
51 Job51 Running True localhost D:\wamp\bin\php\php5....
And retrieving the output:
Receive-Job 51
I'm running in C:\Users\my_name\Documents !
Ok, file was opened:
Write in file returned 24
File closed
Hope it will help.

Categories