Can I get an iPhone in the middle of my contract?

My contract is up in 6 months, but my phone is cracked and is broken. It's a smartphone so I do have a dataplan. I heard its possible to buy an iPhone 4 in the middle of your contract, and you can take it to your local ATT ( i have att) and they can put your simcard in it. Is that true?
Can I just purchase the iPhone somewhere online like ebay and will they be able to replace the sim card? What are the conditions the phone has to be it to be useable? I've heard something like it has to be factory unlocked or something like that

You can buy the iPhone for full price when you don't qualify for an upgrade.

Or you can buy a used AT&T iPhone online.

If you only have six months left on your contract, you can do one of the following:

If you've been with the same provider for a long time, you can call their customer retention (not standard customer service) and ask them to help sign you up on a new contract with a new phone of your choice.
You might have to call back a few times, not all of the people who work there are helpful and care.

You can pay off the remaining value of your phone. So six amounts should be around 80$ or less. And then pick a new phone on contract for free or really cheap.

You can do to the Apple Store and see how much to fix it. Normally about $100.00

If you don't mind Android, the Google Nexus5 is about $350 is has some great hardware for the dollar. Also a nice size screen. Check it out on the google play store. I personaly like the iOS eco system. But that's just my preference.

If you buy an iPhone on Ebay, be extremely careful. Allot of stolen phones, or phones with hidden issues. You can often get a half decent deal, but beware. Now if the phone is unlocked, you can just swap your sim card with the new iPhone. If the phone is locked to a network, you will need to ask the seller to get it unlocked or it will not work with your sim card. Their is a method by jailbreaking your phone and software unlocking it, but every time you update iOS versions, you will need to make sure that the version is Jailbreakable or your phone will be useless. I personally find it a pain. If you're lucky, you will bid on a phone locked to the network you already use. I would still ask the seller to have it unlocked, this way if you choose to change providers or resell your phone in the future, you will have an easier time.

Hope this helps!