proper usage of glob() - php

Is this the correct way to us glob() i'm trying to do a case insensitive search for the folder TestFolder on the server.
$chid = "testFoLdER";
$dirchk2 = "/temp/files/" . glob('".$chid."') . "/" . $data[1] . ".doc";
#code_burgar I made these changes to apply to the example code_burgar showed me. is this correct?
what i'm trying to do here is what ever globistr find for casing, rename the folder to lowercase.
$chid = (strtolower($_POST['chid']));
$findbatch = globistr($chid);
$results = glob($findbatch);
if ( !empty($results) ) {
$result = $results[0];
rename("/temp/files/" . $results . "/", "/temp/files/" . strtolower($chid) . "/");
}
else
{
$missing_dir = 'Folder containing files, Not Found: ' . $chid . "\r";
$errfile = fopen("/rec/" . $chid . "-errlog.txt", "a");
fwrite($errfile, $missing_dir . "\n");
fclose($errfile);
exit();
}

That is most definitely not the way to use glob(). glob() returns an array and you are trying to use it in string concatenation.
As Pekka pointed out, PHP man page for glob has some case-insensitive example code.
What you are looking for basically is something along these lines (globistr() comes from PHP man page comments):
$chid = globistr("testFoLdER");
$results = glob($chid);
if ( !empty($results) ) {
$result = $results[0];
$dirchk2 = "/temp/files/" . $result . "/" . $data[1] . ".doc";
} else {
echo('Not found');
}

As workaround you can search all folder inside /temp/files/ that contain $data[1]. '.doc' file and then loop through results to make case-insensitive check if path contains your folder.
$file = "/temp/files/*/".$data[1].".doc";
$locations = glob($file);
$found = false;
foreach($locations as $l){
if(stripos($l,'/testfolder/') !== false){
$found = $l;
break;
}
}

Related

Removing some strings in a word in PHP within an array

I am have retrieved all the file contents from a directory. It prints the file contents name from an array. However I want only a portion of the file content name. Any idea how can I achieve this? I have tried using the following:
The file contents from the directory has format: pdb101m.ent.gz , pdb102l.ent.gz
I want to retrieve only the 101m and 102l
<?php
$dir = "C:/Users/Desktop/EAD/PDB/";
$files = array();
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
foreach($files as $ex){
echo str_replace('pdb.ent.gz', ' ', $ex). '<br>';
}
?>
Please help. Grateful.
Use substr() function:
echo substr('pdb101m.ent.gz',3,4); // Outputs: 101m
echo substr('pdb102l.ent.gz',3,4); // Outputs: 102l
So:
foreach($files as $ex){
echo substr($ex, 3,4). '<br>';
}
Edit: Update my answer attending the OP new request:
So in your query you should use:
foreach ($files as $ex) {
$search = substr($ex, 3, 4);
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 6';
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$pdb[] = $row['pdb_code'];
}
}
If it's always pdb at the beggining and .ent.gz at the end you can do simply:
echo substr('pdb101m.ent.gz',3,-7);
Negative value of third parameter in substr() means
that many characters will be omitted from the end of string

Conditional regex php

I'm facing some problem with php regex but after many researches (conditional regex, subpattern regex), I still can't solve it.
I have a folder that contains many images and based on variable value I have to go to that folder and select all images that match the value.
e.g: In my folder I have 3 images:
p102.jpg ; p1020.jpg ; p102_1.jpg;
I only want the regex to select :
p102.jpg ; p102_1.jpg
but with the regex below It selects all 3 images.
$image_to_find = 102;
$path = "[^\d]*.*/"
$test = "/^[a-zA-Z]?$image_to_find".$path;
foreach(glob($file_directory) as $file){
if(preg_match($test, $file)){
match[]= $file;
}
}
I also try:
$path = "(?:\_[0-9]?).*/"; (it selects only p102_1.jpg)
Can you help me to figure it out. thanks
(sorry for the english)
You can avoid the foreach loop if you use the glob pattern:
$num = 102;
$result = glob($path . '[a-zA-Z]' . $num . '[._]*');
Note: if you need to allow several different formats, you can use array_merge and several glob patterns: array_merge(glob(...), glob(...));
If you want the first letter optional:
$result = array_merge(
glob($path . $num . '[._]*jpg'),
glob($path . '[a-zA-Z]' . $num . '[._]*jpg')
);
or better, use the brace option:
$result = glob($path . '{[a-zA-Z],}' . $num . '[._]*jpg', GLOB_BRACE);
That stays a better alternative than the combo "foreach/preg_match" (or preg_grep) if filenames are not too complicated.
With preg_grep:
$pattern = '~(?:^|/)[a-z]?' . $num . '(?:_\d+)?\.jpg$~i';
$result = preg_grep($pattern, glob($path . '*' . $num . '*.jpg'));
Try this:
/p102[_\.]\d*\.?jpg/g
https://regex101.com/r/hM4oE0/1
Where p102 should be your 'image_to_find' var.
Not tested, should work.
$find = 102;
$pattern = "/p". $find ."(?:_\d+)?\.jpg/";
$list = array();
foreach (glob($file_directory) as $file)
{
if (preg_match($pattern, $file))
{
$list[] = $file;
}
}
regex: http://regexr.com/3bp29
Tested and working:
<?php
$image_to_find = 102;
$pattern = '[a-zA-Z]' . $image_to_find . '[._]*';
$path = '/your_folder/your_subfolder/';
$file_directory = glob($path . $pattern );
echo '<pre>';
var_dump($file_directory);
echo '</pre>';
exit();
I hope this helps!

