1
\$\begingroup\$

This currently works properly, but just takes too long. Some of the functions in it are necessary and need to remain, such as resizing, and double saves. But it probably has room for improvement. I just need it to post image as it does, but faster.

  <?php
 ini_set('memory_limit', '-1');
 $target_dir = "";
 $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
 $uploadOk = 1;
 $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
 // Check if image file is a actual image or fake image
 if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;
}
 }
 // Check if file already exists
 if (file_exists($target_file)) {
     echo "Sorry, file already exists.";
     $uploadOk = 0;
 }



 if ($_FILES["fileToUpload"]["size"] > 50000000000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
 }
 // Allow certain file formats
 if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
 && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";

 echo $imageFileType;
$uploadOk = 0;
 }
 // Check if $uploadOk is set to 0 by an error
 if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
 // if everything is ok, try to upload file


 } else {
if (1==1) {

 $servername = "localhost";
 $username = "dbinfo";
 $password = "dbinfopw";
 $dbname = "dbinfo";

 // Create connection
 $conn = mysqli_connect($servername, $username, $password, $dbname);
 // Check connection
 if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
 }


 $name = ''; $type = ''; $size = ''; $error = '';
     function compress_image($source_url, $destination_url, $quality) {

    $info = getimagesize($source_url);

        if ($info['mime'] == 'image/jpeg')
                $image = imagecreatefromjpeg($source_url);

        elseif ($info['mime'] == 'image/gif')
                $image = imagecreatefromgif($source_url);

    elseif ($info['mime'] == 'image/png')
                $image = imagecreatefrompng($source_url);

        imagejpeg($image, $destination_url, $quality);
    return $destination_url;
}





 $image = imagecreatefromstring(file_get_contents($_FILES['fileToUpload']['tmp_name']));
 $exif = exif_read_data($_FILES['fileToUpload']['tmp_name']);
 if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
    case 8:
        $image = imagerotate($image,90,0);
        break;

    case 3:
        $image = imagerotate($image,180,0);
        break;

    case 6:
        $image = imagerotate($image,-90,0);
        break;


}


 }



 $url = basename( $_FILES["fileToUpload"]["name"]);
 ob_start();
 imagejpeg($image,null,30);
 $image = ob_get_clean();
 ob_end_clean();
 $url = $name = str_replace(' ', '-', $url);
 file_put_contents($url,$image);

 $fn = $_FILES['fileToUpload']['tmp_name'];
 $size = getimagesize($fn);
 $ratio = $size[0]/$size[1]; // width/height
 if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
 }
 else {
$width = 200*$ratio;
$height = 200;
 }
 $sot="1".$url;
 //$src = imagecreatefromstring(file_get_contents($fn));
 $src = imagecreatefromstring(file_get_contents($_FILES['fileToUpload']['tmp_name']));
 $exif = exif_read_data($_FILES['fileToUpload']['tmp_name']);
 if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
    case 8:
        $src = imagerotate($src,90,0);
        break;

    case 3:
        $src = imagerotate($src,180,0);
        break;

    case 6:
        $src = imagerotate($src,-90,0);
        break;


}


 }
 $dst = imagecreatetruecolor($width,$height);
           imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
 imagedestroy($src);


 $sot = $name = str_replace(' ', '-', $sot);
 imagepng($dst,$sot);




 echo "Upload was successful. now click home where you can search, and      reserve placeprints! ";
 header( "refresh:2;url=../index.php" );
 ?><u><A HREF="../">Home</A></u><br><?php
 $postnf = $_GET["na"];
 if ($postnf == "1"){


                                                $db_name     = 'dbinfo';
                                                $db_user     = 'dbinfo';
                                                $db_password = 'dbinfopw';
                                                $server_url  = 'localhost';

                                                $mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);

                                                /* check connection */
                                                if (mysqli_connect_errno()) {
                                                    error_log("Connect failed: " . mysqli_connect_error());
                                                    echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
                                                } else {
                                                    $stff= preg_replace('/[0-9]+/', '', ( $_POST['lname']));
                                                         $stmt = $mysqli->prepare("INSERT INTO ffff_ms (`fdress`, `u_id`, `te`, `acon`,`ac_id`,`cont`, `lgi`,`lti`, `ie_url`, `numid`, `uname`,`imrlo`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
                              $tom = "web user";
                  $toml = "1";
 $time = date("d:m:y:h:i:sa");
 $action = "web add";
 $carddd ="http://www.placeprint.xyz/images/".$sot;
 $safea = $name = str_replace(' ', '-', $carddd);
 $cardddf ="http://www.placeprint.xyz/images/".$url;
 $safeaf = $name = str_replace(' ', '-', $cardddf);
 $content= $_POST["content"];
 $name= $_POST["name"];
                                                              $stmt->bind_param('ssssssssssss', $tom, $name, $time, $action, $action,      $content, $toml, $tom, $safeaf, $name , $name, $safea);

   $postn = $_GET["content"];
 $setthispostverifyok = 2;
 //echo "ssp".$postn;
 $str = ltrim($postn);
 $good = urlencode($str);
 $tom1f = "learn about their placeprints here! ";
                                 $carddd = "http://placeprint.xyz     /?name=". $good . "&nafme=2 ".$str." ".$tom1f ;
                // echo "ko";                 

                 //   $til="http://placeprint.xyz/?name=". $str . "&nafme=2 #placeprint ";    


                                                    $stmt->execute();

                                                    if ($stmt->error) {error_log("Error: " . $stmt->error); }

                                                    $success = $stmt->affected_rows;

                                                    /* close statement and connection */
                                                    $stmt->close();



 }
                                                    }


 }





} 

 header( "refresh:2;url=../index.php" );

 ?>
  <style type="text/css">
 body {
   background-color: #eee;
 }

 </style>


 <body> </body>
