Display array rows only if a file path has a certain extension - php

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"

Related

Optimising a script to scan files in a folder

I have my folder /images (with ~ 95.000 files), and i check every file if is in the database.
Table : images
Row : hash
The folder containt all my image with sha1 name.
I use shuffle($images); to make sure the verification is random, otherwise it only verifies the first 35,000 images.
If I go over 35,000 checks, the script puts a timeout and the page blocks it.
Example name of an image : d0a0bb3149bea2335e8784812fef706ad0a13156.jpg
My Script :
I select the images in the database
I'm putting it in a array
I make the array random (to avoid always checking the first 35,000
images)
I create a array of images file in the folder /images
I check for missing database files using the array created by the
opendir(); function
I display the answer
<?php
set_time_limit(0);
$images = [];
$q = $mysqli->query('SELECT hash FROM images');
while($r = $q->fetch_assoc())
{
$images[] = $r['hash'].'.jpg';
}
shuffle($images);
$i_hors_bdd = 0;
$images_existent_hors_bdd = [];
if($dh = opendir($_SERVER['DOCUMENT_ROOT'].'/images'))
{
while(($file = readdir($dh)) !== false)
{
if(!in_array($file, $fichiers_a_exclures))
{
if(!is_sha1($file) OR !in_array($file, $images))
$images_existent_hors_bdd[] = '<p>Name of File: '.$file.'</p>';
}
if($i_hors_bdd > 35000)
{
break;
}
$i_hors_bdd++;
}
}
closedir($dh);
if(count($images_existent_hors_bdd) > 0)
{
echo '<p>Image exist, but not in the databse.</p>';
sort($images_existent_hors_bdd);
foreach($images_existent_hors_bdd as $image_existe_hors_bdd)
echo $image_existe_hors_bdd;
}
else
echo '<p>All images are in datase.</p>';
echo '<p>'.$i_hors_bdd.' images checked.</p>';
So my question is: How can I optimize this script to improve the speed of the script to allow checking more images without blocking the script? Knowing that my VPS is not very powerful and I don't have SSD.
Here are some things to consider or try:
Concatenate '.jpg' to hash in the sql, then use fetch_all into a numeric array.
use scandir to build an array of files in the directory
use array_diff to remove $fichiers_a_exclures and $images
iterate over this smallest array to do the sha1 test

name of images from folder not printed on screen in php

