String adding new lines and I don't understand why - php

I have got this code to open each file in a folder, decrease a value by 5 and then overwrite the existing content.
<?php
foreach (glob("users/*.php") as $filename) {
$array = file($filename);
$wallet = $array[0];
$time = $array[1];
$status = $array[2];
$steamid = $array[3];
$process = fopen($filename, "w") or die("Unable to open file!");
$time = $time - 5;
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
fwrite($process, $newdata);
fclose($process);
}
?>
Before I execute the script, the files that are opened look like this:
680
310
0
74892748232
After the script was executed, the file looks like this:
680
305
0
74892748232
If the script is executed again, it adds more lines and just breaks the files even more.
The string for the file is created here:
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
Why does it add an empty line after $wallet and $status, but not after $time? How can I avoid this and instead write down:
$wallet
$time
$status
$steamid
Thanks a lot in advance.:)

Try with this solution
You can also use file_put_contents():
file_put_contents($filename, implode("\n", $array) . "\n", FILE_APPEND);
from this SO question
https://stackoverflow.com/a/3066811/1301180

Related

How to extract balance from bitcoin address

I'm trying to extract the balance from a list of bitcoin addresses in a text file.
Here is my code:
<?php
$list = file("list.txt");
$file = "checked_list.txt";
foreach ($list as $address) {
$url = "https://blockchain.info/address/" . $address . "?format=json";
$json = json_decode(file_get_contents($url), true);
$FinalBalance = $json["final_balance"];
echo $address . " Balance is: " . $FinalBalance;
$data_array = array($address, $FinalBalance);
//Saving to file
$my_data = file_put_contents($file, implode(' ', $data_array) . "\n", FILE_APPEND | LOCK_EX);
sleep(5);
}
My issue here is when I have more than 1 line in list.txt it will throw an error:
Warning: file_get_contents(https://blockchain.info/address/ADDRESS-HERE
?format=json): Failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
in C:\laragon\www\Scanner\BalanceCheckerByAddress\check.php on line 9
Warning: Trying to access array offset on value of type null
If it is only 1 single address, it will display the balance and save the data to checked_list.txt
What am I missing here?
Add this line right after foreach:
$address = trim($address);
Your problem is in function file(..) because every line in the file list.txt containts line break. And you should remove the white space before working the string $address.
Your full code should looks like this:
<?php
$list = file("list.txt");
$file = "checked_list.txt";
foreach ($list as $address) {
$address = trim($address); // Added line to remove white-space
$url = "https://blockchain.info/address/" . $address . "?format=json";
$json = json_decode(file_get_contents($url), true);
$FinalBalance = $json["final_balance"];
echo $address . " Balance is: " . $FinalBalance;
echo "<br>"; // Added line for seeing the results better in web-browser
$data_array = array($address, $FinalBalance);
//Saving to file
$my_data = file_put_contents($file, implode(' ', $data_array) . "\n", FILE_APPEND | LOCK_EX);
sleep(5);
}
I tested the code in PHP 7.4.10 and it works well.

How do I create a new log file if my current log file is larger than 50mb in php?

I have a project where I have to make a new log file if the current log file is larger than 50mb. I know that we have to test for the size of the file.
I am starting out with this $log variable:
$log =
"Branch: ".$branchDir . PHP_EOL.
"Phase: ". $phaseDir . PHP_EOL.
"Total number of results files deleted: ". count($folderCounter). PHP_EOL.
"File names: " . $filePathToDelete . PHP_EOL.
"Starting CustomerID directory name: " . $CustIDvalue . PHP_EOL;
// $log = 'this is a test' . $branch . PHP_EOL;
$dt = time();
$mysql_datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
$mysql_datetimes = preg_replace('/\s+/', '', $mysql_datetime);
$logFileName = "ResultsFileDeletion" . $mysql_datetimes . ".txt";
if (unlink($filePathToDelete)) {
//this echo string will be moved to a log file
echo "first unlink: {$filePathToDelete} was deleted <br>";
$myFile =
file_put_contents("c:\\sites\\EtonBio/sequencing/logs/{$logFileName}",
$log, FILE_APPEND);
echo 'my file: ' . $myFile . '<br>';
}
I found this code snippet:
$size = filesize($_FILES['foto']['tmp_name']);
I believe my if statement would look something like this:
if($size < 52428800) {
*creates another log file
}
I want to format the $size variable correctly and I am also not sure how to make a new log file.
$size = filesize($_FILES['foto']['tmp_name']); only works if you are uploading the file.
If you want to check a file already in you server ou can simply do
$size = filesize("path/to/file");
Also, there is a ' in your $log declaration that shouldn't be there

