echo 15 random lines of html files - php

I have to do a php assignment for college.
How would I echo 15 random lines of a html file if there is a movie script text and a image with the same in the same folder?
What I have tried so far:
$folder = 'Filmnoir/';
$hitchcock ='Hitchcock/';
$shakespear ='Shakespear/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$file2 = glob ($hitchcock.$filetype);
$file3 = glob ($shakespear.$filetype);
$count = count($files);
$count1 = count($file2);
$count2 = count($file3);
$scripttype ='*.html';
$Scripts = glob($ScriptFilmNoir.$scripttype);
$Scripts=file_get_contents("DoubleIndemnity.html");
if($_POST['radio1']=="0"){
if(($i %1)==0){
for ($i = 0; $i < $count; $i++)
{
echo '<div class="image2">';
echo '<img src="'.$files[$i].'" />';
echo '</div>';
if (condition) {
include 'DoubleIndemnity.html'; }
echo '</td></tr>';
}
echo '<div class="Passwordtext">';
echo 'Type in password to view full Script';
echo '</div>';
echo "<label><div class=\"password\"><input type='password' name='code' value='code'/></div></label>";
echo "<form method='POST' action='ca1_result.php'>";
echo "<div class=\"SubmitIt\"><input type='submit' name='submitScript' value='Submit Password'/></div>";
echo '</form>';
}
}
if($_POST['radio1']=="1"){
echo '<div class="Sorrytext">';
echo 'We apologize. No script available for this movie.';
echo '</div>';
}
if($_POST['radio1']=="2"){
echo '<div class="Sorrytext">';
echo 'We apologize. No script available for this movie.';
echo '</div>';
}
I want to achieve that when there is an image (e.g DoubleIndemnity.png) and movie script (e.g DoubleIndemnity.html) in the same folder that I get 15 random lines of the movie script text plus the image. Could I use the glob function and when yes how would I achieve that?
Can I ask another thing? When I submit the password how to I get then the full movie script?
I tried:
foreach($files as $file2) {
if($_POST['submitPassword']){
if($file2 === '.' OR $file2 === '..' OR $file2 === 'thumbs.db' OR !is_dir($folder.'/'.$file2)) {continue;}
if(file_exists($folder.'/'.$file2.'/doubleindemnity.gif') AND file_exists($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm')) {
echo '<div class="Container">';
echo "<div class='image2'><img src='$folder/$file/doubleindemnity.gif'>";
$lines4 = file($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm');
$count = count($lines4);
for($a = 0;$a < $count;$a++) {
echo substr($lines4[$a],strlen($folder),strpos($lines4[$a], '.')-strlen($folder));
}
echo "</div>";
}
echo "</div>";
}
}
?>
With that code I just get a couple of lines from the html file. I don't want that. I want the full text. And how can I use the string replace function to get rid of the code and just receive the text from the paragraphs?
Cheers:)

This piece of code will loop trough folders in a pre-defined folder (eg: /movies). It will look if whatever is inside is a folder, and if that folder has 2 files: image.png and lines.html. If it has those two files, it'll first place the image, then it'll read the HTML file, and writing down 15 random lines from that file.
<?php
$folder = "movies";
$files = scandir($folder);
foreach($files as $file) {
if($file === '.' OR $file === '..' OR $file === 'thumbs.db' OR !is_dir($folder.'/'.$file)) {continue;}
if(file_exists($folder.'/'.$file.'/image.png') AND file_exists($folder.'/'.$file.'/lines.html')) {
echo "<div class='image2'><img src='$folder/$file/image.png'>";
$lines = file($folder.'/'.$file.'/lines.html');
for($x = 1;$x<=15;$x++) {
echo $lines[rand(0, count($lines)-1)]."<br>";
}
echo "</div>";
}
}

Loops through files in $directory and then outputs 15 random lines into a html variable and if the image exists it adds it to the image html variable. If they are both added it returns the result. (untested but should work)
<?php
//I dont know where you have got some of these variables from
$directory = "Filmnoir";
$ScriptFilmNoir = "DoubleIndemnity";
$scripttype ='html';
$supportedImages = Array("png", "jpg", "jpeg");
$html = "";
$imagehtml = "";
$allFiles = scandir($folder);
$imageFound = 0;
$htmlFound = 0;
foreach($files as $file) {
if($file === '.' || $file === '..' || $file === 'thumbs.db' || is_dir($file)) {
continue;
}
$nameWithoutExtension = substr($file, 0 , (strrpos($file, ".")));
$fileExtension = $id = substr($file, strrpos($file, '.') + 1);
if($nameWithoutExtension == $ScriptFilmNoir){
if($fileExtension == $scripttype){
$htmlFound = 1;
$lines = file($directory . "/" . $ScriptFilmNoir . "." . $scripttype);//file in to an array
$range = range(1, count($lines));
$range = array_flip($range);
$range = array_rand($range, 15);
foreach($range as $line){
$html .= $lines[$value] . PHP_EOL;
}
}elseif(in_array ( $fileExtension , $supportedImages)){
$imageFound = 1;
$imagehtml = "<img src='{$directory}/{$ScriptFilmNoir}.{$fileExtension}' /><br />";
}
}
}
if($imageFound == 1 && $htmlFound == 1){
echo $imagehtml . $html;
}

I think what owen is looking for is a random extract of 15 lines rather than 15 random lines.
Using #ThijmenDF's example, just change
for($x = 1;$x<=15;$x++) {
echo $lines[rand(0, count($lines)-1)]."<br>";
}
to
$random = rand(0, count($lines)-1);
for($x = 1;$x<=15;$x++) {
echo $lines[$random + $x]."<br/>";
}

Related

Issue while embedding css in the php code?

I want to display 2 images with their created time to be displayed parallely in wordpress . So tried to write css (display flex) using 'echo' command . Although logic is correct but tag of the image is not working and there may be other syntactical error.As the beginners please review the code and help me.
In this below, if i close table tag before div it is not working properly.
<?php
$dir = opendir('/var/www/html/data1/products/images/avhrr/rgb');
$files = array();
while (($file = readdir($dir)) !== false)
{
if ($file == '.' || $file == '..' ) continue;
if (is_dir("/var/www/html/data1/products/images/avhrr/rgb/$file")) continue;
$lastModified = filemtime("/var/www/html/data1/products/images/avhrr/rgb/$file");
$files[$file] = $lastModified;
}
closedir($dir);
asort($files);
$files=array_reverse($files);
$count = 0;
foreach ($files as $file => $lastModified)
$name = basename($file);
$str = $name;
$pattern = "/top/i";
if(preg_match_all($pattern, $str, $matches))
{
$file_stats = stat("/var/www/html/data1/products/images/avhrr/rgb/".$name);
echo '<div class="container" style="display:flex">';
echo '<table border="5">';
echo '<tr><td>';
echo 'Daily_RGB : '.date('d-m-Y h:m:i A',$file_stats["mtime"]).PHP_EOL; //Equivalent of filemtime()
echo "<br>";
echo "<a href='/data1/products/images/avhrr/rgb/$file' target='_blank'></a>";
echo "<img src='/data1/products/images/avhrr/rgb/$file' height='450' width='450'/>";
echo '</td></tr>';
echo '</div>';
echo '</table>';
$count++;
}
if ($count == 2) break;
}
?>

