Include php file randomly - php

I have a question about php include. Here goes the existing code that i have.
<?php
srand();
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php");
$rand = array_rand($files);
include ($files[$rand]);
?>
This code actually works very well for me now as the content displaying randomly. But, i would like to get something better. Because, by using this code, everytime i have added a new content like content5.php, content6.php and so on, i have to bother to update the code above to make new content.php appear.
Is there any solution i can have, to not to bother the code above everytime i add a new content.php and the new content.php appears automatically when added? Is it possible?
Updated: New testing code(tested failed again with part of my page mising)
<?php
$sDirectory = 'myfolder';
if( is_dir( $sDirectory ) )
{
$rDir = opendir( $sDirectory );
while( ( $sFile = readdir( $rDir ) ) !== FALSE )
{
if( ( $sFile == '.' ) || ( $sFile === '..' ) )
{
continue;
}
$aFiles[] = $sDirectory . '/' . $sFile;
}
}
$sRandom = array_rand( $aFiles );
require_once( $aFiles[ $sRandom ] );
?>

$sDirectory = 'includes';
if( is_dir( $sDirectory ) )
{
$rDir = opendir( $sDirectory );
while( ( $sFile = readdir( $rDir ) ) !== FALSE )
{
if( ( $sFile == '.' ) || ( $sFile === '..' ) )
{
continue;
}
$aFiles[] = $sDirectory . '/' . $sFile;
}
}
$sRandom = array_rand( $aFiles );
require_once( $aFiles[ $sRandom ] );

Related

PHP zip file downloads locally but not in production

