title: Resize images and fit each image into the square mantaining aspect ratio (backend)
body: <p>I don't have any experience with PHP and images in general, but I have a need to resize all images into the square when they get uploaded.</p>
  
  <p>Since I have multiple products and they have different pictures that comes in different sizes, I think that the best approach is to 'standardize' them during the upload by taking an image and 'fitting' it into the 800x800 white square while maintaining the aspect ratio (if longest size >800 then downsize, if longest size &lt;800, then re-size).</p>
  
  <p>My initial solution was created via JavaScript, where I tried to find the biggest picture and resize all other images according to it. Although, it is not very useful and can be faulty since if there is a delay in image load, images might not be loaded for JS to perform the operation, thus not showing images at all.</p>
  
  <pre><code>$product = getProductById($productid);
  
  $filesArray = array();
  
  
  if (isset($_GET['files']) &amp;&amp; $productid &gt; 0) {
      $error = false;
      $files = array();
      $fileName = '';
  
      $uploaddir = "../images/products/";
      foreach ($_FILES as $file) {
          $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
          $random_name = $widgets-&gt;randomFileName();
          $randomFullFileName = $productid .'_'. $random_name . '.' . $ext;
  
          //copy to location
          //----------------
          //HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
          //----------------
          if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
  
              //save to database
              $image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
  
              if ($image_id &gt; 0) {
                  echo 'Added new image';
              } else {
                  echo 'Error, unable to add. &lt;br&gt; Please try again.';
              }
          } else {
              echo 'Error, unable to add. &lt;br&gt; Please try again.';
          }
      }
  }
  </code></pre>
  
  <p>Before: 600x300
  <a href="https://i.stack.imgur.com/PzImZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PzImZ.jpg" alt="BEFORE"></a></p>
  
  <p>After: 800x800 with white borders to fill-in the space
  <a href="https://i.stack.imgur.com/krLQS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/krLQS.jpg" alt="AFTER"></a></p>