too long

Brief & Code

I have the content of a Chat log stored in a .txt file. The content is as follows:

a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"14:15:54";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 2";s:4:"time";s:8:"14:16:55";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 3";s:4:"time";s:8:"14:17:59";}

A jQuery function calls out to a page chatretrieve.php to collect the content of this file. The PHP file looks like this:

<?php

session_start();

$data = unserialize(file_get_contents('../sessions/chats/log_'.$_SESSION['chatCode'].'.txt'));

#exit(print_r($data));

$content = '';

for($i = 0; $i < count( $data ); $i++){
    $content.='<div class="msgln">';
        $content.='<div class="meta">';
            $content.='<span class="name">'.$data[$i]['author'].'</span>';
            $content.='<span class="time">'.$data[$i]['time'].'</span>';
        $content.='</div>';
        $content.='<div class="msg">'.stripslashes(htmlspecialchars($data[$i]['message'])).'</div>';
    $content.='</div>';

}

return $content;

The relevant part of the jQuery function is as follows:

$.post('inc/chatretrieve.php').done(function(data) {
    console.log(data);
});

The problem

When I comment out the exit(print_r($data)) part of the PHP page, the console returns only the first of the array variables in the .txt file:

Array
(
    [author] => e297f
    [message] => test
    [time] => 14:15:54
)
1

As there are three messages in the .txt file (and retrieved with the file_get_contents() function), why can I only see the first line when I use the unserialize() function?

The issue is that your serialised data isn't valid:

'a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"14:15:54";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 2";s:4:"time";s:8:"14:16:55";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 3";s:4:"time";s:8:"14:17:59";}

Because this is three arrays it's unclear how to unserialise this (I'm surprised that PHP doesn't fail outright but instead returns the first object).

You will need to either store this as a serialised array or, alternatively find a way to split the file into sections for each message - this could probably be done on newlines or something similar.

e.g. Something like

<?php
//Note the added newlines.
$sez = 'a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"14:15:54";}
a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 2";s:4:"time";s:8:"14:16:55";}
a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 3";s:4:"time";s:8:"14:17:59";}';


foreach(explode("
",$sez) as $line){
    $data = unserialize($line);
    print_r($data);
}

Example here http://codepad.org/sq1SbhIz