I am working on some files to download in a zip. Works fine locally but not in any environment (staging or production). Using WP VIP also, not sure if that helps. I'm a little new to VIP. Really racked by brains here and can't seem to figure out the issue.
I've read the resources on PHP zip creation. I do get the "Unable to add zip file.', 500 );" error producing.
Code below:
$context = [];
$post = theme()->twig()->create_post();
$tab_index = filter_input( INPUT_GET, 'tab-index', FILTER_SANITIZE_NUMBER_INT );
$content_calendar = $post->get_field('content_calendar');
if ( ! isset( $content_calendar[ $tab_index ] ) ) {
\wp_send_json_error( 'Invalid tab-index.', 400 );
exit;
}
$tab = $content_calendar[ $tab_index ];
// Create zip name;
$name = 'content-calendar-' . $tab_index;
$group_index = filter_input( INPUT_GET, 'group-index', FILTER_SANITIZE_NUMBER_INT );
if ( null !== $group_index ) {
if ( ! isset( $tab['groups'][ $group_index ] ) ) {
\wp_send_json_error( 'Invalid group-index.', 400 );
exit;
}
$groups = [ $tab['groups'][ $group_index ] ];
// Append group to name
$name .= '-' . $group_index;
} else {
$groups = $tab['groups'];
}
// Extract paths from resources with assets
$paths = [];
foreach ( $groups as $group ) {
foreach ( $group['resources'] as $resource ) {
if ( $resource['social_resource'] ) {
$asset_id = get_field( 'asset', $resource['social_resource'] );
if ( $asset_id ) {
$paths[] = get_attached_file( $asset_id, true );
}
}
}
}
// Remove invalid or duplicate URLs
$paths = array_unique( array_filter( $paths ) );
if ( empty( $paths ) ) {
\wp_send_json_error( 'No files to download.', 400 );
exit;
}
// Generate file names
$zipfile = wp_upload_dir()['basedir'] . '/' . $name . '.zip';
$zipname = $name . '-' . date('Y-m-d') . '.zip';
// Generate file
$zip = new ZipArchive;
if ( true !== $zip->open( $zipfile, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
\wp_send_json_error( 'Unable to create zip file.', 500 );
exit;
}
foreach ( $paths as $path ) {
if ( true !== $zip->addFile( $path, basename( $path ) ) ) {
$zip->close();
\wp_send_json_error( 'Unable to add file to zip.', 500 );
exit;
}
}
$zip->close();
// Send headers and stream file
header( 'Content-Type: application/zip' );
header( 'Content-disposition: attachment; filename=' . $zipname );
header( 'Content-Length: ' . filesize( $zipfile ) );
readfile( $zipfile );
exit;
Any help is appreciated.

php scan directories in direcctories

Problem it's in sub directories, i have many sub directories and sub sub directories, i need check them all, Maybe someone know how to help .
My code:
$mainFodlers = array_diff(scandir(self::PROJECT_DIRECTORY, 1), array('..', '.','__todo.txt'));
foreach ($mainFodlers as $mainFodler) {
if (is_dir(self::PROJECT_DIRECTORY . '/' . $mainFodler)) {
$subFolders = array_diff(scandir(self::PROJECT_DIRECTORY . '/' . $mainFodler, 1), array('..', '.','__todo.txt', 'share_scripts.phtml'));
} else {
$extension = $this->getExtension($subFolder);
if ($extension == 'phtml') {
$file = $subFolder;
$fileContent = file_get_contents(self::PROJECT_DIRECTORY . '/views/' . $file, true);
}
}
}
Because I cannot really determine the end result of your code it is hard to answer effectively but to solve the problem of nested folders you might wish to consider a recursiveIterator type approach. The following code should give a good starting point for you - it takes a directory $dir and will iterate through it and it's children.
/* Start directory */
$dir='c:/temp2';
/* Files & Folders to exclude */
$exclusions=array(
'oem_no_drivermax.inf',
'smwdm.sys',
'file_x',
'folder_x'
);
$dirItr = new RecursiveDirectoryIterator( $dir );
$filterItr = new DirFileFilter( $dirItr, $exclusions, $dir, 'all' );
$recItr = new RecursiveIteratorIterator( $filterItr, RecursiveIteratorIterator::SELF_FIRST );
foreach( $recItr as $filepath => $info ){
$key = realpath( $info->getPathName() );
$filename = $info->getFileName();
echo 'Key = '.$key . ' ~ Filename = '.$filename.'<br />';
}
$dirItr = $filterItr = $recItr = null;
Supporting class
class DirFileFilter extends RecursiveFilterIterator{
protected $exclude;
protected $root;
protected $mode;
public function __construct( $iterator, $exclude=array(), $root, $mode='all' ){
parent::__construct( $iterator );
$this->exclude = $exclude;
$this->root = $root;
$this->mode = $mode;
}
public function accept(){
$folpath=rtrim( str_replace( $this->root, '', $this->getPathname() ), '\\' );
$ext=strtolower( pathinfo( $this->getFilename(), PATHINFO_EXTENSION ) );
switch( $this->mode ){
case 'all':
return !( in_array( $this->getFilename(), $this->exclude ) or in_array( $folpath, $this->exclude ) or in_array( $ext, $this->exclude ) );
case 'files':
return ( $this->isFile() && ( !in_array( $this->getFilename(), $this->exclude ) or !in_array( $ext, $this->exclude ) ) );
break;
case 'dirs':
case 'folders':
return ( $this->isDir() && !( in_array( $this->getFilename(), $this->exclude ) ) && !in_array( $folpath, $this->exclude ) );
break;
default:
echo 'config error: ' . $this->mode .' is not recognised';
break;
}
return false;
}
public function getChildren(){
return new self( $this->getInnerIterator()->getChildren(), $this->exclude, $this->root, $this->mode );
}
}

$_POST variable staying the same

I'm having trouble with this code and using different emails to view images in a directory (processed/$email) and the email changes per user's respective form entry, yet only shows the images from the most recent folder created regardless of the email given.
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST">
E-mail:
<input type="text" name="email" id="email2"><br>
<br>
<input type="submit" value="Retrieve" name="submit"><br><br>
</form>
and here's the PHP:
<?php
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path)
&& in_array(end(explode('.', end(explode('/', $path)))), $exts)
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:250px;max-width:250px" /> </a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
echo scanDirectoryImages(processed.$_POST['email2']);
?>
I've tried unsetting variables, etc. It doesn't work. When I go back to the form from any page, it's still only showing the most recently uploaded folder of images. The only thing that will make it show new images is if there is a new directory. I feel like I must be approaching this fundamentally wrong somehow and I'm new to PHP so some help would be hugely appreciated.
The original function has a recursive nature to it but doesn't utilise the existing suite of recursiveIterator classes - hopefully the below will be of use in that respect. When I tried your original function all I got it to return was a folder name and not a list of files / images.
function scanImageDirectory( $directory, $root, $exts=array('jpg','jpeg','png','gif'), $exclusions=array('bmp') ){
$html=array();
$dirItr = new RecursiveDirectoryIterator( $directory );
$filterItr = new DirFileFilter( $dirItr, $exclusions, $directory, 'all' );
$recItr = new RecursiveIteratorIterator( $filterItr, RecursiveIteratorIterator::SELF_FIRST );
foreach( $recItr as $filepath => $info ){
if( $info->isFile() && in_array( strtolower( pathinfo( $info, PATHINFO_EXTENSION ) ), $exts ) ) {
$filename=str_replace( array( realpath( $root ), chr(92) ), array( '', chr(47) ), realpath( $info ) );
$html[]="<a href='{$filename}' target='_blank'><img src='{$filename}' alt='{$info->getFilename()}' /></a>";
}
}
return implode( PHP_EOL,$html );
}
$dir=ROOT.'/images/css/icons/browsers';
$root='c:/wwwroot';
echo scanImageDirectory( $dir, $root );
Or, as example for your situation
$dir="processed/{$_POST['email']}";
$root=$_SERVER['DOCUMENT_ROOT'];
echo scanImageDirectory( $dir, $root );
I realise that the class DirFileFilter is one I wrote and not a native PHP class - this can only be described as an id-10-T error.. Apologies - here is that class.
class DirFileFilter extends RecursiveFilterIterator{
protected $exclude;
protected $root;
protected $mode;
public function __construct( $iterator, array $exclude, $root, $mode='all' ){
parent::__construct( $iterator );
$this->exclude = $exclude;
$this->root = $root;
$this->mode = $mode;
}
public function accept(){
$folpath=rtrim( str_replace( $this->root, '', $this->getPathname() ), '\\' );
$ext=strtolower( pathinfo( $this->getFilename(), PATHINFO_EXTENSION ) );
switch( $this->mode ){
case 'all':
return !( in_array( $this->getFilename(), $this->exclude ) or in_array( $folpath, $this->exclude ) or in_array( $ext, $this->exclude ) );
case 'files':
return ( $this->isFile() && ( !in_array( $this->getFilename(), $this->exclude ) or !in_array( $ext, $this->exclude ) ) );
break;
case 'dirs':
case 'folders':
return ( $this->isDir() && !( in_array( $this->getFilename(), $this->exclude ) ) && !in_array( $folpath, $this->exclude ) );
break;
default:
echo 'config error: ' . $this->mode .' is not recognised';
break;
}
return false;
}
public function getChildren(){
return new self( $this->getInnerIterator()->getChildren(), $this->exclude, $this->root, $this->mode );
}
}

