Save result in more txt files - php

if (is_writable($filename2)) {
if (!$handle = fopen($filename2, 'a')) {
echo "Cannot open file ($filename2)";
exit;
}
if (fwrite($handle, $datass) === FALSE) {
echo "Cannot write to file ($filename2)";
exit;
}
fclose($handle);
} else {
echo "The file $filename2 is not writable";
}
}
$filename2 = 'test.txt';
and this code work and the info come on test.txt but I want to process more files like test.txt and test2.txt.
How can I do this?

Not sure what you want to achieve, but maybe you want to extract a function and then use that function to write to multiple files?
function writeToFile($filename, $content)
{
if (!is_writable($filename2)) {
echo sprintf(
'The file "%s" is not writable',
$filename
);
return;
}
$handle = fopen($filename, 'a');
if (false === $handle) {
echo sprintf(
'The file "%s" cannot be opened',
$filename
);
return;
}
$written = fwrite($handle, $data);
fclose($handle);
if (false === $written) {
echo sprintf(
'Could not write to file "%s"',
$filename
);
}
}
$data = '...';
writeToFile('test.txt', $data);
writeToFile('test2.txt', $data);
Note Opening files with fopen() and mode a and then writing using fwrite() will append to existing files, otherwise create new files. Also, you should still close the file handle with fclose(), even if you were unable to write to the file.
For reference, see:
http://php.net/manual/en/language.functions.php
http://php.net/manual/en/function.fopen.php
http://php.net/manual/en/function.fwrite.php
http://php.net/manual/en/function.fclose.php

Related

PHP : failed to open stream error when reading file name from file

I have a file input.txt that contains file names that I need to open and read data. I have written the following php code and I get the failed to open stream: No such file or directory when it tries to open with variable $files, i.e., the second fopen is failing.
$handle = fopen("/home/user/input.txt", "r");
if($handle) {
while(($files = fgets($handle)) !== false) {
print $files;
$filename = fopen($files,"r");
print $filename;
}
}
input.txt content:
/home/user/file_1
/home/user/file_2
/home/user/file_3
/home/user/file_4
file_1,file_2,file_3 and file_4 are in /home/user/
I am not sure what I am doing wrong.
My guess is that the file lines contains whitespaces (e.g. \r), to remove them we'll use trim()
function open_files_from_file_list()
{
$handle = fopen("/home/user/input.txt", "r");
if(!$handle)
return;
while(($line = fgets($handle)) !== false)
{
$line=trim($line);
print $line;
if (!file_exists($line))
{
print ' does not exists';
continue;
}
$filename = fopen($line,"r");
print $filename;
}
}

PHP Script To Check a File Exist in a Remote Server

I want to write a script that checks if the file exists on the remote Server or not.
If file exists Write url in a file found.txt. How i can Read many urls from a txt file and Write the url to a different txt file?
This is my code:
<pre>
$sourcePath = "http://www.example.net/file.txt";
$AgetHeaders = #get_headers($sourcePath);
if (preg_match("|200|", $AgetHeaders[0])) {
$found = fopen('found.txt', "w") or die("Unable to open file!");
fwrite($found, $sourcePath);
fclose($found);
} else {
echo "Not found!";
}
</pre>
If you store urls in text file one per line you could manage it like this:
$handle = fopen("AddressList.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$sourcePath = $line;
$AgetHeaders = #get_headers($sourcePath);
if (preg_match("|200|", $AgetHeaders[0])) {
$found = fopen('found.txt', "w") or die("Unable to open file!");
fwrite($found, $sourcePath);
fclose($found);
} else {
echo "Not found!";
}
}
} else {
// error opening the file.
}
fclose($handle);

php fwrite not writing

I'm trying to write a nickname from teamspeak to a file.
It goes through all the checks, but when I check the file afterwards, nothing gets written.
$file = "test.txt";
$fh = fopen($file, 'w');
if(file_exists($file))
{
echo "exist";
}else{
echo "absent";
}
if(is_writable($file))
{
echo "writable";
}else {
echo "cant write";
}
if (false === $fh) {
throw new RuntimeException('Unable to open log file for writing');
}
foreach($Summoners as $su){
$name = $su["TsNICK"];
echo $name;
fwrite($fh, $name);
echo "Wrote to file";
}
fclose($fh);
I can't really tell why your code isn't working, but you should consider rewriting it to this:
$file = "test.txt";
if (false === ($fh = fopen($file, 'w'))) {
throw new RuntimeException('Unable to open log file for writing');
}
foreach($Summoners as $su) {
$name = $su["TsNICK"];
echo $name;
fwrite($fh, "$name\n");
}
fclose($fh);
If you wish to always append to a file, you would need mode 'a' instead of 'w'.

cannot overwrite files with PHP

I am trying to overwrite files i created in php
when i'm using file_put_contents i receive 0 of "x" bytes written
with the function below that uses fwrite i get the error the file is not writable.
the permissions are 777 (including the directories)
there is no problem creating files, the problem is when i try to modify them.
can anyone figure what is the problem?
function update_body($body)
{
$URL = $_REQUEST["URL"];
$filename = $URL;
$somecontent = $body;
if (is_writable($filename))
{
if (!$handle = fopen($filename, 'w'))
{
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE)
{
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
}
else
{
echo "The file $filename is not writable";
}
}
the procedure where i create the file
function save_body($body)
{
$datearr = getdate(); //get date array, use date for folder, time for filename
$current_date = $datearr['year'].$datearr['mon'].$datearr['mday'];
$current_time = $datearr['hours'].$datearr['minutes'].$datearr['seconds'];
// create directory according the date
if (!file_exists($_SERVER['DOCUMENT_ROOT'] .'/articles/'.$current_date))
mkdir($_SERVER['DOCUMENT_ROOT'] .'/articles/'.$current_date, 0777, true);
// write the file
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/articles/'.$current_date.'/'.$current_time.'.txt',"w");
fwrite($fp,$body);
fclose($fp);
return $current_date.'/'.$current_time;
}
Welcome to Stack Overflow.
As #Sebas said, try to use a relative path (../../../articles) or wherever your folder is instead of
$_SERVER['DOCUMENT_ROOT']
Have a nice day!

fwrite not writing

$fp = fopen('log.txt', 'w');
fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . '\n');
The code above is not writing to the file. the $row['toolbar_id'] is a value from a for each loop. Any suggestions? There is no PHP error, as the file does open as I have debugged that part.
Try this for extra surety
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$fp = fopen('log.txt', 'ab');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$bytes = fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . PHP_EOL);
printf('Wrote %d bytes to %s', $bytes, realpath('log.txt'));
fclose($fp);
Edit: Changed the "write" flag (w) to "append" (a) as truncating a log file doesn't sound like a great idea
https://bugs.php.net/bug.php?id=48607
there is a php bug with fwrite and ftp which means the last chunks of files sometimes dont get written when fclose is called directly after fwrite
putting a sleep(1); before fclose fixes the issue, or in your case logging to a file before fclose can also stop it
posting for future reference!
<?php
$filename = 'log.txt';
$somecontent = "Missing gallery image for: ";
if($row['toolbar_id'] != "")
{
$somecontent .= $row['toolbar_id'];
}
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
Try this code... !!

Categories