Jump to content

only storing one loop in txt file


Boxerman

Recommended Posts

Hey guys,

 

Hopefully its a simple one, but im confused.

 

The code below is outputting the correct on the page (in the array i have 2 outputs) but it is only storing the last array in the txt file, how would i fix this issue?

foreach($servers as $server)
{
    $connection = ssh2_connect($server['ip'], 22);
    if (ssh2_auth_password($connection, $server['user'], $server['pass']))
    {
        $stream = ssh2_exec($connection, 'cd /home/matrix/www; htpasswd2 -b -d .htuser-james '.$aduser.'@domain.com '.$cryptpass.'');
	stream_set_blocking($stream, true);
	// read the output into a variable
	$data = '';
	//loop the buffer and store output to $data
	while($buffer = fread($stream, 4096)) {
    $data .= $buffer;
	}
	// close the stream
	fclose($stream);
	// print the response
	$output = 'User Added to '.$server['ip'].'';
	echo $output;
	echo '<br>';
	$filename = '../logs/docops/'.$aduser.'.txt'; //the name of our file.
	$strlength = strlen($output); //gets the length of our $content string.
	$create = fopen($filename, "w"); //uses fopen to create our file.
	$write = fwrite($create, $outout, $strlength); //writes our string to our file.
	$close = fclose($create); //closes our file
    }

}

Output on page:

User added to IP 1.1.1.1

User added to IP 1.2.2.2

 

Output in text file:

User Added to IP 1.2.2.2

 

Hope this supplies enough information! 

Edited by Boxerman
Link to comment
Share on other sites

$create = fopen($filename, "w");

 

http://php.net/manual/en/function.fopen.php

 

'w' Open for writing only; 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.

 

'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.

 

$create = fopen($filename, "a+");

 

It would be better to build your variable or array in the loop and write it all at the same time to the file after the loop.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.