Save variable using fwrite - php

I just trying to understand how to use fwrite. In the below code, i am trying to save the output in the text file. I am just getting an empty txt file.
Can anyone please tell me what i am doing wrong here
<?php
$name = fix_name("ALAN", "james", "LiM");
echo $name[0] . " " . $name[1] . " " . $name[2];
function fix_name($n1, $n2, $n3) {
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));
return array($n1, $n2, $n3);
}
$fp = fopen("name.txt", "wb");
$written = fwrite($fp, $name);
fclose($fp);
?>

You are passing an array to fwrite.
If you enable error reporting with
error_reporting(E_ALL);
You would get a warning saying
Warning: fwrite() expects parameter 2 to be string, array given in file.php on line 16
Either return a string from your function
return $n1 . ', ' . $n2 . ', ' . $n3;
Or outside the function, use implode to get a string from the elements of the array
$name = implode(', ',fix_name("ALAN", "james", "LiM"));
Also, outside the function, print out just the $name variable
print $name;
In your text file you will have this
Alan, James, Lim

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.

Php foreach echo (if/else) [duplicate]

This question already has answers here:
Turn off warnings and errors on PHP and MySQL
(6 answers)
Closed 5 years ago.
It prints on the screen when it is correctly entered, but I do not want to do anything when it is entered incorrectly
How can I do that?
<?php
header('Content-type: text/html; charset=utf8');
$api_key = 'local';
$keyword = 'test';
$url = 'test.json' . $api_key . '&' .'keyword' .'=' . $GLOBALS['q'] ;
$open = file_get_contents($url);
$data = json_decode($open, true);
$istatistikler = $data['data'];
if ($data) {
foreach ( $istatistikler as $istatistik ){
echo '<div class="right">';
echo 'Oyun modu: ' . $istatistik['title'] . '<br />' .
'Kazanma: ' . $istatistik['content'] . '<br />' .
'Kazanma: ' . $istatistik['image'] . '<br />' .
'Kazanma: ' . $istatistik['category'] . '<br />' .
'<br />' .
'<hr/>';
$karakter_simge = 'http://google.com' . $istatistik['image'] . '';
echo "<img src=".$karakter_simge." >" ;
echo '</div>';
}
}
?>
Successful output
Failed output
Warning:
file_get_contents(http://localhost/api/detail?X-Api-Key=local&keyword=a):
failed to open stream: HTTP request failed! HTTP/1.1 406 Not
Acceptable in /opt/lampp/htdocs/weather-master/php/php-api.php on line
10
"I do not want to print unsuccessfully"
thank you for your help!
This may be helpful:
$open = #file_get_contents($url);
# sign before a function name (in a call) prevents from showing any warnings (It's a bad practice though).
Good luck!
Change
$open = file_get_contents($url);
into
$open = #file_get_contents($url);
if ($open === false)
die("wrong");
The # suppresses the error message. Using die() will abort the script completely with the given message.
Alternatively, change the condition to !== false and wrap the rest of your "successful" code in its body:
$open = #file_get_contents($url);
if ($open !== false)
{
$data = json_decode...
...
...
}
I guess I overshot the goal here a little, but not even running into code that won't work properly without its data isn't a bad idea at all.

String adding new lines and I don't understand why

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

file_get_contents Warning: Failed to open stream

I have a question here, tho, I've been digging here at SO, it seems I can't find the real deal;
I am trying the ff:
<?php
$filename = $trantype . $delimiter . $dateToday . $fileExtension ;
//echo $filename . '<br/>';
$fileToOpen = $filepath . $filename;
echo "File To Open: " . $fileToOpen . '<br/>';
$string = file_get_contents($fileToOpen);
//$string = file_get_contents("../transactions/o/O_20120809.xx");
$json_array = json_decode($string, true);
echo "Echo: " . $json_array[0]['itemheader_sysid'] . '<br/>';
echo "The File Contents: " . $string;
?>
The $string = file_get_contents('../transaction/o/O_20120809.xx') works smoothly on the other hand the $string = file_get_contents($fileToOpen); doesn't seem to work and is giving me the ff: error;
Warning: file_get_contents(../transactions/o/0_20120809.xx) [function.file-get-contents]: failed to open stream: No such file or directory in C:\xampp\htdocs\xx\helper\upo.php on line 19
why so?
Anyone please?

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