Display uploaded file or image in grid in php

I have successfully uploaded some images to the server. Im thinking to display them in my admin page in grid view.. currently it displayed vertically.
Can anyone help?
Thanks in advance for you kind assistance.
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
{
// get file name
echo "File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}
}
}
}
?>
This code works fine but I just don't know to display it in grid or table..
You can achieve that by echoing each table part inside the loop:
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
$numCol = 3;
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
$n = 0;
echo '<table>';
echo '<tr>';
if($files[$i] !='.' && $files[$i] !='..')
{
$n ++;
// get file name
echo "<td>File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'></td>";
if($n % $numCol == 0) echo "</tr><tr>";
}
echo '</tr>';
echo '</table>';
}
}
?>
$numCol defines how many column must have every table's row.
Also, I removed these {} that were useless:
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}

Link list based on directory without file extension and hyphens in php

I am using the following script for listing the files in a particular directory as a hyperlink list.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
echo "<li><a href='$files[$x]'>$files[$x]</a></li>";
}
Please tell us whether the following is possible
1. The file extension should not be displayed
2. I need " " instead of "-" in the file names
If possible how to incorporate it.
Update 2:
Thanks for your kindly help. I followed,
The files names which i have mentioned must not be displayed (like dont display index.php), How do i change the code for this?
<?php
$directory = '';
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", " ", $parts['filename']);
echo "<li>{$name}</li>";
}
?>
Try the following using glob in a loop.
$directory = 'folder/';
foreach (glob($directory . "*.*") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", "", $parts['filename']);
echo "{$name}";
}
Example with your provided code, two lines added pathinfo and a preg_replace.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
$parts = pathinfo($files[$x]);
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li><a href='$files[$x]'>$name</a></li>";
}
Updated:
The following doesn't show the files called index.php, wtf.php, and hide.php
$directory = 'folder/';
$blacklist = array(
'index',
'wtf',
'hide'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}

