Is it bad to apply to one PhD program with the intent of leaving for another (more prestigious) one? I'm in my senior year of undergrad. I messed up a little bit academically this semester - not seriously, but enough to be confident I wouldn't get into a top 20 math PhD program. So I wanted to work on improving my CV for a year or two and then apply to the top 20 PhD programs (kind of like this person). I was thinking of this year applying to 2nd-tier schools for either a Master's or PhD program, then if I'm excelling really well in my first semester, applying to 1st-tier math PhD programs at the end of that semester. The main question I have is whether I should apply to the Master's or the PhD programs at 2nd-tier schools.

At first it seemed like a no-brainer to apply to the PhD programs at the 2nd-tier schools in order to receive free tuition and a stipend (which usually don't come with Master's programs). But then I was worrying if it would be looked down upon by both the university I am at and the one I am applying to if I am "quitting" one funded PhD program in order to join another. I especially felt concerned after looking at this answer, which describes a PhD as a "long-term relationship... an expensive and rare opportunity." Should I avoid applying to one PhD program with the intent of leaving for another (more prestigious) one? If so, should I just apply to Master's programs at the 2nd-tier schools this year?
This would be wrong.

The reason the PhD is subsidized, while the master's is not, is because you are making a longer-term commitment to the university, and they expect to benefit as an institution from your PhD work.  You would be accepting this under false pretenses.  In my opinion, this is just wrong, apart from whether it harms you or not.  You should not enter into agreements where you never intend to hold up your side of the deal.

It would also not work as well for your plan.

I think it will be hard to produce evidence, based on 6 months or a year of a PhD program, of your improved academic performance.  But you could actually complete a master's degree in a year's time, and that would be something that would really help admission into a PhD program.

Leaving shortly into your PhD program is definitely frowned upon.

Universities actively try to stop this from happening.  For example, they usually do not allow people in PhD programs to convert their work into a master's degree after a year or two of study, precisely because people would try to take advantage of this loophole to get a free master's.

This will look bad to the institution you are leaving.  I'm less certain about how the institution you are going to would view it, but it seems a potential negative there, as well.