rebosha
rebosha

Reputation: 23

Foreach txt and image files with different code blocks

I have a gallery. I would like to glob files into. It works fine for jpg, png etc.

Directory:

1.jpg

2.png

3.jpg ...

Code :

foreach ($gallery as $u)   
{ 
echo'<div class="section active" id="">'; 

foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {

    echo '<div class="slide"><img class="" src="https://onlinegallery.online/'.$filename.'" /></div>';  //slide
}

echo('</div>');
}

I would like to put a txt file to directory and create foreach for txt and image files (Some slides should be a txt files). I don't know how to do that because txt file can't be used in img src tag. It should looks something like this.

Directory:

1.png

2.img

3.txt

4.jpg


$images = '<img class="" src="https://onlinegallery.online/'.$filename.'" />';

$txt = '<div><p>fopen("'.$filename.'", "r");
             echo fread($txt,filesize("'.$filename.'"));
             fclose($txt); </p></div>';

foreach ($gallery as $u)   
{ 
echo'<div class="section active" id="">'; 

foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {

    echo '<div class="slide"> 

//$images or $txt files
//i need txt and images files here

</div>';  //slide
}

echo('</div>');
}

I suppose I'm completely out, but thank you for your advice anyway.

Upvotes: 1

Views: 54

Answers (2)

rebosha
rebosha

Reputation: 23

foreach (glob("$meno/$new/*.{png,jpg,jpeg,gif,txt}", GLOB_BRACE) as $filename) {

        $imgFileType = pathinfo($filename,PATHINFO_EXTENSION);

        $title = basename("$meno/$new/$filename", ".jpg").PHP_EOL;

        if(($imgFileType == 'jpg') || ($imgFileType == 'png') || ($imgFileType == 'jpeg') || ($imgFileType == 'gif')) {
    echo '<div class="slide"><img class="" onclick="fullscreen()" src="https://onlinegallery.online/'.$filename.'" alt="'.$title.'"/><p class="imagetitle">'.$title.'</p></div>'; 
}

        if(($imgFileType == 'txt')) {

    echo '<div class="slide"><p class="txtslide" onclick="fullscreen()">';
    echo filter_var(file_get_contents($filename), FILTER_SANITIZE_STRING);
    echo '</p><p class="imagetitle">'.$title.'</p></div>';     
}


}


echo('</div>');

Upvotes: 0

Cameron Little
Cameron Little

Reputation: 3711

You'll need to read the contents of your text files and output them. Be careful to sanitize the text contents - you don't want to accidentally emit something that's treated as html, especially if the contents are coming from an unknown source (read more).

You'll also need to add an if inside the for loop to determine if you're outputting an image or text. For images, you can keep using your existing code.

For text, something like this might work:

echo htmlentities(file_get_contents($filepath));

Upvotes: 2

Related Questions