Search code examples
phplinuxserializationcpanelfile-get-contents

Issues reading serialized .txt file when moving from localhost to live web


I have serialized arrays stored in .txt files. I have php code which reads the arrays using file_get_contents and displays the information from the text file.

put the contents into the file:

file_put_contents($filename, serialize($data));

read the contents from the file:

 $data = unserialize(file_get_contents($filename));

Everything works fine when reading the text files on my localhost.

I recently pushed the files to a web server.

The transferred .txt files are exactly the same contents, but on the web server the same code does not read the text files. The files are there with all the serialized data, but the code returns null after they have been transferred to the web server from localhost.

If I regenerate the serialized arrays and create .txt file on the server directly, the code runs fine.

I am wondering if anyone has had a similar issue and how I can troubleshoot. I'm thinking it might be an issue of encoding or the transfer of files, but curious what the Stackoverflow universe thinks.


Solution

  • I was able to resolve this by using base64_encode when serializing data:

    file_put_contents($filename, base64_encode(serialize($data)));
    

    and by using base64_decode when unserializing data:

    $data = unserialize(base64_decode(file_get_contents($filename)));
    

    Unfortunately I still had to remove and regenerate all of the text files, but once done it appears everything is written/read correctly now. Hopefully this will help others in the future with similar issues.