I want to compare $images, $uploads but the outputs have different names:
$images = '/fiscalapplications/uploads/Image_00314_20200122.pdf';
$uploads = 'Image_00314_20200122.pdf';
How do I do SUBSTR for the $images to = Image_00314_20200122.pdf
<?php
//pulling images from mysql colum1
require_once 'database_connection.php';
$result = mysqli_query($conn,"SELECT check_pic_path FROM checklog");
$images = []; // store a list of images from the database
while ($row = mysqli_fetch_array($result)) {
$images[] = $row['check_pic_path'] . "<br>";
}
//pulling pictures from specific path
$dir = "fiscalapplications/uploads";
$uploads = []; // store a list of files on disk
if(is_dir($dir)) {
while (($file = readdir($dh)) !== false) {
$uploads[] = $file . "<br>";
}
}
}
//attempting to compare $image to $upload
$compare = array_diff($images, $uploads);
print_r($compare);
Use basename() to remove the directory from a pathname:
$images[] = basename($row['check_pic_path']) . "<br>";
In MySQL it may be
SUBSTRINT_INDEX(tablename.imagefield, '/', -1)
$uploadsnew = substr($images , strrpos($images , '/') + 1);
strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.
if there is no slash this doesn't work correctly since strrpos returns false. Here's a more robust version:
$pos = strrpos($url, '/');
$uploadsnew = $pos === false ? $url : substr($images , $pos + 1);
In PHP:
$images = $images ?: '';
$uploads = substr($images, ($pos = strrpos($images, '/')) ? $pos : 0);
In MySQL:
if( ifnull( locate( '/', check_pic_path ), 0 ) > 0, substring_index( check_pic_path, '/', -1 ), check_pic_path )
Related
I have a php search code that returns the results in the page. What I wanna do is limit the number of results per page to 10, and echo a link for more results.
My code is:
$dir = 'www/posts';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
if (!empty($q)) {
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/'.$file;
if (file_exists($fpath)) {
echo "<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date ("d F Y ", filemtime($fpath)) ;
echo "<br>";
}
}
}
closedir($res);
}
else {
echo "";
}
I tried the $q->limit(10); but it doesnt work. Please help me write a working code.
<?php
$dir = 'www/posts';
$exclude = array(
'.',
'..',
'.htaccess'
);
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$results=[];
if (! empty($q)) {
$res = opendir($dir);
while (false !== ($file = readdir($res))) {
if (strpos(strtolower($file), $q) !== false && ! in_array($file, $exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/' . $file;
if (file_exists($fpath)) {
$results[]="<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date("d F Y ", filemtime($fpath));
}
}
}
closedir($res);
}
foreach ($results as $result) {
echo $result;
echo "<br>";
}
if (count($results) > 10 ) {
echo 'results is more than 10, but only 10 results is shown';
}
Here is a completely untested suggestion... I am happy to have a bit of back and forth to iron it out.
if(!empty($_GET['q'])){
// perform some logical validation/sanitization on `$_GET['q']` for stability/security
$path = '../posts'; // this relative path may need some adjusting
$files=glob("$path/*.txt"); // collect all .txt files from the directory
var_export($files);
$filtered=preg_grep('~.*'.preg_quote($q,'/').'.*\.txt$~i',$files); // case-insensitive filename search
var_export($filtered);
if(!empty($filtered)){
$batches=array_chunk($filtered,10); // store in groups of 10
var_export($batches); // check the data
if(!isset($_GET['page'],$batches[--$page])){ // a page has been submitted and that page exists in the batches array (subtract one to sync the page with the index)
$page=0;
}
$leftovers=array_keys(array_diff_key($batches,[$page=>'']));
foreach($batches[$page] as $filename){
$withoutExt=substr($filename,0,strrpos($filename,"."));
$fpath="posts/$filename";
echo "<div><a href='/search.php?post=$withoutExt'>$withoutExt</a> on ",date("d F Y",filemtime($fpath)),"</div>";
}
// here you can list the other pages available from this search
if($leftovers){
echo "Additional pages:";
foreach($leftovers as $offset){
echo " <a href='/search.php?q={$_GET['q']}&page=",++$offset,"'>$offset</a>";
}
}
}
}else {
echo "No Search Terms found";
}
I have a directory containing folders like
baseurl/2-435435435_323423/
baseurl/5_435435435_32423/
baseurl/3_543543543_2342342/
Now i want to rename all the folders from their original name to new name i.e. truncate last part separated by '_'. new names would be
baseurl/2-435435435/
baseurl/5_435435435/
baseurl/3_543543543/
$path_from = 'E:/documents/';
if(file_exists($path_from)){
$files = scandir($path_from);
foreach($files as $key1 => $file) {
$newName = ? // I need this
rename($path_from.$file,$path_from.$newName);
}
}
Or Let me know if there is anyway in windows to rename batch without any script.
As you mention for getting only $newName, Just use substr and strrpos.
strrpos - Find the numeric position of the last occurrence of a string
$str = 'baseurl/3_543543543_2342342/';
$pos = strrpos($str, "_");
if ($pos === false){
//do nothing
}else
$str = substr($str, 0, $pos)."/";
echo $newName = $str; //baseurl/3_543543543/
You can make use of strstr
$path_from = 'E:/documents/';
if(file_exists($path_from)){
$files = scandir($path_from);
foreach($files as $key1 => $file) {
$newName = strstr($file, '_', true);
rename($path_from.$file,$path_from.$newName);
}
}
e.g.
$str = 'baseurl/2-435435435_323423/';
$imagePreFix = strstr($str, '_', true);
echo $imagePreFix;
OUTPUT:
baseurl/2-435435435
$newName = substr($file, 0, strrpos($file, '_'));
I have on my linux machine such folder tree structure:
/dir/yyyy/mm/dd/HH
e.g.:
/dir/2014/03/01/08
/dir/2014/03/20/09
/dir/2014/03/01/10
/dir/2014/08/01/10
/dir/2014/12/15/10
/dir/2015/01/01/14
I'd like to get in php what path is the oldest, like this:
The oldest path is: 2014-03-01 08
The newest path is: 2015-01-01 14
How it can be done?
It could be written better but it works
$paths = array(
'/dir/2014/03/01/08',
'/dir/2014/03/20/09',
'/dir/2014/03/01/10',
'/dir/2014/08/01/10',
'/dir/2014/12/15/10',
'/dir/2015/01/01/14',
);
$dates = array();
foreach($paths as $path)
{
$matches = array();
preg_match('#([^\/]+?)\/([^\/]+?)\/([^\/]+?)\/([^\/]+?)\/([^\/]+)#', $path, $matches);
$dates[$path] = strtotime(sprintf("%s-%s-%s %s:00:00", $matches[2], $matches[3], $matches[4], $matches[5]));
}
asort($dates);
$dates = array_keys($dates);
$oldest = array_shift($dates);
$newest = array_pop($dates);
It changes date find by regex to unixtimestamp then sorts it and returns top and bottom value of sorted array.
Little bit like Pascal style)
<?php
$oldest = '';
$newest = '';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('./dir/'));
foreach ($iterator as $file => $object) {
if ($iterator->getDepth() === 4) {
$name = $object->getPath();
if ($name > $newest) {
$newest = $name;
}
if (empty($oldest) or $name < $oldest) {
$oldest = $name;
}
}
}
var_export([$oldest, $newest]);
Result:
array (
0 => './dir/2014/03/01/08',
1 => './dir/2015/01/01/14',
)
All you have to do is loop through each folder and find the directory that has the lowest number. If you have the file paths stored in a database, it can be easier, but from your question it seems like you want to search the folders.
<?php
$base = 'dir';
$yearLowest = lowestDir($base);
$monthLowest = lowestDir($yearLowest);
$dayLowest = lowestDir($monthLowest);
echo $dayLowest;
function lowestDir($dir) {
$lowest = null;
$handle = opendir($dir);
while(($name = readdir($handle))) {
if($name == '.' || $name == '..') {
continue;
}
if(is_dir($dir.'/'.$name) && ($lowest == null || $name < $lowest)) {
$lowest = $name;
}
}
closedir($handle);
return $dir.'/'.$lowest;
}
?>
i have an ads site where images are located and named as the follow:
images/139/16_2_139.jpg
where: -
images/139/ is the users folder
16 is the id of ad
2 is the number of images available for this ad
139 is the user id
examples
images/1390/3800_12_1390.jpg
images/27/728_7_27.jpg
images/8563/13281_2_8563.jpg
Now I need to display every images concerning this ad in a slideshow (colorbox)
i extract the ad id and the user id from sql
i need that php read in the directory every images concerning the ad id and the user id and display it in colorbox slideshow (jQuery addon)
the ad id goes from 1 to 15000 and the user id goes from 1 to 9000 and can also be more
i dont know if better regex or preg_match can solve my problem
thanks for your help
try this
$str='images/1390/3800_12_1390.jpg
images/27/728_7_27.jpg
images/8563/13281_2_8563.jpg';
preg_match_all('#images/([0-9]+)/([0-9]+)_([0-9]+)_([0-9]+)#is',$str,$res);
$r=array();unset($res[0]);
foreach($res as $k=>$v){
foreach($v as $k2=>$v2){
$r[$k2][$k]=$v2;
}
}
print_r($r);
i found myself a solution who work
i share for reference:
function microtime_float()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
ini_set ("display_errors", "1");
error_reporting(E_ALL);
$start = microtime_float();
$b = '<br />'; $ad = 16; $cust = 139;
$directory = $_SERVER['DOCUMENT_ROOT'].'/ginew/advertiser/images/'. $cust .'/';
// echo $directory;
if( is_dir( $directory ) ) {
$handler = opendir( $directory );
$images = glob("$directory{*.jpg,*.JPG,*jpeg, *JPEG}", GLOB_BRACE);
$cnt = count($images);
echo 'total images in directory: '. $cnt.$b;
$i=0; $img1 = '';
while ($filename = readdir($handler)) {
if($filename != '.' && $filename != '..') {
$base = basename($filename, ".jpg"); // echo $base.$b;
$ext = substr(strrchr($filename, '.'), 0); // echo $ext.$b;
$imgsize = #filesize($directory.$filename); $imgsize = ($imgsize/1000000) .' mb';
if ( preg_match( '#'.$ad.'_([0-9]+)_'.$cust.'#', $base, $matches ) ) {
$i++;
$img = $i .' matches '. $matches[0] . $ext;
$img1.= $i .' matches '. $matches[1] .'<br>';
echo $img.$b;
} // END is_dir
echo $i .' --> '. $filename . $ext .' => '. $imgsize .'<br />';
} // END preg_match
} // END if filename
$end = microtime_float();
} // END while
echo '/ -------------------------- /<br>';
echo $img1.$b;
echo 'matches images found: '. $i . $b;
echo 'preg_match brauch : '.($end-$start).' Sekonnen';
output:
total images in directory: 6
1 matches 16_2_139.jpg
2 matches 16_7_139.jpg
3 matches 16_1_139.jpg
/ -------------------------- /
1 matches 2
2 matches 7
3 matches 1
matches images found: 3
preg_match brauch : 0.00037693977355957 Sekonnen
if anybody has a better solution for this please post it
thanks to everyone
;-)
I have a folder that contains files named standard_xx.jpg (xx being a number)
I would like to find the highest number so that I can get the filename ready to rename the next file being uploaded.
Eg. if the highest number is standard_12.jpg
$newfilename = standard_13.jpg
I have created a method to do it by just exploding the file name but it isn't very elegant
$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
$maxfile = $files[count($files)-1];
$explode = explode('_',$maxfile);
$filename = $explode[1];
$explode2 = explode('.',$filename);
$number = $explode2[0];
$newnumber = $number + 1;
$standard = 'test-xrays-del/standard_'.$newnumber.'.JPG';
echo $newfile;
Is there a more efficient or elegant way of doing this?
I'd do it like this myself:
<?php
$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
natsort($files);
preg_match('!standard_(\d+)!', end($files), $matches);
$newfile = 'standard_' . ($matches[1] + 1) . '.JPG';
echo $newfile;
You can make use of sscanfDocs:
$success = sscanf($maxfile, 'standard_%d.JPG', $number);
It will allow you to not only pick out the number (and only the number) but also whether or not this worked ($success).
Additionally you could also take a look into natsortDocs to actually sort the array you get back for the highest natural number.
A complete code-example making use of these:
$mask = 'standard_%s.JPG';
$prefix = 'test-xrays-del';
$glob = sprintf("%s%s/%s", $uploaddir, $prefix, sprintf($mask, '*'));
$files = glob($glob);
if (!$files) {
throw new RuntimeException('No files found or error with ' . $glob);
}
natsort($files);
$maxfile = end($files);
$success = sscanf($maxfile, sprintf($mask, '%d'), $number);
if (!$success) {
throw new RuntimeException('Unable to obtain number from: ', $maxfile);
}
$newnumber = $number + 1;
$newfile = sprintf("%s/%s", $prefix, sprintf($mask, $newnumber));
Try with:
$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
natsort($files);
$highest = array_pop($files);
Then get it's number with regex and increase value.
Something like this:
function getMaxFileID($path) {
$files = new DirectoryIterator($path);
$filtered = new RegexIterator($files, '/^.+\.jpg$/i');
$maxFileID = 0;
foreach ($filtered as $fileInfo) {
$thisFileID = (int)preg_replace('/.*?_/',$fileInfo->getFilename());
if($thisFileID > $maxFileID) { $maxFileID = $thisFileID;}
}
return $maxFileID;
}