Home > Mobile >  str_contains() gives HTTP ERROR 500 | Wordpress
str_contains() gives HTTP ERROR 500 | Wordpress

Time:04-06

I am trying to get list of all those files whose extension is jpeg,jpg or png and title contains '100x100' text.

I can easily get the list of files filtering by their extension, that's working fine but when I add a condition into it && str_contains($value,'100x100') then page is not working and gives HTTP ERROR 500

function:

function scan_files(){
    $upload_dir = wp_upload_dir();
    $folder = $upload_dir['basedir'];
    $files = list_files( $folder );
    
   foreach($files as $value){
    if(pathinfo($value, PATHINFO_EXTENSION)=='jpeg'||pathinfo($value, PATHINFO_EXTENSION)=='jpg'||pathinfo($value, PATHINFO_EXTENSION)=='png' && str_contains($value,'100x100')){

        $filtered_files[] = $value;
            }
    
        }
        echo "<pre>";
        print_r($filtered_files);
    }

Can anyone help?

UPDATE

According @luk2302 's comment I have corrected the ) issue and page is working fine but values are not getting filtered, also according to @CBroe 's comment, I am using php7 so I replaced str_contains with strpos but still it's not giving expected results.

New Code:

function scan_files(){
    $upload_dir = wp_upload_dir();
    $folder = $upload_dir['basedir'];
    $files = list_files( $folder );
    
   foreach($files as $value){
    if(pathinfo($value, PATHINFO_EXTENSION)=='jpeg'||pathinfo($value, PATHINFO_EXTENSION)=='jpg'||pathinfo($value, PATHINFO_EXTENSION)=='png' && strpos($value,'100x100')!==false){

        $filtered_files[] = $value;
            }
    
        }
        echo "<pre>";
        print_r($filtered_files);
    }

CodePudding user response:

Change this line:

if(pathinfo($value, PATHINFO_EXTENSION)=='jpeg'||pathinfo($value, PATHINFO_EXTENSION)=='jpg'||pathinfo($value, PATHINFO_EXTENSION)=='png' && strpos($value,'100x100')!==false){

To:

if((pathinfo($value, PATHINFO_EXTENSION)=='jpeg'||pathinfo($value, PATHINFO_EXTENSION)=='jpg'||pathinfo($value, PATHINFO_EXTENSION)=='png') && strpos($value,'100x100')!==false){

Notice the extra parentheses around your pathinfo statements. You want to check if any of the extensions are true AND the path contains your key value. Your original code would only filter on filename if the extension was png.

  • Related