Eventually in your web development you may run into one of these annoying errors. What it typically means is that your browser is being sent some HTML before the PHP command header() and it’s causing your issue.
Unfortunately there is no easy way to go about troubleshooting this other than following the logic through your code, hopefully you’ve saved & tested recently and have a fairly short code to go troubleshooting with. In video games I learned early on to “Save early, save often”. I’ve since modified that to my programming so that I remember to save early, save often but also “Test early, test often”. Make little changes, then you know how much you need to go back and troubleshoot when there is an error. Anyway, another less known cause of this issue is that you’ve got the dos character ^M inserted in your code. This recently happened to me when I used FTP to download a website and then uploaded it somewhere else. Somewhere along the line my windows PC decided my perfectly fine files should have some ^M inserted into some of the files. As a result I got the “Headers already sent” error.
I’d run into the error before but I knew that I hadn’t introduced any new code so I knew it couldn’t be any html being sent before the header() function. After much googling and “facedesk”‘ing I finally found that the dos character could also cause this error. After a bit more googling I found that the easiest way to get rid of this is to simply run the following command and it will easily and quickly remove all of the dos characters (^M).
dos2unix your_messed_up_file.php
I ran this command on the file and then tried my test again and just like that I was back to normal again 🙂