使用php和mysql上传图像并调整大小而不会使图像变形

I have the code that uploads the image and store it in database, but I need to resize that image on uploading without deforming it. I'm trying not to use js, but if its needed please use, and help me.

Here is my file add_post.php:

<?php //include config
require_once('../includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: ../login.php'); }
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Admin - Add Post</title>
  <link rel="stylesheet" href="../style/normalize.css">
  <link rel="stylesheet" href=".style/style.css">
  <script src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
  <script>
          tinymce.init({
              selector: "textarea",
              plugins: [
                  "advlist autolink lists link image charmap print preview anchor",
                  "searchreplace visualblocks code fullscreen",
                  "insertdatetime media table contextmenu paste"
              ],
              toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
          });
  </script>
</head>
<body>
    <?php include('template/menu.php');?>
<div id="wrapper">

    <p><a href="./">Blog Admin Index</a></p>

    <h2>Add Post</h2>

    <?php

    //if form has been submitted process it
    if(isset($_POST['submit'])){

        $_POST = array_map( 'stripslashes', $_POST );

        $file = rand(1000,100000)."-".$_FILES['file']['name'];
        $file_loc = $_FILES['file']['tmp_name'];
        $folder="../images/articole/";

        $new_file_name = strtolower($file);

        $final_file=str_replace(' ','-',$new_file_name);

        //collect form data
        extract($_POST);
        extract($_FILES);

        //very basic validation
        if($postTitle ==''){
            $error[] = 'Please enter the title.';
        }

        if($postDesc ==''){
            $error[] = 'Please enter the description.';
        }

        if($postCont ==''){
            $error[] = 'Please enter the content.';
        }
        if(move_uploaded_file($file_loc,$folder.$final_file)) {
        if(!isset($error)){
            try {

                //insert into database
                $stmt = $db->prepare('INSERT INTO blog_posts (postTitle,postDesc,postCont,postImage,postDate) VALUES (:postTitle, :postDesc, :postCont, :final_file, :postDate)') ;
                $stmt->execute(array(
                    ':postTitle' => $postTitle,
                    ':postDesc' => $postDesc,
                    ':postCont' => $postCont,
                    ':final_file' => $final_file,
                    ':postDate' => date('Y-m-d H:i:s')
                ));

                //redirect to index page
                header('Location: index.php?action=added');
                exit;

            } catch(PDOException $e) {
                echo $e->getMessage();
            }
        }
        }

    }

    //check for any errors
    if(isset($error)){
        foreach($error as $error){
            echo '<p class="error">'.$error.'</p>';
        }
    }
    ?>

    <form action='' method='post' enctype="multipart/form-data">

        <p><label>Title</label><br />
        <input type='text' name='postTitle' value='<?php if(isset($error)){ echo $_POST['postTitle'];}?>'></p>

        <p><label>Description</label><br />
        <textarea name='postDesc' cols='60' rows='10'><?php if(isset($error)){ echo $_POST['postDesc'];}?></textarea></p>

        <p><label>Content</label><br />
        <textarea name='postCont' cols='60' rows='10'><?php if(isset($error)){ echo $_POST['postCont'];}?></textarea></p>

        <p><label>Image</label><br />
        <input type="file" name="file" />

        <p><input type='submit' name='submit' value='Submit'></p>

    </form>

</div>

</div>

Assuming $tmp is your uploaded file

First, i recommand you to check the validity of uploaded image. uncomment Exif and php extension (in you php.ini, and restart) To check the image mime type.

Try the same thing with GD php extension (not included with php) Previous detected mime type, can provide you to use the proper extension functions to use for resizing. with GD.

And finally calculating the good preserved ratio to your resize.

if(move_uploaded_file($file_loc,$folder.$final_file))
{
    $tmp = $folder.$final_file;
    $type = exif_imagetype($tmp);
    switch($type)
    {
        case IMAGETYPE_PNG: $orig = imagecreatefrompng($tmp); break;
        case IMAGETYPE_JPEG: $orig = imagecreatefromjpeg($tmp); break;
        case IMAGETYPE_GIF: $orig = imagecreatefromgif($tmp); break;
    }

    //trying to get original size, if not, it's not valid image (cf. security)
    $size   = getimagesize($tmp);
    if(is_bool($size))
        return false;

    $w      = "800"; // this is your ratio fixer;
    $reduce = (($w * 100)/$size[0]);
    $h      = (($size[1] * $reduce)/100);

    $new    = imagecreatetruecolor($w, $h);

    imagecopyresampled($new , $orig, 0, 0, 0, 0, $w, $h, $size[0],$size[1]);

     // save resized 
    imagepng($new, $tmp);

    if(!isset($error))
    {
        try
        {

This is a self made script, but: You can also looking for ImageMagick php ext, more stronger.