get file name include_once file based on name - php

I have multiple files in a directory for pages.
All the pages are the same except the content I enter based on
rental inspections.
bedroom1.php
bedroom2.php
bedroom3.php
But to get them to use the right header I need them to see the
correct header based on their own filename.
bedroom1.php to include header1.php
bedroom2.php to include header2.php
bedroom3.php to include header3.php
.......
bedroom10.php to include header10.php
I can get the filename easy enough.
I'm trying to use preg_match(Maybe should use something else?)
but with not getting any errors in the logs so I'm not sure
what I'm missing and not knowing enough about file comparing
I'm lost.
EDIT: ADDED : Forgot to add, this code is in bedroom1.php etc...
Thanks in advance
<?php
$file = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
if (preg_match('/bedroom . $i .php/', $pfile, $i)) {
$number = $i[1];
foreach(array('header') as $base) {
include_once "$base$number.php";
}
}
?>

It should be:
if (preg_match('/bedroom(\d+)\.php/', $pfile, $i)) {
You need to use \d+ to match numeric digits, and put it inside parentheses to make it a capture group, so you can access it with $i[1].

Try this one:
$file = basename($_SERVER['SCRIPT_NAME'], '.php');
$base = 'header';
$parts = array();
if (preg_match('/bedroom(\d+)/', $file, $parts)) {
include_once $base . $parts[1] . '.php';
} else {
// the file doesn't follow the bedroom{number}.php structure
}
Good luck!

use this
basename($_SERVER['SCRIPT_NAME'])
you get the script name

$file = $_SERVER["SCRIPT_NAME"];
$baseName=basename($file);
$base="header";
preg_match_all('/\d+/', $baseName, $baseNameInt);
$basNameFile=$baseNameInt[0][0];
if(file_exists("$base$basNameFile.php")){
include_once("$base$basNameFile.php");
} else {
// ...
}

Not sure what your array contains that necessitates the foreach (if that is just example code) but why not just:
$array = array('header');
$suffix = str_replace($array, '', basename(__FILE__));
foreach($array as $base) {
if(file_exist("$base$suffix")) {
include_once("$base$suffix");
}
}
If the only thing that will be in the array is header then forgo the loop altogether.

Related

Subst a string reverse to the last slash

Hello. I have a string with a path. I do not need the whole path. Is it possible to substr to a last slash ? Based on the code below, I dont need the modelname.
Thanks for any hints you can give.
$path = userdir/modeldir/modelname
Try exploding the array by using the slash as a delimiter?
$pathArray = explode('/', $path);
That should give you the entire folder tree as an array.
For further information visit: http://www.php.net/explode
Bit confused,
do you want modelname? ok then use basename() See it in action
echo basename('userdir/modeldir/modelname'); //modelname
Or do you want userdir/modeldir? ok then use dirname() See it in action
echo dirname('userdir/modeldir/modelname/'); //userdir/modeldir
$path = 'userdir/modeldir/modelname';
$arr = explode('/', $path);
echo $arr[count($arr) - 1]; // Will output modelname
you can use this
$address = 'userdir/modeldir/modelname';
$a=explode("/",$address);
echo $a[2];
<?php
$path = 'userdir/modeldir/modelname';
$pathArray = explode('/', $path);
array_pop($pathArray);
$path = implode('/', $pathArray);
?>
Or, if you want it in a nice function:
<?php
function removeLast($path, $delim = '/') {
$pathArray = explode($delim, $path);
if (count($pathArray) == 1) return $pathArray[0];
array_pop($pathArray);
return implode($delim, $pathArray);
}
echo removeLast('userdir/modeldir/modelname');
?>

PHP problem with include

<?
$dir=scandir('/home/crusty/www/crusty.bshellz.pl/htdocs/404/');
foreach($dir as $file){
if($file!='.' && $file!='..' && $file!='index.php'){
$choice=$dir[rand(0, count($dir) - 1)];
include($choice);
}
}
?>
I have a little problem with that code. Of course it is working on some files but it is still trying to include index.php, .. and .
Can sameone help me with solving it?
Split Your code into two parts: first one to prepare array of good files; second to include random file:
$allfiles = scandir('/home/crusty/www/crusty.bshellz.pl/htdocs/404/');
$goodfiles = array();
foreach ($allfiles as $file) {
if($file!='.' && $file!='..' && $file!='index.php'){
$goodfiles[] = $file;
}
}
$choicenfile = $goodfiles[rand(0, count($goodfiles) - 1)];
// As I understant You want to include only one file, not all;
include($choicenfile);
Now You can even extract this code to methods or functions
You have to supply the full path, your trying to include the file from the location of the script.
Change this:
include($choice);
to:
include('/home/crusty/www/crusty.bshellz.pl/htdocs/404/'.$choice);
I wouldn't do it this way, but it should work.
I'm not shure if you want to include all files in randomized order or just one random file of the given folder, so I have included both in the solution - just delete what you don't need:
function filter_includes($incfile) {
return !in_array($incfile, array(".", "..", "index.php"));
}
$dirPath = '/home/crusty/www/crusty.bshellz.pl/htdocs/404/';
$dir = array_filter(scandir($dirPath), "filter_includes");
// include all files in randomized order
shuffle($dir);
foreach($dir as $file) {
include($dirPath . $file);
}
// include one random file
include($dirPath . $dir[rand(0, count($dir) - 1)]);
What is the point of the rand in $choice=$dir[rand(0, count($dir) - 1)];?
Because right now it's just including a random file in your array.
You should change your code to something like:
$dir=scandir('/home/crusty/www/crusty.bshellz.pl/htdocs/404/');
foreach($dir as $file){
if($file!='.' && $file!='..' && $file!='index.php'){
include($file);
}
}

How Do I Use PHP To Show A Unique Header IMG Based On Path On A Drupal Site?

I have a Drupal site that needs to display a unique header image based on the path. I have found some helpful code. It gets me close to where I need to be, but not all the way. I have pasted it at the end of this post.
The issue I am having is that it bases the banner image off of the characters after the first "/" after example.com in the URL. For example, example.com/forum returns a banner of header-FORUM.png.
I need it to work a little differently. I would like it to base the banner returned off the characters after the second "/" after example.com in the URL. For example, example.com/category/term should return a banner of header-TERM.png.
Any help that you can offer with this is much appreciated.
Here's the code I mentioned earlier via AdaptiveThemes (FYI, there is a comment on that page that attempts to solve a similar issue to mine but I can't get it to work).
<?php
// Return a file based on the URL alias, else return a default file
function unique_section_header() {
$path = drupal_get_path_alias($_GET['q']);
list($sections, ) = explode('/', $path, 2);
$section = safe_string($sections);
$filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
if (file_exists($filepath)) {
$output = $filepath;
}
else {
$output = path_to_theme() . '/images/sections/header-default.png';
}
return $output;
}
//Make a string safe
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
return $string;
}
?>
Thanks!
Not exactly sure what the output of drupal_get_path_alias is, but try this:
<?php
// Return a file based on the URL alias, else return a default file
function unique_section_header() {
$path = drupal_get_path_alias($_GET['q']);
$pathSegments = explode('/', $path, 3);
$section = safe_string($pathSegments[2]);
$filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
if (file_exists($filepath)) {
$output = $filepath;
}
else {
$output = path_to_theme() . '/images/sections/header-default.png';
}
return $filepath;//$output;
}
//Make a string safe
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
return $string;
}
The only changes made were to the usage of explode. explode will separate the path based on the /, so you just need to access a different element in that array. The last parameter of explode is the maximum number of elements to be returned and may also need to be tweaked
I'm adding an answer so I can include code. This is based on Gilean's response.
/** Return a file based on the URL alias, else return a default file
*/
function unique_section_header() {
$path = drupal_get_path_alias($_GET['q']);
$pathSegments = explode('/', $path, 3);
$section = safe_string($pathSegments[1]);
$filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
if (file_exists($filepath)) {
$output = $filepath;
}
else {
$output = path_to_theme() . '/images/sections/header-default.jpg';
}
return $output;
}
/** Make a string safe
*/
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
return $string;
}
This is what I would do:
In your theme's template.php, create the function THEMENAME_preprocess_page (replace THEMENAME with the name of your theme) as follows. If it already exists, add the following code to that function. (disclamer: untested code)
function THEMENAME_preprocess_page(&$variables) {
$path = drupal_get_path_alias($_GET['q']);
$path_segments = explode('/', $path, 3);
if ($path_segments[0] == 'category' && !empty($path_segments[1])) {
$safe_term = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $path_segments[1]));
$filepath = path_to_theme() . '/images/sections/header-' . $safe_term .'.png';
if (!file_exists($filepath)) {
$filepath = path_to_theme() . '/images/sections/header-default.png';
}
$variables['header_image'] = theme('image', $filepath);
}
}
Using a preprocess function (like the one above) is the Drupal way to make extra variables available for a template file. You only have to add a new element to the $variables array. Once you have done the above, you can simply put the following line in your page.tpl.php:
<?php print $header_image; ?>
This will print the complete <img> element.
PS. Usually, I advice not to base code like this on path aliases. It's a method that breaks easily because path aliases can change.