\$\endgroup\$
  • 2
    \$\begingroup\$ Profile the code: add some calls to microtime() at key points and log the results. I suspect your real problem is the time required to upload the image, and changing this code won't affect that much. \$\endgroup\$ – user65045 Jul 27 '15 at 1:57
  • \$\begingroup\$ its YOUR job to find out, not ours, start benchmarking \$\endgroup\$ – Dagon Jul 27 '15 at 1:57
  • \$\begingroup\$ correct Hobo, that is what i am trying to fix, trying to make upload take less than 5 seconds. its is around 12-15 now. \$\endgroup\$ – PlacePrint App Jul 27 '15 at 1:58
  • \$\begingroup\$ so you know its not resizing? or db insertion? \$\endgroup\$ – Dagon Jul 27 '15 at 1:59
  • \$\begingroup\$ well it is resizing, and it is doing db insertion. it just needs to be faster. Is there a bad practice somewhere in the code above? \$\endgroup\$ – PlacePrint App Jul 27 '15 at 1:59
1
\$\begingroup\$

Personally I'd look at re-architecting the code to allow an asynchronous resize operation.

So you could save the image as it, store it unprocessed and return very quickly. Then, using either a queue or a simple maintenance script, process it in the background.

Add a status field to your image table to output a placeholder if the image is accessed before it's been properly resized.

\$\endgroup\$
1
\$\begingroup\$

Building on what others have said, I would for sure do this in the background. There are a number of mature message queues that are very easy to setup and get running.

RabbitMq, is one that I am currently using and although it looks daunting at first it was actually quite easy to get running, on both Windows and Linux.

There are many advantages of using a existing queuing system, but of them the biggest is that you don't have to code maintaining the state of a database style queue. Which at first seems a fairly trivial task, depending on how robust you need the system to be, in can quickly get out of control. A pre-built solution allows you to focus on building the task and not the architecture of it so much. There will be some things specific to your use case but, you don't have to worry about an image ( message ) being sent to more workers then it needs to be sent to for example.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.