I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
<img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>
I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.
The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
echo '<img src="unit_images/' . htmlspecialchars(basename($filename))
. '" />';
}
If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir() to determine the items in the directory):
$files = scandir('unit_images');
Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
$file = $files[i];
$prefix = explode("_", $file)[0];
if ($prefix != $_GET['id'])
{
unset($files[i]);
}
}
$files is now an array of only the file names prefixed with $_GET['id]
My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);
Related
I have an array, which contains amongst other things a file path to a video file. There are various file formats .avi, .mp4 etc etc.
Now I only want to display the rows where the file path's file extension is .mp4.
Currently I'm using a function to extract the file extension, but I'm having trouble doing this on the fly while displaying the rows.
An example of the file path: c:\TempVideoDir\Office-P-cam01-20140826-083016.avi
The function im using to get the file ext:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
echo $just_fileext;
}
Which works fine.
Now I'm querying the database to get the filepath along with other details about the file, and I only want to display the rows where the file path contains a .mp4 file.
I've tried everything I could thing of/find on Google etc but this is what I currently have:
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
if (in_array((get_fileext($row["Filename"])== "mp4"), $result)) {
echo " blah blah
I dont have the option of adding the file extension into the database table as this is backed up automatically by a piece of equipment.
So, whadoyareckon? is it possible to do it on the fly like this?
Any help is much appreciated!
Thanks
I dont think you can use in_array() like that. Its searching the entire index of the array, so when it looks ate $result[] its never going to find $row['filename'] with only an ext.
try this:
//looping through $result array
foreach($result as $row) {
//check if $row['filename'] has a string with a mp4 extension.
if (get_fileext($row["Filename"])== "mp4") {
echo "Row has a filename with the mp4 extension';
also as someone else pointed out fix your get_fileext() method to return something.
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
return $just_fileext;
}
Your function isn't returning a value. It's emitting the value to the output:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
echo $just_fileext;
}
So there's no way for anything invoking that function to see that result. Instead, return the value:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
return $just_fileext;
}
That way the invocation of the function itself evaluates to the returned value, allowing you to use the function in your logic.
You could consider adjusting your database query to only return rows with ".mp4" files.
Change your query to have something like:
filepath = "%.mp4"
In MySQL the % operator is a wildcard, so this will match any strings ending in ".mp4"
I have a folder (blogfiles/posts) with various text files, numbered (1.txt, 2.txt, 3.txt...) and they each hold a post for a blog (I haven't learned SQL yet). I'm trying to make a search engine for it that will take a query from a text box (done with this part), then search the files for each word in the query, and return the results (possibly in order of the number of times the word occurs).
Each text file looks like this:
Title on Line 1
Date Posted on Line 2 (in Month Date, Year form)
Post body to search on lines 3 and up
I currently have this code:
<?php
$q = $_GET["q"];
$qArray = explode(" ", $q);
//preparing files
$post_directory = "blogfiles/posts/";
$files = scandir($post_directory, 1);
$post_count = (count($files)) - 2;
$files = array_pop($files); // there are 2 server files I want to ignore (#1)
$files = array_pop($files); // there are 2 server files I want to ignore (#2)
foreach ($files as $file) {
//getting title
$post_path = $post_directory . $file;
$post_filecontents = file($post_path);
$post_title = $post_filecontents[0];
echo "<tr><td>" . $post_title . "</td></tr>";
}
if ($post_count > 2) {
$postPlural = "s";
}
echo "<tr><td>" . $post_count . " post" . $postPlural . ".";
?>
I'll apologize now for the formatting, I was trying to separate it to troubleshoot.
Any help to get this working would be greatly appreciated.
There are many ways to search files.
use preg_match_all function to match pattern for each file.
use system() function to run external command like grep (only available under *nix).
use strpos function ( not recommended because of low performance and lack of support of pattern ).
If you will face a big traffic you'd better use pre-build indexes to accelerate the search. for example split the posts into tokens ( words ) and add position info along with the words, when user search the some words you can just split the words first and then look for the indexes. It's simpler to discribe this method than to implement it. You may need a existing full-text search engine like Apache Lucene.
So, this is the only issue I am having left to fix on my site. When it fetches a post from the database and is then called to parse/replace the URL as a it has a problem. The problem is only with duplicates or image names containing a space in them.
$result = mysql_query("SELECT * FROM posts ORDER BY postid DESC");
while($row = mysql_fetch_array($result))
{
$str = $row['post_content'];
$str = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#', function($arr)
{
if(strpos($arr[0], 'http://') !== 0)
{
$arr[0] = 'http://' . $arr[0];
}
$url = parse_url($arr[0]);
// images
if(preg_match('#\.(png|jpg|gif)$#', $url['path']))
{
return '<img src="'. $arr[0] . '" /><br /><br />';
}
Here is what it does for the first uploaded image:
http://domain.com/server/php/files/filename.jpg
Here is what it does for the second uploaded image:
http://domain.com/server/php/files/filename http://(1).jpg
I need to either control the naming convention for how names the file or control how it reads the spaces in the URL.
in your post there are two question :
How to read spaces in url
answer : you can use urlencode() function.
naming convention for file
there may be following options :
a. either don't allow space in file name . remove space with the help of regex
b. either check the file name first in db, if it exist then append 1 or 2 in filename.
if you have any question, let me know
My website has an image in a certain place and when a user reloads the page he should see a different image on the same place. I have 30 images and I want to change them randomly on every reload. How do I do that?
Make an array with the "picture information" (filename or path) you have, like
$pictures = array("pony.jpg", "cat.png", "dog.gif");
and randomly call an element of that array via
echo '<img src="'.$pictures[array_rand($pictures)].'" />';
Looks weird, but works.
The actual act of selecting a random image is going to require a random number. There are a couple of methods that can help with this:
rand() is used to generate a random number.
array_rand() is used to select a random element's index from an array.
You can think of the second function as a shortcut for using the first if you're specifically dealing with an array. So, for example, if you have an array of image paths from which to select the one you want to display, you can select a random one like this:
$randomImagePath = $imagePaths[array_rand($imagePaths)];
If you're storing/retrieving the images in some other way, which you didn't specify, then you may not be able to use array_rand() as easily. But, ultimately, you need to generate a random number. So some use of rand() would work for this.
If you store the information in your database, you can also SELECT a random image:
MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
PgSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
Best,
Philipp
An easy way to create random images on popup is this method below.
(Note: You have to rename the images to "1.png", "2.png", etc.)
<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>
This method is simple and I use this every time when I need a random image.
Hope this helps! ;)
I've recently written this which loads a different background on every pageload. Just replace the constant with the path to your images.
What it does is loop through your imagedirectory and randomly picks a file from it. This way you don't need to keep track of your images in an array or db or whatever. Just upload images to your imagedirectory and they will get picked (randomly).
Call like:
$oImg = new Backgrounds ;
echo $oImg -> successBg() ;
<?php
class Backgrounds
{
public function __construct()
{
}
public function succesBg()
{
$aImages = $this->_imageArrays( \constants\IMAGESTRUE, "images/true/") ;
if(count($aImages)>1)
{
$iImage = (int) array_rand( $aImages, 1 ) ;
return $aImages[$iImage] ;
}
else
{
throw new Exception("Image array " . $aImages . " is empty");
}
}
private function _imageArrays( $sDir='', $sImgpath='' )
{
if ($handle = #opendir($sDir))
{
$aReturn = (array) array() ;
while (false !== ($entry = readdir($handle)))
{
if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
{
$aReturn[] = $sImgpath . $entry ;
}
}
return $aReturn ;
}
else
{
throw new Exception("Could not open directory" . $sDir . "'" );
}
}
}
?>
My name is Shruti.I'm new to php. I have a program which displays images randomly, there are about 200 images in my program.I want to display the random images with out repetition, can any one please help with this. here is my code.
Appreciate your help
Thank you.
I don't know whats about the $img_id but you could consider to use shuffle().
shuffle($file_array);
But then you loose the connection to $img_id. You could (I am not sure if this is the best solution), build your array this way:
$file_array = array(
array("images/bag200.bmp", 1),
array("images/bag178.bmp", 1),
array("images/bag004.bmp", 0,
...
);
In the long run, it is probably better to store all the image paths in a CSV file or even a database. Believe me, you don't want to maintain an array with > 200 entries manually ;)
You can loop over images this way (they are in random order now):
<?php foreach($file_array as $image): ?>
<img src="<?php echo $image ?>" />
<?php endforeach; ?>
If you only want to display a subset of the images, randomly chosen, you can do this:
$n = 20; // want to display 20 images
$rand = array_rand(range(0,200), $n); // draw keys randomly
shuffle($rand); //shuffle keys
foreach($rand as $r) {
echo '<img src="' . $file_array[$r] . '" />';
}
Some comments on your code:
$ran = array_rand($file_array);
$ran contains a key randomly chosen from the images.
for ($i=0;$i<200;$i++) {
//while (in_array($tst,$rand_array)){
$tst = $file_array[$ran];
$id = $img_id[$ran];//}
$rand_array[] = $tst;
$rand_id[] = $id;
}
You always pick the same entry from $file_array and $image_id because you never change $ran. That is way you get the same image 200 times.
If you want randomness but require uniqueness, you are looking for a quasi-random number generator. There are many different types with different properties. Look here for information on creating an algorithm: http://www.mathworks.nl/access/helpdesk/help/toolbox/stats/br5k9hi-8.html