I suggest you not to write the code, that already written so many times... Try to use some open source classes. Like this one. The class is easy and lightweight, and have pretty good documentation. The usage is simple:
// *** Include the class
include("resize-class.php");
// *** 1) Initialize / load image
$resizeObj = new resize('sample.jpg');
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(150, 100, 'crop');
// *** 3) Save image
$resizeObj -> saveImage('sample-resized.gif', 100);
You can use 'auto' option instead of 'crop', and provide max width and height. This mean's, that the image resolution will be generated based on the maximum properties you provided, and also, based on image orientation. Try it ;)