Using php for an automatic updating sitemap

How would I get this to index pages that have no ending at all? My website is created of pages similar to this http://www.example.com/example/post-id-the-post-title-would-go-here and because it has no ending it does not display within the sitemap.
Update
Config.php
define( 'SITEMAP_DIR', './' );
define( 'SITEMAP_DIR_URL', 'http://www.example.com' );
define( 'RECURSIVE', true );
$filetypes = array( 'php', 'html', 'pdf' );
// The replace array, this works as file => replacement, so 'index.php' => '', would make the index.php be listed as just /
$replace = array( 'index.php' => '' );
$xsl = 'xml.xsl';
$chfreq = 'daily';
$prio = 1;
$ignore = array( 'config.php' );
I am not interested in rewriting the urls because I have already done this from the http://www.exaple.com/index.php?a=track&id=17 when I first started.
Sitemap.php
require './config.php';
// Get the keys so we can check quickly
$replace_files = array_keys( $replace );
// Sent the correct header so browsers display properly, with or without XSL.
header( 'Content-Type: application/xml' );
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
$ignore = array_merge( $ignore, array( '.', '..', 'config.php', 'xml-sitemap.php' ) );
if ( isset( $xsl ) && !empty( $xsl ) )
echo '<?xml-stylesheet type="text/xsl" href="' . SITEMAP_DIR_URL . $xsl . '"?>' . "\n";
function parse_dir( $dir, $url ) {
global $ignore, $filetypes, $replace, $chfreq, $prio;
$handle = opendir( $dir );
while ( false !== ( $file = readdir( $handle ) ) ) {
// Check if this file needs to be ignored, if so, skip it.
if ( in_array( utf8_encode( $file ), $ignore ) )
continue;
if ( is_dir( $file ) ) {
if ( defined( 'RECURSIVE' ) && RECURSIVE )
parse_dir( $file, $url . $file . '/' );
}
// Check whether the file has on of the extensions allowed for this XML sitemap
$fileinfo = pathinfo( $dir . $file );
if ( in_array( $fileinfo['extension'], $filetypes ) ) {
// Create a W3C valid date for use in the XML sitemap based on the file modification time
if (filemtime( $dir .'/'. $file )==FALSE) {
$mod = date( 'c', filectime( $dir . $file ) );
} else {
$mod = date( 'c', filemtime( $dir . $file ) );
}
// Replace the file with it's replacement from the settings, if needed.
if ( in_array( $file, $replace ) )
$file = $replace[$file];
// Start creating the output
?>
<url>
<loc><?php echo $url . rawurlencode( $file ); ?></loc>
<lastmod><?php echo $mod; ?></lastmod>
<changefreq><?php echo $chfreq; ?></changefreq>
<priority><?php echo $prio; ?></priority>
</url><?php
}
}
closedir( $handle );
}
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><?php
parse_dir( SITEMAP_DIR, SITEMAP_DIR_URL );
?>
</urlset>

