Web Analytics Made Easy -
StatCounter PHP gallery optimsation - CodingForum

Announcement

Collapse
No announcement yet.

PHP gallery optimsation

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • PHP gallery optimsation

    Hey!
    I have a problem with a PHP gallery that I use to monitor my 3D printer.
    Pictures taken at regular intervals while the printer is active, but they are presented in random order in the gallery.
    I need to get them in descending order so that the flow can be observed.
    Name of the images is set like this: 2016-10-06_0321.jpg where 0321 is the time the picture is taken.

    Is this possible?




    <head>
    <title>Gallery</title>
    </head>
    <body>
    <?php
    $folder_path = 'webcam/';

    $num_files = glob($folder_path . "*.{JPG,jpg}", GLOB_BRACE);

    $folder = opendir($folder_path);

    if($num_files > 0)
    {
    while(false !== ($file = readdir($folder)))
    {
    $file_path = $folder_path.$file;
    $extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
    if($extension=='jpg')
    {
    ?>
    <a href="<?php echo $file_path; ?>"><img src="<?php echo $file_path; ?>" height="250" /></a>
    <?php
    }
    }
    }
    else
    {
    echo "the folder was empty !";
    }
    closedir($folder);
    ?>
    </body>

  • #2
    Example

    This is a example:

    Click image for larger version

