PHP not stopping the include (break) - php

I'm trying to get my script to find all of the PHP files in my include directory and put them in to an array (I've done the array part). Then, the script does a for loop to check if the GET request matches the current position value in the array (or whatever you want to call it).
But, if it doesn't find it at all.. it will include the default page, but obviously if it does it'll include the file it matched.
The problem is.. the break command isn't working at all. So, it's including the default page if it's been matched. Please help.
<?php
if(!defined("PLUGIN")){
echo "You cannot view this file directly.";
} else {
$glob = glob("inc/*.php");
$count = count($glob);
for($i=0;$i<$count;$i++){
$explode = explode("/", $glob[$i]);
$explode2 = explode(".", $explode[1]);
if($_GET["page"] == $explode2[0]){
include $glob[$i];
break;
} include_once "default.php";
}
}
?>

As it stands now, your loop will include the default page on EVERY iteration of the loop, until it matches that get/explode combination.
As well, using explode for analyzing file paths is poor practice. Instead, use path_info():
$found = false;
foreach ($glob as $file) {
$basename = path_info($file, PATHINFO_FILENAME);
if ($basename == $_GET['page']) {
$found = true;
break;
} else {
include($basename); // probably need to adjust this to make it a full filename
}
}
if (!$found) {
include('default.php'); // include this only if no other match was found.
}

Related

while loop with operator++ only counting up once

I adopted code from https://stackoverflow.com/a/44553006/8719001
but can't figure out why when uploading the same file "test.jpg" several times it only counts up once, creating "test-1.jpg" but not more ie. test-2.jpg, test-3.jpg.
Can anybody spot the issue and help please?
$keepFilesSeperator = "-";
$keepFilesNumberStart = 1;
if (isset($_FILES['upload'])) {
// Be careful about all the data that it's sent!!!
// Check that the user is authenticated, that the file isn't too big,
// that it matches the kind of allowed resources...
$name = $_FILES['upload']['name'];
//If overwriteFiles is true, files will be overwritten automatically.
if(!$overwriteFiles)
{
$ext = ".".pathinfo($name, PATHINFO_EXTENSION);
// Check if file exists, if it does loop through numbers until it doesn't.
// reassign name at the end, if it does exist.
if(file_exists($basePath.$name))
{
$operator = $keepFilesNumberStart;
//loop until file does not exist, every loop changes the operator to a different value.
while(file_exists($basePath.$name.$keepFilesSeperator.$operator))
{
$operator++;
}
$name = rtrim($name, $ext).$keepFilesSeperator.$operator.$ext;
}
}
move_uploaded_file($_FILES["upload"]["tmp_name"], $basePath . $name);
}
your while loop condition has a problem
while( file_exists( $basePath.$name.$keepFilesSeperator.$operator ) )
the $name variable still contains the full name of file, in this case test.jpg, you're testing a value like /home/test.jpg-1 so finally the while loop is never executed as the file test.jpg-1 never exists, that's why you always get the test-1.jpg on disk and not a ...-2.jpg or ...-3.jpg

PHP 5.3.x - How do I turn the server path into its domain name, and a clickable URL?

I'm a newbie...sorry...I'll admit that I've cobbled this script together from several sources, but I'm trying to learn. :-) Thanks for any help offered!!
$directory = new \RecursiveDirectoryIterator(__DIR__, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) {
if ($current->getFilename() === '.') {
return FALSE;
}
if ($current->isDir()) {
return $current->getFilename() !== 'css';
}
else {
// Only consume files of interest.
return strpos($current->getFilename(), 'story.html') === 0;
}
});
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
$files[] = $info->getPathname();
}
?>
Then down in my HTML is where I run into problems, in the 2nd echo statement...
<?php
echo '<ul>';
foreach ($files as $item){
echo '<li>http://<domain.com/directory/subdirectory/story.html></li>';
echo '</ul>';
};
?>
The purpose of my script is to "crawl" a directory looking for a specific file name in sub-directories. Then, when it finds this file, to create a human-readable, clickable URL from the server path. Up to now, my HTML gets one of these two server paths as my list item:
http://thedomain.com/var/www/vhosts/thedomain.com/httpdocs/directory/subdirectory/story.html
or
file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html
...depending on where I'm running my .php page.
I feel like I need to "strip away" part of these paths... to get down to /subdirectory/story.html ... If I could do that, then I think I can add the rest into my echo statements. Everything I've found for stripping strings has been from the trailing end of the path, not the leading end. (dirname($item)) takes away the filename, and (basename($item)) takes away the subdirectory and the filename ... the bits I want!!
Try this function
function strip($url){
$info = parse_url($url);
$slash = (explode('/',$info['path']));
$sub = $slash[count($slash)-2];
$file = basename($url)==$sub ? "" : basename($url);
return "/".$sub."/".$file;
}
calling it by
echo strip('file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html');
will result in
/subdirectory/story.html