how to use multiple different a href link on each different images?

how to use multiple different a href link on each different images? and images are getting from the `folder or directory?
Php Code
<?php
$directory = "data/uploads/bottomslider/";
if (glob($directory . "*") != false)
{
$filecount = count(glob($directory . "*"));
}
$files_index = glob("data/uploads/"."bottom"."slider/*.*");
for ($i=0; $i<$filecount; $i++)
{
$num2 = $files_index[$i];
?>
<li class="jcarousel-item"><a href=""><img src="<?php echo $num2;?>"
style="height: 119px!important; width:132px !important;"/></a></li>
<? }?>
For Example
i want like this?
Image1
Image2
Image2
I did not test the code. But this should work. Assuming that the folder "data" is in the root of your webpage.
$directory = "data/uploads/bottomslider/";
if(file_exists($directory)) {
$files = scandir($directory);
$output = "";
foreach($files as $key => $value) {
if($value != '.' && $value != '..' && $value != '.quarantine' && $value != '.tmb') {
$output .= '<li class="jcarousel-item"><a href="/'.$directory.$value.'"><img src="/'.$directory.$value.'"
style="height: 119px!important; width:132px !important;"/></a></li>';
}
}
//$output contains all the images.
echo $output;
}
<?php
$directory = "data/uploads/bottomslider/";
$link = "";
if (glob($directory . "*") != false)
{
$filecount = count(glob($directory . "*"));
}
$files_index = glob("data/uploads/"."bottom"."slider/*.*");
//this array must be same size like number of images
$array1 = array('www.yahoo.com', 'www.google.com', 'www.facebook.com', 'www.stackovrflow.com', 'www.blahblah.com');
for ($i=0; $i<$filecount; $i++)
{
$num2 = $files_index[$i];
$link = $array1[$i];
?>
<li class="jcarousel-item"><a href="<?php echo $link?>"><img src="<?php echo $num2;?>"
style="height: 119px!important; width:132px !important;"/></a></li>
<?php
}
?>
Give full path of link like "https://www.facebook.com/"

Load Random Images from Directory

I'd like to randomly load images from a directory and have a button somewhere that refreshes the entire page. Here's the current code I have now:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
The problem is it loads all 400,000 images at once. I only want 30 to load. 30 random images from the directory. I tried looking up some code such as modifying the above to this:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
if (++$i == 2) break;
}
?>
But it seems to do absolutely nothing.. So if someone can help me get 30 random photos from that directory to load and have some type of reload button, that would be of great help.
Thank you in advance
Here is my solution with a cache:
<?php
define('CACHE_FILE', 'mycache.tmp');
define('CACHE_TIME', 20); // 20 seconds (for testing!)
define('IMG_COUNT', 30);
define('IMG_DIR', '../public/wp-content/uploads/2012/01');
/**
* Loads the list (an array) from the cache
* Returns FALSE if the file couldn't be opened or the cache was expired, otherwise the list (as an array) will be returned.
*/
function LoadListFromCache($cacheFile, $cacheTime)
{
if ( file_exists($cacheFile) )
{
$fileHandle = fopen($cacheFile, 'r');
if ( !$fileHandle )
return false;
// Read timestamp (separated by "\n" from the content)
$timestamp = intval( fgets($fileHandle) );
fclose($fileHandle);
// Expired?
if ( $timestamp+$cacheTime > time() )
return false;
else
{
// Unserialize the content!
$content = file_get_contents($cacheFile);
$content = substr( $content, strpos($content, "\n") );
$list = unserialize($content);
return $list;
}
}
return false;
}
/**
* Caches the passed array
* Returns FALSE if the file couldn't be opened, otherwise TRUE.
*/
function SaveListToCache($cacheFile, $list)
{
$fileHandle = fopen($cacheFile, 'w');
if ( $fileHandle === FALSE ) return false;
fwrite($fileHandle, time());
fwrite($fileHandle, "\n");
fwrite($fileHandle, serialize($list));
fclose($fileHandle);
return true;
}
/**
* Generates the list of all image files (png, jpg, jpeg) and caches it.
* Returns the list as an array.
*/
function GenerateList()
{
$a = array();
$dir = IMG_DIR;
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
SaveListToCache(CACHE_FILE, $a);
return $a;
}
function GetRandomImages($list, $count)
{
$listCount = count($list);
$randomEntries = array();
for ($i=0; $i<$count; $i++)
{
$randomEntries[] = $list[ rand(0, $listCount) ];
}
return $randomEntries;
}
// This code will execute the other functions!
$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);
if ( $list === FALSE )
{
$list = GenerateList();
}
$images = GetRandomImages($list, IMG_COUNT);
foreach ($images as $image)
{
echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';
}
If you have 400,000 images then I think reading the entire directory everytime is going to be an expensive means of showing random images. I would use a database instead and store the file paths in it.
If you want to use your existing code then think of it this way. You have an array of length n containing image names. You want to generate thirty random numbers between 0 and n-1. Then display the image associated with that position in the array. I'm not a php expert, but here is some pseudocode:
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
for ( i=0; i < 30; i++) {
//generate a random number between 0 and N-1
random = rand(0, $a.length - 1);
//display that image in the array
echo "<img src='" . $dir . '/' . $a[random] . "' />";
}
You need to create a new variable for the counter instead of using $i
For example, you can do this instead
$j = 0;
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
$j++;
if ($j >= 30)
{
break;
}
}
EDIT: Perhaps for the random part you can first generate a random number between 0 and n-1 where n is the total number of the images and then just echo out the image from the array with the index number.
Instead of using foreach, I think you'll need a for loop instead.
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 30; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
You should maybe only read 30 file from your directory. Stop looking in the directory when readdir return false or your array's length is 30.
This should work
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle)) && (count($a) <= 30) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
It may not execute (I didn't try). But the idea is here
For randomize the image: shuffle($a) should do the trick
in simplest way ,
you can use
find , sort , head
commands in linux,in conjuction with PHP's built in
exec()
function to get 30 random image links easily , the folowing snippet lists how to do it
(How to get random 30 image links in an array.)
<?php
$picdir = "directory/containing/pictures"; // directory containing only pictures
exec("find " . $picdir . " | sort -R | head -30 ",$links);
while(list($index,$val) = each($links) ) {
echo "<img src =" .$val . "> <br/>"; // shows image
}
?>
Here $links array contain random 30 image names(from folder) with complete path . This is used with img tag in echo to generate images
Here $picdir has the path of the directory having images and it is assumed that dirrectory is having only image files . in other case its only matter of modifying find command to exclude non image files(such as using grep command to exclude )

Categories