4000 lines!
yikes, I have written big scripts but that makes mine look like a joke.
Let me try to give you few tips.
It sounds like you put all your sites functionality into one page.
If when a user clicks a link if there is anything in the script that does not pertain directly to the content they are viewing in that one page it should be in a different script.
I generally I have, one file that has my javascript functions, one file that has my CSS, there is my index file which has just the basic visual fame work for the site and it directs traffic, there is a session/login file, there is separate file for the menu if there is a left menu it is a separate file from the right menu, a separate file for the site header, a separate file for the content sections general visual layout, a separate file for the footer, and then for every link I make a separate HTML page and another PHP functions page. And on top of that if multiple pages can reuse a function I have a page for common PHP functions.
In a recent project without any links loaded and content section blank 10 files had to load. One section of the site was so complex and dynamic that I on certain pages you could have been seeing about 15 files all brought together to make what you saw. I suppose all of it together may have been close to that 4000 lines but as each part could be used in other places separate from the rest I made them into individual parts to be included if needed.
The long (hard) way to do coding.
if (isset($var)) {
//500 lines of code
}
else {
//400 lines of code
}
A simple way to brake it up
if (isset($var)) {
include('500lines.php');
}
else {
include('400lines.php');
}
It is real simple, cut and paste out sections and in there place just put an include() with the name of the file that has the php you cut out.
Also it may help you to look up optimization for php. There is a lot neat tricks out there to make things more compact and clean. Also if you feel like really expanding your knowledge look into Object Oriented Programing (OOP).