too long

I have an upload form where you select photos. Upon upload I resize the image if necessary.

It seems any photo that I upload where the HEIGHT > WIDTH stretches the image. If I upload an image where WIDTH > HEIGHT it works fine. I've been racking my brain trying to figure this out. I'm pretty sure I know which line is the issue and I've pointed it out in a comment.

Can anyone see what is wrong with my math? Thanks!

<?php
$maxWidth  = 900;
$maxHeight = 675;
$count     = 0;

foreach ($_FILES['photos']['name'] as $filename)
{
    $uniqueId   = uniqid();
    $target     = "../resources/images/projects/" . strtolower($uniqueId . "_" . $filename);
    $file       = $_FILES['photos']['tmp_name'][$count];    
    list($originalWidth, $originalHeight) = getimagesize($file);

    // if the image is larger than maxWidth or maxHeight
    if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
    {
        $ratio = $originalWidth / $originalHeight;

        // I think this is the problem line
        (($maxWidth / $maxHeight) > $ratio) ? $maxWidth = $maxWidth * $ratio : $maxHeight = $maxWidth / $ratio; 

        // resample and save
        $image_p    = imagecreatetruecolor($maxWidth, $maxHeight);
        $image      = imagecreatefromjpeg($file);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $originalWidth, $originalHeight);
        $image      = imagejpeg($image_p, $target, 75);
    }
    else
    {
        // just save the image
        move_uploaded_file($file,$target);
    }
    $count += 1;
}
?>

When scaling, you need to modify both the width and the height of the target.

Try:

if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
{
    if ($originalWidth / $maxWidth > $originalHeight / $maxHeight) {
        // width is the limiting factor
        $width = $maxWidth;
        $height = floor($width * $originalHeight / $originalWidth);
    } else { // height is the limiting factor
        $height = $maxHeight;
        $width = floor($height * $originalWidth / $originalHeight);
    }
    $image_p    = imagecreatetruecolor($width, $height);
    $image      = imagecreatefromjpeg($file);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
    $image      = imagejpeg($image_p, $target, 75);
}