Php simple algorithm for autoloader

Here's my "simple" algorithm:
if the class is named like 'AaaBbbCccDddEeeFff' loop like this:
include/aaa/bbb/ccc/ddd/eee/fff.php
include/aaa/bbb/ccc/ddd/eee_fff.php
include/aaa/bbb/ccc/ddd_eee_fff.php
include/aaa/bbb/ccc_ddd_eee_fff.php
include/aaa/bbb_ccc_ddd_eee_fff.php
include/aaa_bbb_ccc_ddd_eee_fff.php
if still nothing found, try to look if those files exist:
include/aaa/bbb/ccc/ddd/eee/fff/base.php
include/aaa/bbb/ccc/ddd/eee/base.php
include/aaa/bbb/ccc/ddd/base.php
include/aaa/bbb/ccc/base.php
include/aaa/bbb/base.php
include/aaa/base.php
include/base.php
If still not found then error.
I'm looking for a fast and easy way to convert this:
'AaaBbbCccDddEeeFff'
to this:
include/aaa/bbb/ccc/ddd/eee/fff.php
and then and easy way to remove latest folder (I guess I should look for explode()).
Any idea how to do this? (I'm not asking for the whole code, I'm not lazy).
Since you specifically asked not to have the whole code, here is some code to get you started. This takes the input and divides it into chunks delineated by changes in case. The rest you can work out as an exercise.
<?php
$input = "AaaBbbCccDddEeeFff";
$str_so_far = "";
$last_was_upper = 0;
$chunks = array();
while($next_letter = substr($input,0,1)) {
$is_upper = (strtoupper($next_letter)==$next_letter);
if($str_so_far && $is_upper && !$last_was_upper) {
$chunks[] = $str_so_far;
$str_so_far = "";
}
if($str_so_far && !$is_upper && $last_was_upper) {
$chunks[] = $str_so_far;
$str_so_far = "";
}
$str_so_far .= $next_letter;
$input = substr($input,1);
$last_was_upper = $is_upper;
}
var_dump($chunks);
?>
I think a regular expression would work. Something like preg_match_all('[A-Z][a-z][a-z]'
, $string); might work - that would match a capital letter, followed by a lowercase letter, and another lowercase letter.
As the other answers are regex, here's a non-regex way for completeness:
function transform($str){
$arr = array();
$part = '';
for($i=0; $i<strlen($str); $i++){
$char = substr($str, $i, 1);
if(ctype_upper($char) && $i > 0){
$arr[] = $part;
$part = '';
}
$part .= $char;
}
$arr[] = $part;
return 'include/' . strtolower(implode('/', $arr)) . '.php';
}
echo transform('AaaBbbCccDddEeeFff');
// include/aaa/bbb/ccc/ddd/eee/fff.php
This builds an array of the folders, so you can manipulate it as needed, for example remove a folder by unsetting the desired index, before it gets imploded.
Here is the first part of your algorithm:
AaaBbbCccDddEeeFff -> include/aaa/bbb/ccc/ddd/eee/fff.php
include/aaa/bbb/ccc/ddd/eee_fff.php
include/aaa/bbb/ccc/ddd_eee_fff.php
include/aaa/bbb/ccc_ddd_eee_fff.php
include/aaa/bbb_ccc_ddd_eee_fff.php
include/aaa_bbb_ccc_ddd_eee_fff.php
I think you can do last part independently based on my answer.
<?php
function convertClassToPath($class) {
return strtolower(preg_replace('/([a-z])([A-Z])/', '$1' . DIRECTORY_SEPARATOR . '$2', $class)) . '.php';
}
function autoload($path) {
$base_dir = 'include' . DIRECTORY_SEPARATOR;
$real_path = $base_dir . $path;
var_dump('Checking: ' . $real_path);
if (file_exists($real_path) === true) {
var_dump('Status: Success');
include $real_path;
} else {
var_dump('Status: Fail');
$last_separator_pos = strrpos($path, DIRECTORY_SEPARATOR);
if ($last_separator_pos === false) {
return;
} else {
$path = substr_replace($path, '_', $last_separator_pos, 1);
autoload($path);
}
}
}
$class = 'AaaBbbCccDddEeeFff';
var_dump(autoload(convertClassToPath($class)));