PHP fopen() invalid argument

I'm running this code once the user submits a form. The idea is to save a new file called "message_timestamp" where timestamp is the current date and time. It need to be saved in the misc folder, which is located in the same directory as this php file.
My code:
if (isset($_POST['submitIssue'])) {
$type = $_POST['typeOfIssue'];
$prefName = $_POST['preferredName'];
$email = $_POST['userEmail'];
$details = $_POST['detailedReport'];
date_default_timezone_set('Atlantic/Bermuda');
$date = new DateTime('now');
$date = $date->format('Y-m-d_H:i:s');
$date = trim($date);
$fileName = "misc/message_" . $date;
$out = "Issue Alert!\nType of issue: " . $type . "\n\nSubmitted by " . $prefName . "\nEmail ID: " . $email . "\nSubmitted at: " . $date . "\n\nDetails: " . $details;
$myFile = fopen($fileName,"w") or die("Cannot open file!");
fwrite($myFile, $out);
fclose($myFile);
}
I've tried removing whitespaces and looking for escape characters. But as long as $date is appended to the filename, I get the error:
fopen(misc/message_2018-02-0210:47:41): failed to open stream: Invalid
argument in C:\MAMP\htdocs\A2\report.php on line 76
I can get it to work if I don't put the timestamp on it. Any suggestions?

PHP - Difficulties Writing New Line [duplicate]

