Ottawa scored twice in third against Antero Niittymaki to even the score, then Gagne scored his 18th goal with 5:30 left.
The Flyers won their sixth straight at home, punctuated by Mike Richards' empty-netter in the final seconds.
Niittymaki had been strong in net in place of an ill Martin Biron until he hit a rough patch in the third. Dany Heatley scored his second goal of the game midway through the period and Chris Phillips ended his scoring slump minutes later with a slapper inside the blue line to make it 4-4.
Gagne, who has bounced back nicely after missing most of last season with a concussion, got the winner.
Heatley's first goal of the game and 15th of the season early in the second made it 2-2.
Carter seemed poised to give the Flyers a lead when he sprinted down the ice for the puck with Ottawa defenseman Christoph Schubert on his tail. Carter was ready to shoot on goalie Alex Auld when Schubert tripped the Flyers center from behind and sent him sprawling to the ice.
Schubert was whistled for 2 minutes for tripping. Carter made Ottawa pay when he knocked in the puck for the lead.
Andreas Nodl gave the Flyers scored his first career goal to make it 4-2. While Niittymaki had a 2.46 GAA in his last eight starts (6-1-1) entering the game, Nick Foligno needed only 5 minutes to poke the puck into the net for a 1-0 lead.
The Flyers evened the score on Matt Carle's third goal of the year, and Joffrey Lupul made it 2-1 on his 13th goal when he tipped in the puck from the crease off a sizzling shot from Scott Hartnell along the boards.
The Senators got off to a rough start on their season-high eight-game road trip that lasts until mid-January. Ottawa's eight points on the road are fewest in the Eastern Conference and it has only three road victories this season.
Notes: Senators D Anton Volchenkov left the game in the first period when he slid face first into the glass. ... The Flyers flash "Write Him In!" every time Carter scores in an attempt to earn him a spot on the All-Star team.