get file name include_once file based on name

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.

Detecting between the lowercase and uppercase php

I am using this script to delete picture from my server. But at the same time I want to protect the files in my server. Not accidentally delete but I noticed that if I typed the file index.pHp or index.Php is deleted from my server. Although setting it will not delete why php or this method not know between lowercase and uppercase.
What is not done right?
<?php
error_reporting (0);
$thefile = $_GET ['filetodel'];
$filename = "$thefile";
//$filename = "picture1.jpg";
/*protect some files*/
if ($thefile=='index.php' or $thefile=='INDEX.PHP' or $thefile=='UPLOADS.ZIP' or $thefile=='uploads.zip' or $thefile=='del.php'or $thefile=='DEL.PHP' or $thefile==NULL or $thefile=='.htaccess' or $thefile=='.HTACCESS' )
{
exit("<h2>cannot delete $thefile</h2>");
}
if ($thefile=="$thefile")
{
if (file_exists($filename))
{
unlink ("$thefile");
echo "<h2> file $thefile is delete</h2>";
}
else
{
echo "<h2>The<br>";
echo "$filename<br>";
echo "Does not exist</h2>";
}
}
?>
Just convert the input to lowercase and test it once, rather than worrying about every possible mix of case:
if (strtolower($thefile) == 'index.php') {
// ...
}
For the next iteration, you could store your protected files in an array:
$protected_files = array('index.php', 'uploads.zip', 'del.php', '.htaccess');
if (in_array(strtolower($thefile), $protected_files) || $thefile==NULL) {
// ...
}
the problem is here:
if ($thefile=="$thefile")
as if your 1st condition for file check is false than the second condition is
if ($thefile=="$thefile")
which is always true so it will unlink the file
Also add one line as below just before 1st condition
$thefile = strtolower($thefile);

Make PHP include randomizer not repeat itself

Situation
I have a relatively short php code I found and tweaked that includes a random html file from my 'randomizer' folder into my page.
Here is the code
<?php
error_reporting(0);
function random_file($string){
return ((file_exists($string))&&(preg_match('#(\.html)$#i',$string))) ? true : false ;
}
define('OUTPUT_TYPE','text');
define('RANDOM_FILES_FOLDER','randomizer/');
$my_array = Array();
$my_dir = RANDOM_FILES_FOLDER ;
if ($dir = #opendir("$my_dir")) {
while (($file = readdir($dir)) !== false) {
if ($file != "." && $file != ".." && !is_dir($my_dir.$file))
{
switch(OUTPUT_TYPE):
case'text':
if(random_file($my_dir.$file)){
$my_array[] = $file;
}
break;
default:
break;
endswitch;
}
}
closedir($dir);
}
if(count($my_array)>0){
$random_number = rand(0, count($my_array)-1);
$random_file = $my_array[$random_number];
switch(OUTPUT_TYPE):
case'text':
include($my_dir.$random_file);
break;
default:
break;
endswitch;
}
?>
Question
It does what it is supposed to do (perhaps someone can trim/optimize that code for me) but I have only a few files to randomize and I don't want the same file to appear twice when I refresh or open the page a day after.
I think cookies may be the answer, but not sure how to do anything with them.
Can anyone write a piece code to add to mine to do that or provide a code that has all those attributes? keep in mind it must include files at random from a folder, I don't want the code from those files on my actual page code for CMS purposes
Keep in mind I am a PHP and Javascript beginner with VERY basic knowledge, so please dumb it down for me.
Thanks!
Very rough:
session_start();
$dir = 'randomizer/';
if (empty($_SESSION['files'])) {
$_SESSION['files'] = array_filter(scandir($dir), function ($file) use ($dir) {
return is_file($dir . $file) && preg_match('#(\.html)$#i', $file);
});
shuffle($_SESSION['files']);
}
include $dir . array_shift($_SESSION['files']);
Keep a list of all candidate files in the session, use them one by one. That way all files will be displayed once in random order before the cycle starts again. Only not recommended if the list is very long.
It's worth noting that the array_filter callback syntax requires PHP 5.3.
This is not the perfect way to do this but it will work(intentionally simple):
Include this after the line $random_file = $my_array[$random_number];
$oldFile = ''
if(!empty($_COOKIE['oldfilename']) {
$oldFile = $_COOKIE['oldfilename'];
}
while ($oldFile == $random_file) {
$random_number = rand(0, count($my_array)-1);
$random_file = $my_array[$random_number];
}
setcookie('oldfilename', $random_file);

Categories