This question already has answers here:
Writing a new line to file in PHP (line feed)
(4 answers)
Closed 6 years ago.
I am encountering difficulties with writing to a new line in a basic text file. All the other text (including the comma) appears just fine, but no new line (no space or anything either). I would greatly appreciate any direction.
<?php
session_start();
$user = $_SESSION['store'];
function format($input) {
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$file = "messages/reminder.txt";
$image;
$secFreqLabel;
$freqLabel;
$uploadDirectory = "corpImages/";
if(!file_exists($file)) {
$temp = fopen($file, "w"); // create file
fclose($temp);
}
$con = new PDO("sqlite:bk.db");
if($_SERVER['REQUEST_METHOD'] == "POST") {
$secFreqLabel = 'reminder.jpg';
$freqLabel = 'reminderHourly.jpg';
$thirdFreqLabel = 'reminderThree.jpg';
$fourthFreqLabel = 'reminderFour.jpg';
$freqUploadFile = $uploadDirectory . $freqLabel;
$secFreqUploadFile = $uploadDirectory . $secFreqLabel;
$thirdFreqUploadFile = $uploadDirectory . $thirdFreqLabel;
$fourthFreqUploadFile = $uploadDirectory . $fourthFreqLabel;
$statement = $con->prepare("INSERT INTO slides (image, label) VALUES (:image, :label)");
if(!empty($_FILES['freqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminder.jpg'");
}
if(!empty($_FILES['secFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderHourly.jpg'");
}
if(!empty($_FILES['thirdFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderThree.jpg'");
}
if(!empty($_FILES['fourthFreqImage'])) {
$con->exec("DELETE FROM slides where label = 'reminderFour.jpg'");
}
$image = file_get_contents($_FILES['freqImage']['tmp_name']);
move_uploaded_file($_FILES['freqImage']['tmp_name'], $freqUploadFile);
$statement->bindParam(":label", $freqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['secFreqImage']['tmp_name']);
move_uploaded_file($_FILES['secFreqImage']['tmp_name'], $secFreqUploadFile);
$statement->bindParam(":label", $secFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['thirdFreqImage']['tmp_name']);
move_uploaded_file($_FILES['thirdFreqImage']['tmp_name'], $thirdFreqUploadFile);
$statement->bindParam(":label", $thirdFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$image = file_get_contents($_FILES['fourthFreqImage']['tmp_name']);
move_uploaded_file($_FILES['fourthFreqImage']['tmp_name'], $fourthFreqUploadFile);
$statement->bindParam(":label", $fourthFreqLabel);
$statement->bindParam(":image", $image);
$statement->execute();
$text = format($_POST['freq']) . "," . format($_POST['freqMessage']) . "\n" . format($_POST['secFreq']) . "," . format($_POST['secFreqMessage']) . "\n" . format($_POST['thirdFreq']) . "," . format($_POST['thirdFreqMessage']) . "\n" . format($_POST['fourthFreq']) . "," . format($_POST['fourthFreqMessage']);
$writer = fopen($file, "w");
fwrite($writer, $text);
fclose($writer);
touch("update.txt");
}
$handler = fopen($file, "r");
$firstReminder = fgetcsv($handler, ",");
$secondReminder = fgetcsv($handler, ",");
$thirdReminder = fgetcsv($handler, ",");
$fourthReminder = fgetcsv($handler, ",");
fclose($handler);
?>
Instead of using \n use constant called PHP_EOL which represents end of line according to your enviroment.
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 5.0.2
$text = format($_POST['freq']) . "," . format($_POST['freqMessage']) . PHP_EOL . format($_POST['secFreq']) . "," . format($_POST['secFreqMessage']) . PHP_EOL . format($_POST['thirdFreq']) . "," . format($_POST['thirdFreqMessage']) . PHP_EOL . format($_POST['fourthFreq']) . "," . format($_POST['fourthFreqMessage']);
PHP_EOL in windows will be CR+LF and in unix system LF
CR - Carriage Return, U+000D
LF - Line Feed, U+000A

PHP dump $_REQUEST to file

I want to dump request variables to a file for debugging. How's this possible?
<?php
$req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fclose($fp);
Untested but should do the job, just change request.log to the file you want to write to.
I think nowadays this method is easier and faster:
$req_dump = print_r($_REQUEST, true);
$fp = file_put_contents('request.log', $req_dump, FILE_APPEND);
Use serialize() function for dumping. Dump $_SERVER, $_COOKIE, $_POST and $_GET separately (may go to the same file). If you're planning on debugging with the data it helps to know if the data was part of a POST request or a GET request.
Dumping everything is good for debugging in development, but not so in production. If your application does not have many users, it can work in production too. If you anticipate many users, consider dumping just the $_POST data, or limit server variables to those starting with HTTP_.
/* may be late but he can help others.
it's not my code, I get it from :
https://gist.github.com/magnetikonline/650e30e485c0f91f2f40
*/
class DumpHTTPRequestToFile {
public function execute($targetFile) {
$data = sprintf(
"%s %s %s\n\nHTTP headers:\n",
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$_SERVER['SERVER_PROTOCOL']
);
foreach ($this->getHeaderList() as $name => $value) {
$data .= $name . ': ' . $value . "\n";
}
$data .= "\nRequest body:\n";
file_put_contents(
$targetFile,
$data . file_get_contents('php://input') . "\n"
);
echo("Done!\n\n");
}
private function getHeaderList() {
$headerList = [];
foreach ($_SERVER as $name => $value) {
if (preg_match('/^HTTP_/',$name)) {
// convert HTTP_HEADER_NAME to Header-Name
$name = strtr(substr($name,5),'_',' ');
$name = ucwords(strtolower($name));
$name = strtr($name,' ','-');
// add to list
$headerList[$name] = $value;
}
}
return $headerList;
}
}
(new DumpHTTPRequestToFile)->execute('./dumprequest.txt');
// add this line at the end to create a file for each request with timestamp
$date = new DateTime();
rename("dumprequest.txt", "dumprequest" . $date->format('Y-m-d H:i:sP') . ".txt");
<?php //log
$razdelitel = '--------------------------------------------'.PHP_EOL . date("Y-m-d H:i:s") .PHP_EOL.PHP_EOL;
$data_REQUEST = '$_REQUEST: ' . print_r($_REQUEST, true).PHP_EOL;
$data_POST = '$_POST: ' . print_r($_POST, true).PHP_EOL;
$data_GET = '$_GET: ' . print_r($_GET, true).PHP_EOL;
$data_all = $razdelitel . $data_REQUEST . $data_POST . $data_GET;
$name_txt = __DIR__ . '/log_' . date('m.Y') . '.txt'; //log_12.2021.txt
$chmod = '0244';
chmod($name_txt, $chmod);
file_put_contents($name_txt, $data_all, FILE_APPEND);
//var_dump($name_txt, $chmod); ?>

Categories