Jump to content

File format switching


skis

Recommended Posts

Here's what I'm trying to do: I have a text file with the format password:username and I need to switch it to username:password

 

Sounds simple enough right? Can anyone see what's wrong with the code I wrote below? I'll provide the code and a logical sample of what the output is.

 

#!/usr/bin/php -q
<?php

if ($argc < 2) {
        echo "\nusage: $argv[0] inputfilename outputfilename\n\n";
        die;
}

$handle = fopen($argv[1], "r");
$contents = fread($handle, filesize($argv[1]));
fclose($handle);

$array = explode(":", $contents);

$handle = fopen($argv[2], "a");
$i = 0;
while ($i < count($array)) {
        $first = current($array);
        $second = next($array);
        next($array);
        $i = $i+2;
        fwrite($handle, $second.":".$first."\r\n");
}
fclose($handle);

?>

 

Output:

user1
password2:password1
user3
password4:user2
password3
user5
password6:user4

and so on...

 

I can't figure out why it's doing this? Can anyone else see the coding error somewhere?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/103478-file-format-switching/
Share on other sites

 

I think you have each password:username in a separate line and you read a line-feed inside the string $contents. If this is the case, try something like this

 

<?php
$contents = array_map('trim', file($argv[1]));
foreach($contents as $line)
{
  list($password, $username) = explode(':', $line);
  print "$username:$password\n";
}
?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.