I have an html file and i have done the code for printing the names of images from a folder in PHP , but it is not printing the values to screen. if i echo any other thing it is printed on screen.
i have the set the server using xampp.
how to correct this, i make the names of images from that folder printed on screen?
do i need to do anything extra
im a newbie in php. how can i achieve this?
<?php
function findImagesInFolder()
{
$folder = $_GET['C:\xampp\htdocs\firstsite'];
$images = glob($folder . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
echo json_encode($images);
exit();
}
?>
It seems you have misused the $_GET variable.
I thing you want to just use the string value, ie.:
$folder = 'C:\xampp\htdocs\firstsite';
And note, the exit() terminates whole script after printing the json_encoded string.
So, to make the function reusable change it to get the path as a parameter $folder:
<?php
function findImagesInFolder($folder, $filter = '*.*')
{
// note, here we expect the path does not trail with backslash
$images = glob($folder . '\\' . $filter, GLOB_BRACE);
return json_encode($images);
}
// call the function with actual path to scan:
$path = 'C:\xampp\htdocs\firstsite';
$filter = '{*.png,*.jpg,*.jpeg,*.gif}';
echo findImagesInFolder($path, $filter);
?>
Note: output as [] means empty array encoded to JSON.

Using PHP how can you tell if the image already exists on your server regardless of name?

I have seen several websites where if you upload an image and an identical image already exists on there servers they will reject the submission. Using PNGs is there an easy way to check one image against a massive folder of images?
http://www.imagemagick.org/discourse-server/viewtopic.php?t=12618
I did find this with imagemagick, but I am looking for one vs many and not one to one a million
You can transform the file content into a sha1. That will give you a way to identify two pictures strictly identical.
see http://php.net/manual/fr/function.sha1-file.php
Then after you save it into a NFS, or use some kind of database to test if the hash already exists.
Details of the images are probably maintained in a database; while the images are stored in the filesystem. And that database probably has a hash column which is used to store an md5 hash of the image file itself, calculated when the image is first uploaded. When a new image is uploaded, it calculates the hash for that image, and then checks to see if any other image detail in the database has a matching hash. If not, it stores the newly uploaded image with that hash; otherwise it can respond with details of the previous upload. If the hash column is indexed in the table, then this check is pretty quick.
If I understood your question correctly. You want to find out if a specific image exists in a Directory with so many images, right? If so, take a look at the solution:
<?php
// CREATE A FUNCTION WHICH RETURNS AN ARRAY OF ALL IMAGES IN A SPECIFIC FOLDER
function getAllImagesInFolder($dir_full_path){
$returnable = array();
$files_in_dir = scandir($dir_full_path);
$reg_fx = '#(\.png|\.jpg|\.bmp|\.gif|\.jpeg)#';
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $dir_full_path . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && preg_match($reg_fx, $val) ){
$regx_dot_wateva = '/\.{2,4}$/';
$regx_dot = '/\./';
$regx_array = array($regx_dot_wateva, $regx_dot);
$replace_array = array("", "_");
$return_val = preg_replace($regx_array, $replace_array, $val);
$returnable[$return_val] = $temp_file_or_dir ;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return $returnable;
}
// CREATE ANOTHER FUNCTION TO CHECK IF THE SPECIFIED IMAGE EXISTS IN THE GIVEN DIRECTORY.
// THE FIRST PARAMETER SHOULD BE THE RESULT OF CALLING THE PREVIOUS FUNCTION: getAllImagesInFolder(...)
// THE SECOND PARAMETER IS THE IMAGE YOU WANT TO SEARCH WHETHER IT EXISTS IN THE SAID FOLDER OR NOT
function imageExistsInFolder($arrImagesInFolder, $searchedImage){
if(!is_array($arrImagesInFolder) && count($arrImagesInFolder) < 1){
return false;
}
foreach($arrImagesInFolder as $strKey=>$imgPath){
if(stristr($imgPath, $searchedImage)){
return true;
}
}
return false;
}
// NOW GET ALL THE IMAGES IN A SPECIFIED FOLDER AND ASSIGN THE RESULTING ARRAY TO A VARIABLE: $imgFiles
$imgFolder = "/path/to/directory/where/there/are/images";
$arrImgFiles = getAllImagesInFolder($imgFolder);
$searchedImage = "sandwich.jpg"; //<== OR EVEN WITHOUT THE EXTENSION, JUST "sandwich"
// ASSUMING THE SPECIFIC IMAGE YOU WANT TO MATCH IS CALLED sandwich.jpg
// YOU CAN USE THE imageExistsInFolder(...) FUNCTION TO RETURN A BOOLEAN FLAG OF true OR false
// DEPENDING ON IF IT DOES OR NOT.
var_dump($arrImgFiles);
var_dump( imageExistsInFolder($arrImgFiles, $searchedImage) );

php check if file exist: check only portion

in php we can check if file exist using
if(file_exists("destination/"))
{
condition
}
but what I wanted to do is...
for example I already have this file on my destination
hello_this_is_filename(2).doc
how would I know if there is a file in that directory having a name containing a character
hello_this_is_filename
I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into
hello_this_is_filename(3).doc
I also need to count the existence of my search so I know what number I'm going to put like
(3), (4), (5) and so on
any help?
Use glob.
if (count(glob("destination/hello_this_is_filename*.doc"))) {
//...
}
Leveraging Marc B's suggestion and xdazz, I would do something as follows:
<?php
$files = glob("destination/hello_this_is_filename*");
if (count($files)) {
sort($files);
// last one contains the name we need to get the number of
preg_match("([\d+])", end($files), $matches);
$value = 0;
if (count($matches)) {
// increment by one
$value = $matches[0];
}
$newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
?>
Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...

is_dir doesn't work with for loop

I'd like to loop through images and thumbnails from a folder and insert them into a database.
I want to use is_dir to filter out directories.
I have:
$images = scandir('./images/all_comics/');
$thumbs = scandir('./images/thumbnails/');
for($x=0; $x<count($images); $x++)
{
if(!is_dir($images[$x]))
{
//This shows all images WITHOUT directories
echo $images[$x];
//This is STILL adding images AND directories to database
mysql_query("INSERT INTO images (imgpath, thumbpath) VALUES ('$images[$x]', '$thumbs[$x]')");
}
}
I have a check in there directly after !is_dir, echo $images[$x] ,which echos out all images without the directories, as desired.
But when I check the insert in the database, I see that the directories have been added as records. Why is this?
Thank you!
(Deleting old answer, as the issue was a typo)
scandir returns a list of files in a given directory. When you use is_dir, it's looking in the current directory for those files. I think what you need to do is:
if(!is_dir("./images/all_comics/" . $images[$x])) {
....
Your echo is executed inside if, but query does not:
for($x=0; $x<count($images); $x++)
{
if(!is_dir($images[$x]))
{
echo $images[$x]; //This shows all images WITHOUT directories
mysql_query("INSERT INTO images (imgpath, thumbpath) VALUES ('$images[$x]', '$thumbs[$x]')");
}
}
Also, get rid of mysql_* for PDO, and consider glob as a way to browse for files excluding directories.
You can also use glob
$files = glob('./images/all_comics/*');
foreach ($files as $file) {
if (!is_dir($file)) {
//Do Insert
}
}

Categories