Getting Textmate to create PHP autoload class name from filepath

What I would like is a snippet that when executed, grabs the TM_FILEPATH output
Explodes it on the slash /
Then split out each part as a placeholder containing that part and an underscore (apart from the last part (the filename))
For Example:
for a file in directory path
/Path/To/Original/file
we would get
class ${1:Path_}${2:To_}${3:Original_}${4:File} {
// code here
}
Then I can step through and remove the parts I don't want
ending with a className that fits the standard PHP autoloader
Does this sound possible?
Cheers,
Chris
Have to add this final result as an answer to enable code display.
Just make sure you set 'output as snippet'
#!/usr/bin/php
<?php
$path = $_ENV['TM_FILEPATH'];
$path = trim($path, '/');
$path = trim($path, '.php');
$parts = explode('/', $path);
$lastPart = end($parts);
echo 'class ';
foreach ($parts as $id => $part) {
// textmate placeholders start at 1
$id = $id+1;
if ($lastPart == $part) {
echo '${'.$id.':'.$part.'}';
} else {
echo '${'.$id.':'.$part.'_}';
}
}
?>

Extract direct sub directory from path string

I need to extract the name of the direct sub directory from a full path string.
For example, say we have:
$str = "dir1/dir2/dir3/dir4/filename.ext";
$dir = "dir1/dir2";
Then the name of the sub-directory in the $str path relative to $dir would be "dir3". Note that $dir never has '/' at the ends.
So the function should be:
$subdir = getsubdir($str,$dir);
echo $subdir; // Outputs "dir3"
If $dir="dir1" then the output would be "dir2". If $dir="dir1/dir2/dir3/dir4" then the output would be "" (empty). If $dir="" then the output would be "dir1". Etc..
Currently this is what I have, and it works (as far as I've tested it). I'm just wondering if there's a simpler way since I find I'm using a lot of string functions. Maybe there's some magic regexp to do this in one line? (I'm not too good with regexp unfortunately).
function getsubdir($str,$dir) {
// Remove the filename
$str = dirname($str);
// Remove the $dir
if(!empty($dir)){
$str = str_replace($dir,"",$str);
}
// Remove the leading '/' if there is one
$si = stripos($str,"/");
if($si == 0){
$str = substr($str,1);
}
// Remove everything after the subdir (if there is anything)
$lastpart = strchr($str,"/");
$str = str_replace($lastpart,"",$str);
return $str;
}
As you can see, it's a little hacky in order to handle some odd cases (no '/' in input, empty input, etc). I hope all that made sense. Any help/suggestions are welcome.
Update (altered solution):
Well Alix Axel had it spot on. Here's his solution with slight tweaks so that it matches my exact requirements (eg: it must return a string, only directories should be outputted (not files))
function getsubdir($str,$dir) {
$str = dirname($str);
$temp = array_slice(array_diff(explode('/', $str), explode('/', $dir)), 0, 1);
return $temp[0];
}
Here you go:
function getSubDir($dir, $sub)
{
return array_slice(array_diff(explode('/', $dir), explode('/', $sub)), 0, 1);
}
EDIT - Foolproof implementation:
function getSubDirFoolproof($dir, $sub)
{
/*
This is the ONLY WAY we have to make SURE that the
last segment of $dir is a file and not a directory.
*/
if (is_file($dir))
{
$dir = dirname($dir);
}
// Is it necessary to convert to the fully expanded path?
$dir = realpath($dir);
$sub = realpath($sub);
// Do we need to worry about Windows?
$dir = str_replace('\\', '/', $dir);
$sub = str_replace('\\', '/', $sub);
// Here we filter leading, trailing and consecutive slashes.
$dir = array_filter(explode('/', $dir));
$sub = array_filter(explode('/', $sub));
// All done!
return array_slice(array_diff($dir, $sub), 0, 1);
}
How about splitting the whole thing into an array:
$fullpath = explode("/", "dir1/dir2/dir3/dir4/filename.ext");
$fulldir = explode("/", "dir1/dir2");
// Will result in array("dir1","dir2","dir3", "dir4", "filename.ext");
// and array("dir1", "dir2");
you should then be able to use array_diff():
$remainder = array_diff($fullpath, $fulldir);
// Should return array("dir3", "dir4", "filename.ext");
then, getting the direct child is easy:
echo $remainder[0];
I can't test this right now but it should work.
Here's a similar "short" solution, this time using string functions rather than array functions. If there is no corresponding part to be gotten from the string, getsubdir will return FALSE. The strtr segment is a quick way to escape the percents, which have special meaning to sscanf.
function getsubdir($str, $dir) {
return sscanf($str, strtr($dir, '%', '%%').'/%[^/]', $name) === 1 ? $name : FALSE;
}
And a quick test so you can see how it behaves:
$str = "dir1/dir2/dir3/dir4/filename.ext";
var_dump(
getSubDir($str, "dir1"),
getSubDir($str, "dir1/dir2/dir3"),
getSubDir($str, "cake")
);
// string(4) "dir2"
// string(4) "dir4"
// bool(false)

Categories