Name:	3dprinter.jpg
Views:	1
Size:	37.5 KB
ID:	2270513

    Comment


    • #3
      First you need all your options in one array.
      PHP Code:
      $arr[] = ['filename' =>'abc','filepath'=>'def']; 
      After that you need a sorting function
      PHP Code:
      function sortbyDate($ab,$bb)
      {
        
      $a strtotime($ab['filename']);
        
      $b strtotime($bb['filename']);

        if (
      $a==$b) return 0;
        return (
      $a<$b)?-1:1;
      }

      usort($arr,"sortbyDate");

      //$arr is now sorted by date and you can print it out 
      You will need to use explode to get the actual sortnumber.
      Last edited by Vege; Oct 6, 2016, 08:18 AM.
      Don't use old mysql library
      The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets
      When a white horse is not a horse

      Comment


      • #4
        Thanks for your reply!
        Im not very familiar with php, can I use my old code or do I need to start from blank?

        Can you please show me how to use your example in context with the code I got, if its possible.

        Comment


        • #5
          PHP Code:
          <?php
          $folder_path 
          'fold/';

          $num_files glob($folder_path "*.{JPG,jpg}"GLOB_BRACE);

          $folder opendir($folder_path);

          if(
          $num_files 0)
          {
            while(
          false !== ($file readdir($folder)))
            {
          //
              
          $file_path $folder_path.$file;
              
          $extension strtolower(pathinfo($file ,PATHINFO_EXTENSION));
              
          $file pathinfo ($filePATHINFO_BASENAME);
              if(
          $extension=='jpg')
              {
                
          $arr[] = ['file' =>$file,'filePath'=>$file_path];
              }
            }
          }
          else
          {
            echo 
          "the folder was empty !";
          }



          closedir($folder);

          function 
          sortbyFileNamePart( array $ab, array $bb)
          {
            
          $a explode('_',$ab['file'])[1];
            
          $b explode('_',$bb['file'])[1];
            if ((int)
          $a==(int)$b) return 0;
            return ((int)
          $a<(int)$b)?-1:1;
          }


          usort($arr,"sortbyFileNamePart");



          foreach(
          $arr as $a) {
            echo 
          "<a href=\"{$a['filePath']}\"><img src=\"{$a['filePath']}\"; height=\"250\" /></a>";
          }
          Don't use old mysql library
          The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets
          When a white horse is not a horse

          Comment


          • #6
            Thanks!

            Thanks! It works perfect!


            Originally posted by Vege View Post
            PHP Code:
            <?php
            $folder_path 
            'fold/';

            $num_files glob($folder_path "*.{JPG,jpg}"GLOB_BRACE);

            $folder opendir($folder_path);

            if(
            $num_files 0)
            {
              while(
            false !== ($file readdir($folder)))
              {
            //
                
            $file_path $folder_path.$file;
                
            $extension strtolower(pathinfo($file ,PATHINFO_EXTENSION));
                
            $file pathinfo ($filePATHINFO_BASENAME);
                if(
            $extension=='jpg')
                {
                  
            $arr[] = ['file' =>$file,'filePath'=>$file_path];
                }
              }
            }
            else
            {
              echo 
            "the folder was empty !";
            }



            closedir($folder);

            function 
            sortbyFileNamePart( array $ab, array $bb)
            {
              
            $a explode('_',$ab['file'])[1];
              
            $b explode('_',$bb['file'])[1];
              if ((int)
            $a==(int)$b) return 0;
              return ((int)
            $a<(int)$b)?-1:1;
            }


            usort($arr,"sortbyFileNamePart");



            foreach(
            $arr as $a) {
              echo 
            "<a href=\"{$a['filePath']}\"><img src=\"{$a['filePath']}\"; height=\"250\" /></a>";
            }

            Comment


            • #7
              glob() returns an array of the matching filenames, sorted alphabetically. why aren't you just using that array of filenames?
              Finding out HOW to do something is called research, i.e. keep searching until you find the answer. After you attempt to do something and cannot solve a problem with it yourself, would be when you ask others for help.

              Comment


              • #8
                Originally posted by CFMaBiSmAd View Post
                glob() returns an array of the matching filenames, sorted alphabetically. why aren't you just using that array of filenames?
                Nice catch. I guessed it was OS dependent and did not mention it.
                Don't use old mysql library
                The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets
                When a white horse is not a horse

                Comment


                • #9
                  Originally posted by Vege View Post
                  Nice catch. I guessed it was OS dependent and did not mention it.
                  Is there anything I should change? You are talking above my understanding

                  Comment


                  • #10
                    If all the filenames are in the format you have shown, they will sort alphabetically by the date, then the time within each date. The glob() statement you are using will only find .jpg or .JPG files and return the array of path/files sorted alphabetically.

                    The following is all the code you should need -
                    PHP Code:
                    <head>
                    <title>Gallery</title>
                    </head>
                    <body>
                    <?php
                    $folder_path 
                    'webcam/';

                    $files glob($folder_path "*.{JPG,jpg}"GLOB_BRACE);

                    if(
                    $files)
                    {
                        foreach(
                    $files as $file)
                        {
                            echo 
                    "<a href='$file'><img src='$file' height='250' /></a>";
                        }
                    }
                    else
                    {
                        echo 
                    "the folder was empty !";
                    }
                    ?>
                    </body>
                    Finding out HOW to do something is called research, i.e. keep searching until you find the answer. After you attempt to do something and cannot solve a problem with it yourself, would be when you ask others for help.

                    Comment


                    • #11
                      @CFMaBiSmAd has it right, if the filenames are date and time like you say they are, they should already be in that sort order. You shouldn't HAVE to be doing anything to them but outputting them -- though it is in ASCENDING order from oldest to newest. You want newest to oldest either use a counter to walk the array backwards, or just use a normal sort to flip it.

                      Though I'd lose all the double-quote nonsense for comma delimits, it's cleaner and runs a hair faster. I'd also be trapping the === false condition since that's an error state... and since there are characters that are valid in filenames that could screw up HTML, don't forget to htmlspecialchars the output... and one should probably normalize the path back into the result.

                      Code:
                      <?php
                      $folderPath = 'webcam/';
                      $files = glob($folderPath . "*.{JPG,jpg}", GLOB_BRACE);
                      
                      if ($files === false) echo 'Error encountered accessing image directory!';
                      else if (!count($files)) echo 'Image directory is empty!';
                      else {
                      	$files = rsort($files);
                      	foreach ($files as $fileName) {
                      		$fileName = $folderPath . htmlspecialchars($fileName);
                      		echo '
                      		<a href="', $fileName, '">
                      			<img
                      				src="', $fileName, '"
                      				alt="Describe these, ALT is NOT optional!"
                      				height="250"
                      			>
                      		</a>';
                      	}
                      }
                      The rsort being what flips them around to be newest to oldest assuming your filename convention is exactly as specified.
                      Walk the dark path, sleep with angels, call the past for help.
                      https://cutcodedown.com
                      https://medium.com/@deathshadow

                      Comment


                      • #12
                        Oh, and if you really did want to sort them by time of day ignoring the date, the usort for that could be a lot simpler.

                        Code:
                        <?php
                        $folderPath = 'webcam/';
                        $files = glob($folderPath . "*.{JPG,jpg}", GLOB_BRACE);
                        
                        if ($files === false) echo 'Error encountered accessing image directory!';
                        else if (!count($files)) echo 'Image directory is empty!';
                        else {
                        	function sortByTime($a, $b) {
                        		return
                        			((int) substr(strrchr('_', pathinfo($a, PATHINFO_FILENAME )), 1)) -
                        			((int) substr(strrchr('_', pathinfo($b, PATHINFO_FILENAME )), 1));
                        	}
                        	$files = usort($files, 'sortByTime');
                        	foreach ($files as $fileName) {
                        		$fileName = $folderPath . htmlspecialchars($fileName);
                        		echo '
                        		<a href="', $fileName, '">
                        			<img
                        				src="', $fileName, '"
                        				alt="Describe these, ALT is NOT optional!"
                        				height="250"
                        			>
                        		</a>';
                        	}
                        }
                        Assuming the values are already numeric only being the time, that should work. pathinfo strips off the extension, strrchr gives us everything after the last underscore, substr index 1 strips off that underscore, then we typecast to integer. With usort callbacks all positive numbers are a > b, all negative numbers are a < b, and zero is equals, so we don't need to get fancy with if statements or ternary operators, just subtract! You want reverse order, just swap $a with $b inside that function.
                        Walk the dark path, sleep with angels, call the past for help.
                        https://cutcodedown.com
                        https://medium.com/@deathshadow

                        Comment

                        Working...
                        X