PHP: Variable changes value without seemingly any reason

$subjectDirectory = '../blogtext/';
$subjectHandle = opendir( $subjectDirectory );
$fileName = $_SERVER['PHP_SELF'];
$tempArray = explode( '-', $fileName );
$finalNum = '-'.$tempArray[1].'-';
$subjectFile;
if( $subjectHandle = opendir( '../blogtext/' ) )
{
/* If you echo $finalNum here, you get '-0-' on the page. */
while( false !== ( $subjectFile = readdir( $subjectHandle ) ) )
{
/* If you echo $finalNum here, you get '-0--0--0--0--0-' on the page. */
if( $subjectFile != '.' && $subjectFile != '..' && !is_dir( $subjectFile ) && strpos( $subjectFile, $finalNum ) )
{
include( $subjectFile );
}
}
closedir( $subjectHandle );
}
Basically, what I'm trying to do is;
get -NUMBER- code from the current file name ( -0-example.php ), and then scan through the directory ( $subjectDirectory ) for the file name that begins with the same code. Then include the file.
I'm unable to do so because the $finalNum changes the code to "code 5 times in a row", so I can't find the right file to include.
The reason it's not working is because readdir() returns the file name only, not the full path.
Try this:
include( $subjectDirectory . $subjectFile );
Re: /* If you echo $finalNum here, you get '-0--0--0--0--0-' on the page. */
The reason you get this output is because you are echoing $finalNum 5 times. The value of $finalNum is not changing.
EDIT:
I found one more issue in your if statement. strpos( $subjectFile, $finalNum ) will return 0 if the $subjectFile starts with $finalNum.
Use this instead.
if( $subjectFile != '.' && $subjectFile != '..' && !is_dir( $subjectFile ) && strpos( $subjectFile, $finalNum ) !== false )

Categories