'i have problem with compress my images please advise me best way, this in my code

I am trying to develop an image_compressor web project. I am confused about the best image type for faster page loading speeds and best compression practices. Please advise me on the best way to compress image sizes. Also, please help me to improve my code.

include('connect.php');
$path = "uploads/";
$time = rand(0, 1000);
$valid_formats = array("jpg", "jpeg", "JPG", "JPEG");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
    $name = $_FILES['photoimg']['name'];
    $size = $_FILES['photoimg']['size'];
    $tmp = $_FILES['photoimg']['tmp_name'];
    if (strlen($name)) {
        list($txt, $ext) = explode(".", $name);
        if (in_array($ext, $valid_formats)) {
            if ($size < (5120 * 5120)) {
                include_once("resizeimage.php");
                $actual_image_name = base64_encode($name."+".$time).".".$ext;
                $compress = compressImage($tmp, $path.$actual_image_name, 90);
                if (move_uploaded_file($tmp, $path.$actual_image_name)) {
                    $target_file = "uploads/".$actual_image_name;
                    $resized_file = "uploads-thumb/thumb_".$actual_image_name;
                    $resize = 'thumb_'.$actual_image_name;
                    $wmax = 200;
                    $hmax = 200;
                    $resizeimg = ak_img_resize($target_file, $resized_file, $wmax, $hmax, $ext);

                    $insert = $connect->prepare("INSERT INTO `user` (`profile_image`, `profile_image_small`) VALUES (?,?) ");
                    $insert->bindValue(1, $actual_image_name);
                    $insert->bindValue(2, $resize);
                    $insert->execute();
                    echo "<img src='uploads-thumb/thumb_".$actual_image_name."' class='img-circle img-thumbnail'>";
                } else {
                    echo '<script>alert("failed");</script>';
                }
            } else {
                echo '<script>alert("Image file size max 5 MB");</script>';
            }
        } else {
            echo '<script>alert("the format of file shoulde be JPG");</script>';
        }
    } else {
        echo '<script>alert("Please select image..!");</script>';
    }
    exit;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source