<?php
// get all files from pages/ with .php extension
$pages = glob('pages/*.php');
foreach ($pages as $page) {
// remove path
$page_clean = str_replace('pages/', '', $page);
// put it in an array
$allowed_pages = array($page_clean);
// determine that the lank will be index.php?page=%
$page = $_GET['page'] . '.php';
// load page
if(in_array($page, $allowed_pages)) {
include('pages/' . $page);
} else {
echo "Page not found.";
}
}
?>
It does include the page I call for but it echoes "Page not found" also. What am I doing wrong here?
One love
The if block shouldn't be in the loop. Also, you're constructing the array incorrectly. Try:
<?php
// get all files from pages/ with .php extension
$pages = glob('pages/*.php');
$allowed_pages = array();
foreach ($pages as $page) {
// remove path
$page_clean = str_replace('pages/', '', $page);
// put it in an array
$allowed_pages[] = $page_clean;
}
// determine that the lank will be index.php?page=%
$page = $_GET['page'] . '.php';
// load page
if(in_array($page, $allowed_pages)) {
include('pages/' . $page);
} else {
echo "Page not found.";
}
You shouldn’t browse the whole directory on every request just to see if a given file exists. Just check if that specific file exists:
if (strpos($page, '..') !== false || strpos($page, '/') !== false) {
// invalid value, but you better use a whitelist than a blacklist like I did
} else {
if (is_file('pages/'.$page.'.php')) {
// file exists
} else {
// file doesn’t exist
}
}
I'd do it like this:
if(!isset($_SESSION['allowed_pages'])) {
$_SESSION['allowed_pages'] = array_map('basename', glob('pages/*.php'));
}
$page = $_GET['page'] . '.php';
if(in_array($page, $_SESSION['allowed_pages'])) {
include("pages/$page");
}else {
echo 'Page not found.';
}
That only loads the list of pages once per session and gets rid of the explicit loop for cleaning up the page names from the glob.
Related
I want to display the links separately. One list would include all the .html links and the other all the .jpg links.
right now it displays this and I understand why it is doing it, but when i do another foreach outside or even right before the echo, its like nothing is passing into it.
.jpg
.html
.jpg
.html
I need it to display like this
HTML-Backup HTML
.jpg .html
.jpg .html
php Code
$array = array();
$html= "";
$htmlBackup= "";
if(file_exists("uploads/" . $_POST["prefix"] .'/'))
{
$dir = 'uploads/' . $_POST["prefix"] . '/';
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir));
$prefixDir = scandir($dir);
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.' </br>';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.' </br>';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
}
}
}
Don't put <br> at the end of each echo. Do it after the inner loop so all links from the same directory will be on the same line.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.'';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.'';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
echo "<br>";
}
}
I found a solution by including arrays.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.html") !== false || strpos($lastDir, "H5.html") !== false)
{
//variable to store the list of dir
array_push($html_array, $lastDir);
array_push($html_dir,$secondDir.'/'.$lastDir);
}
else if(strpos($lastDir, "HTML5.jpg") !== false || strpos($lastDir, "H5.jpg")!== false )
{
//variable to store list of dir
array_push($html_backup_array, $lastDir);
array_push($html_backup_dir,$secondDir.'/'.$lastDir);
}
}
}
}
and then display them under in another foreach as I want
if(!empty($html_array))
{
echo "<p>";
echo ("<p><span class='heading'>HTML5 Units</span></p>");
foreach (array_combine($html_dir, $html_array) as $html_dirr => $html_arrays)
{
echo (''.$html_arrays.'');
echo "<br>";
}
echo "</p>";
}
I have a group of pages, and I want to include one of them dependent on a variable in url, but the page is always appear is dashboard
link1 : index.php?pth=&page=dashboard
link2 : index.php?pth=modules/institution&page=inst_classification
if statement :
if (isset($page) && !empty($page)) {
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
}else{
$page ='dashboard';
$pth = '';
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.$page.'.php');
thanks!
You access $page before you write to it. You also never check for the existance of your pth value. Try:
if (empty($_GET['page']) || empty($_GET['pth'])) {
$page ='dashboard';
$pth = '';
}else{
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.$page.'.php');
You probably also need a / here in your include, if modules/institution/inst_classification.php is the file you are looking for:
include('../admin/template/'.$template_fldr.'/html/'.$pth.'/'.$page.'.php'); - but that is not clear from your question.
if (isset($_GET["page"]) && isset($_GET["pth"])) {
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
} else {
$page = 'dashboard';
$pth = '';
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.'/'.$page.'.php');
I have made a function that take in the current page id and based on that result will either show two .php file or just one .php file.
Following is what I have written. Have I approached this in the right way?
<?php
function get_search_or_nav($page_id) {
if(isset($page_id)) {
$id = $page_id;
$pages = array('home', 'thank-you');
foreach($pages as $page){
if($page==$id)
$match = true;
}
if($match) {
include("dir/file_1.php");
include("dir/file_2.php");
}
elseif (!$match) {
include("dir/file_1.php");
}
}
}
?>
The $pages variable holds the $page_id array i.e.$pages = array('home', 'thank-you');
each .php file has a $page_id i.e index.php has $page_id = "home";
The array is a list of the matching $page_id's:
$pages = array('home', 'thank-you');
The call would then be:
get_search_or_nav($page_id);
Any help or advise would be appreciated.
I just will do this:
$id = $page_id;
$pages = array('home', 'thank-you');
$match = in_array($id, $pages);
The iteration is not necessary
There is no need for the foreach loop. PHP has inbuilt functions to handle what you want (in_array()): I'd change your function to something like this:
function get_search_or_nav($page_id) {
if (isset($page_id)) {
$id = $page_id;
$pages = array('home', 'thank-you');
// make sure file is in allowed array (meaning it exists)
if(in_array(id, $pages)) {
include("dir/file_1.php");
include("dir/file_2.php");
return true;
}
// no match, so include the other file
include("dir/file_1.php");
return false;
}
}
You could approach your function in following way:
function get_search_or_nav($page_id) {
if(isset($page_id)) {
$pages = array('home', 'thank-you');
// You could do this with for loop
// but PHP offers in_array function that checks
// if the given value exists in an array or not
// if found returns true else false
$match = in_array($page_id, $pages);
// you are including this in either case
// so no need to repeat it twice in both conditions
include("dir/file_1.php");
// if match include file 2
if ($match) {
include("dir/file_2.php");
}
}
// you might want to throw Exception or log error here
// or just redirect to some 404 page or whatever is your requirement
}
in_array reference
Is it possible to determine what to show depending on the URL?
I have an index file which is:
<?php include './includes/header.php'; ?>
<?php include './includes/menu.php'; ?>
<?php include './includes/content.php'; ?>
<?php include './includes/sidebar.php'; ?>
<?php include './includes/footer.php'; ?>
Note: I have different "content.php"'s
Is it possible to do something like:
If Url = url {
show only content for the url
}
and then have case system like
case: home.php
show some
etc
I know Wordpress can do it. Is it possible with PHP and MySQL and HTML?
EDIT: Instead of content.php i would want show the desired HTML code gotten from my db
Use this function to see your current page. Then use the "switch" case for proper include file:
## Get Current Page / Section
function cur_page()
{
$cur_page='';
if(isset($_SERVER['PHP_SELF']) && $_SERVER['PHP_SELF']!='')
{
$temp_var1 = explode('/', $_SERVER['PHP_SELF']);
$cur_page = $temp_var1[count($temp_var1)-1];
}
else if(isset($_SERVER['SCRIPT_NAME']) && $_SERVER['SCRIPT_NAME']!='')
{
$temp_var1 = explode('/', $_SERVER['SCRIPT_NAME']);
$cur_page = $temp_var1[count($temp_var1)-1];
}
else if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI']!='')
{
$temp_var1 = explode('/', $_SERVER['REQUEST_URI']);
$cur_page = $temp_var1[count($temp_var1)-1];
$temp_var2 = explode('?', $cur_page);
$cur_page = $temp_var2[0];
}
else if(isset($_SERVER['SCRIPT_FILENAME']) && $_SERVER['SCRIPT_FILENAME']!='')
{
$temp_var1 = explode('/', $_SERVER['SCRIPT_FILENAME']);
$cur_page = $temp_var1[count($temp_var1)-1];
}
return $cur_page;
}//end func.....
Querying from database.
I don't recommend MySql, and I hope you learn PDO instead, but just
for this example
function get_me_title($page) {
$query = "SELECT * FROM title WHERE title = $page";
$result = mysql_query($query);
foreach($result as $row) {
return $row[$page];
}
}
Now, you can use function .get_me_title('whatever') to query from database, and echo below
if(isset($_GET['page_id'])) {
$page = $_GET['page_id'];
switch($page) {
case "contact";
echo get_me_title('contact');
break;
case "about";
echo get_me_title('about');
break;
case "portofolio";
echo get_me_title('portofolio')
break;
default:
echo 'you are in home page';
}
}else {echo '404 ERROR! The Page you have requested does not exist';}
Instead of including content.php, you can include needed page.
For example, if You build Your urls, where, for example, $_GET['page'] will refer to needed page, then simply You can do this.
$availablePages = array('default' => 'home', 'about');
if (isset($_GET['page']) && in_array($_GET['page'], $availablePages) {
$page = $_GET['page'] . '.php';
} else {
$page = $availablePages['default'] . '.php';
}
include $page;
How may i able to retrieve different file extensions in a certain directory. Let say i have a folder named "downloads/", where inside that folder are different types of files like PDFs, JPEGs, DOC files etc. So in my PHP code i wanted those files be retrieved and listed with there file names and file extensions. Example: Inside "downloads/" folder are different files
downloads/
- My Poem.doc
- My Photographs.jpg
- My Research.pdf
So i wanted to view those files where i can get there file names, file extensions, and file directories. So in view will be something like this
Title: My Poem
Type: Document
Link: [url here]
Title: My Photographs
Type: Image
Link: [url here]
Title: My Research
Type: PDF
Link: [url here]
Anyone knows how to do it in php? Thanks a lot!
It's pretty simple. To be honest i don't know why didn't you searched on a php.net. They got whole lots of examples for this. Check it in here: click
Example:
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
//---------------------------------------------------------//
// - SECTION 1 - //
// Actions to be performed on ALL ITEMS //
//----------------- Begin Editable ------------------//
$entry['modtime'] = filemtime($path);
//----------------- End Editable ------------------//
do if (!is_dir($path)) {
//---------------------------------------------------------//
// - SECTION 2 - //
// Actions to be performed on FILES ONLY //
//----------------- Begin Editable ------------------//
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
//----------------- End Editable ------------------//
break;
} else {
//---------------------------------------------------------//
// - SECTION 3 - //
// Actions to be performed on DIRECTORIES ONLY //
//----------------- Begin Editable ------------------//
//----------------- End Editable ------------------//
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
// Output each opened file and then close
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>
You could use glob & pathinfo:
<?php
foreach (glob(__DIR__.'/*') as $filename) {
print_r(pathinfo($filename));
}
?>
You will try this code :
$Name = array();
$ext = array();
$downloadlink = array();
$dir = 'downloads'
while ($file= readdir($dir))
{
if ($file!= "." && $file!= "..")
{
$temp = explode(".",$file);
if (count($temp) > 1)
{
$Name[count($Name)] = $temp[0];
swich($ext)
{
case "doc" :
{
$ext[count($ext)] = "Document";
break;
}
[...]
default :
{
$ext[count($ext)] = "Error";
break;
}
}
$downloadlink[count($downloadlink)] = "http://yourdomain.com/".$dir."/".$file;
}
}
}
closedir($dir);
for($aux = 0; $aux < count($Name); $aux++)
{
echo "Name = " . $Name[$aux]."<br />
Type = " . $ext[$aux]."<br/>
Link = " . $downloadlink[$aux]."<br/>
";
}