Multiple File Exists Checking? A Better way?

I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.
Right now I am doing this script as follows:
if (file_exists($img = $node.".png")) { }
else if (file_exists($img = $node.".jpg")) { }
else if (file_exists($img = $node.".gif")) { }
else
{
$img = 'RANDOM.png';
}
There has to be a better way than this... anyone have any ideas?
$list = array_filter(array("$node.png", "$node.jpg", "$node.gif"), 'file_exists');
if (!$img = array_shift($list)) {
$img = 'RANDOM.png';
}
Alternatives :
$list = scandir(".");
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#", $list);
This returns a list of file names that start with $node and with a .jpg, .png or .gif suffix.
If the directory contains many entries, if may be faster to use glob() first:
$list = glob("$node.*"); // take care to escape $node here
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#");
The preg_grep() can also be replaced by
$list = array_intersect($list, array("$node.png", "$node.jpg", "$node.gif"));
Or with a loop:
$img = null;
foreach(array('png','jpg','gif') as $ext) {
if (!file_exists("$node.$ext")) continue;
$img = "$node.$ext"; break;
}
$img = $img ? $img : "RANDOM.png";
The most compact (and therefore not recommended) form would be:
if (array_sum(array_map("file_exists", array($fn1, $fn2, $fn3)))) {
It could be adapted to also returning the found filename using array_search:
array_search(1, array_map("file_exists", array($fn1=>$fn1, $fn2=>$fn2)))
Hardly readable. Note how it also requires a map like array("$node.png"=>"$node.png", "$node.gif"=>"$node.gif", ...). So it would not be that much shorter.
$n_folder="images/nodes/";
$u_folder="images/users/";
$extensions=array(".png",".jpg",".gif");
foreach ($extensions as $ext)
{
if (file_exists($n_folder.$node.$ext))
{
$img=$n_folder.$node.$ext;
break;
}
elseif (file_exists($u_folder.$node.$ext))
{
$img=$u_folder.$node.$ext;
break;
}
}
if (!$img)
{
random image generator script...
}
Okay... this is what I finalized on:
$searches = array(
$folder . "nodes/" . $node . ".png",
$folder . "nodes/" . $node . ".jpg",
$folder . "nodes/" . $node . ".gif",
$folder . "users/" . $user . ".png",
$folder . "users/" . $user . ".jpg",
$folder . "users/" . $user . ".gif"
);
foreach ($searches AS $search)
{
if (file_exists($search))
{
$img = $search;
break;
}
}
if (!$img)
{
random image generator script...
}

Growing a list of links from a query

I have the following code, which will retrieve a filename from a table and make a link to it. What I want to do, is have it so I can refer to $filesList later on, and it will contain a single block of html code with links to as many files as there are files.
I thought adding to the previous variable would be the easiest way to do this, but it actually outputs nonsense code: 0test.sh">test.sh
if ($getFiles = $con->prepare($filesQuery)) {
$getFiles->bind_param("s", $pk);
$getFiles->execute();
$getFiles->bind_result($FILENAME);
$files = array();
while ($getFiles->fetch()) {
$filename = array(
'FILENAME' => $FILENAME,
);
$files[] = $filename;
}
}
$filesList = '';
foreach ($files as $filenames)
{
$filesList = $filesList + '<p>'. $filenames['FILENAME'] .'' . "\n";
};
Sureley I do not need to have an array for what i want to do?
You need to change that code to:
$filesList = '';
foreach ($files as $filenames)
{
$filesList .= '<p>'. $filenames['FILENAME'] ."</p>\n";
};
Does that help? You cannot concatenate with +.
One thing that I immediately spot is that you have $filesList = $filesList + ... Use a dot and not a + -sign.
Try this
$filesList = $filesList . "<p>{$filenames['FILENAME']}";
Have you tried something like this?
(Untested code, as I am not at home)
if ($getFiles = $con->prepare($filesQuery)) {
$getFiles->bind_param("s", $pk);
$getFiles->execute();
$getFiles->bind_result($FILENAME);
$files = array();
while ($getFiles->fetch()) {
$filesList = $filesList + '<p>'. $FILENAME .'' . "\n";
}

Categories