$_POST variable staying the same - php

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 );
}
}

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 : How to fix array_pop and the value 0

I´m trying from various paths to generate a dimensional array.
For that, I´m using the function found here.
My code
function get_dir_content_to_array( string $dir_path, string $dir_filter = null, string $file_filter = null ) {
if( is_dir_empty( $dir_path ) )
return false;
$output = array();
$files = get_subdir_filtered( $dir_path, $dir_filter, $file_filter );
if ( isset( $files ) ) {
foreach ( $files as $name => $object ) {
if ( $object->getFilename() !== "." && $object->getFilename() !== ".." ) {
// Split by the delimiter.
$delimiter = "/";
$name = str_replace( "\\", $delimiter, $name );
$relative_path = str_replace( $dir_path, "", $name );
$a_relative_path = explode( $delimiter, $relative_path );
$path = [ array_pop( $a_relative_path ) ];
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$path = [ $pathPart => $path ];
}
// Add it to a temp list.
$paths[] = $path;
}
$output = call_user_func_array( 'array_merge_recursive', $paths );
}
}
return $output;
}
function get_subdir_filtered( $dir_path, $dir_filter, $file_filter ) {
$path = realpath( $dir_path );
$directory = new \RecursiveDirectoryIterator( $path );
$files = null;
if ( ! empty( $dir_filter ) || ! empty( $file_filter ) ) {
if ( ! empty( $dir_filter ) ) {
$filter = new DirnameFilter( $directory, $dir_filter );
}
if ( ! empty( $file_filter ) ) {
$filter = new FilenameFilter( $filter, $file_filter );
}
$files = new \RecursiveIteratorIterator( $filter );
} else {
$files = new \RecursiveIteratorIterator( $directory );
}
return $files;
}
class DirnameFilter extends FilesystemRegexFilter {
// Filter directories against the regex
public function accept() {
return ( ! $this->isDir() || preg_match( $this->regex, $this->getFilename() ) );
}
}
That works except when a folder is named "0"
How can I fixed that ?
Why array_pop skip the value "0" even if it´s a string ?
When json_encode() encodes an array whose keys are sequential integers starting from 0, or the string equivalents of them, it produces a JSON array rather than an object.
You could use the JSON_FORCE_OBJECT flag, but this will then turn the arrays of filenames inside a folder into objects, which you don't want.
What you can do is use a PHP object instead of an array to represent a folder. json_encode() will encode this as an object, even if it has numeric properties.
I think this might do it:
function get_dir_content_to_array( string $dir_path, string $dir_filter = null, string $file_filter = null ) {
if( is_dir_empty( $dir_path ) )
return false;
$output = array();
$files = get_subdir_filtered( $dir_path, $dir_filter, $file_filter );
if ( isset( $files ) ) {
foreach ( $files as $name => $object ) {
if ( $object->getFilename() !== "." && $object->getFilename() !== ".." ) {
// Split by the delimiter.
$delimiter = "/";
$name = str_replace( "\\", $delimiter, $name );
$relative_path = str_replace( $dir_path, "", $name );
$a_relative_path = explode( $delimiter, $relative_path );
$path = [ array_pop( $a_relative_path ) ];
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$folder = new StdClass;
$folder->{$pathPart} = $path;
$path = $folder;
}
// Add it to a temp list.
$paths[] = $path;
}
$output = call_user_func_array( 'array_merge_recursive', $paths);
}
}
return $output;
}
I haven't tested it because I don't have the get_subdir_filtered() function. It's possible that array_merge_recursive won't do the correct merge of this. You might need to merge the objects, too. This tutorial contains an implementation of mergeObjectsRecursively that I think should be a useful substitute.
In my case I got this path : update.json and 0/1/0/filename.zip
As #Barmar said, basically, the problem is when I try to convert an array to a json object.
In PHP, an array is in fact, all the time an object so... $arr = [ "0" => [ "1" => ... ] ] for php, is equal to : $arr = [ 0 => [ 1 => ... ] ]. In PHP 7.2.x, each time you will merge objects, The "0" as string key will be cast to 0 as int.
Consequences
1 . with json_encode
echo json_encode( get_dir_content_to_array(...) );
//result = ["update.json",{"1":[["filename.zip"]]}]
2 . with json_encode and JSON_FORCE_OBJECT
echo json_encode( get_dir_content_to_array(...), JSON_FORCE_OBJECT );
//result = {"0":"update.json","1":{"1":{"0":{"0":"filename.zip"}}}}
//I got 1,0,0,filename.zip instead of 0,1,0,filename.zip
3 . Add (string)
$path = [array_pop( $a_relative_path)];
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$path = [ (string) $pathPart => $path ];
}
//Same result of 2.
To keep the right order for the path, I found for the moment a hacky solution :
Add underscore before each key
foreach ( array_reverse( $a_relative_path ) as $pathPart ) {
$path = [ "_" . $a_relative_path => $path ];
}
//result = {"0":"update.json", "_0":{"_1":{"_0":{"0":"filenamezip"}}}}
//With a new file path, I got this :
// {"0":"update.json","_toto":{"_foo":{"0":"test.txt"}},"_0":{"_1":{"_0":{"0":"filename.zip"}}}}
This solution is a hack, but I can make a difference between a kee which is a path "_0":{"_1":{"_0" and a key to index a file "0":"filename.zip"

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 );
}
}

Recieving PHP Warning copy(): Filename cannot be empty

I am receiving this warning in one of the Wordpress plugins.
copy(): Filename cannot be empty in /wp-content/plugins/nix-gravatar-cache/nf-gravatar-cache.php on line 181
Please help me correct this, if somebody can. I am not very good with PHP. Thanks
Here is the code.
<?php
class NFGC_Gravatar_Cache {
protected $upload_url;
protected $upload_path;
protected $plugin_dir_path;
public $plugin_name = 'NIX Gravatar Cache';
function __construct(){
if ( get_option( 'upload_url_path' ) ) {
$this->upload_url = get_option( 'upload_url_path' );
$this->upload_path = get_option( 'upload_path' );
}
else {
$up_dir = wp_upload_dir();
$this->upload_url = $up_dir['baseurl'];
$this->upload_path = $up_dir['basedir'];
}
$this->plugin_dir_path = plugin_dir_path( __FILE__ );
require_once $this->plugin_dir_path . '/messages.class.php';
NFGC_Messages::init();
$active = get_option( 'nf_c_a_options' );
if ( $active[0]['active'] == 1 ) {
add_filter( 'get_avatar', array( $this,'get_cached_avatar' ), -1000000000, 5 );
}
add_action( 'admin_menu', array( $this,'add_admin_menu' ) );
register_activation_hook( __FILE__, array( $this, 'activate' ) );
$this->init();
register_deactivation_hook( __FILE__, 'deactivate' );
register_uninstall_hook( __FILE__ , 'uninstall' );
if ( !is_writable( $this->upload_path.'/gravatar/' ) && is_dir( $this->upload_path.'/gravatar/' ) ) {
NFGC_Messages::add_message( 'error', 'Please set write permissions for "'. $this->upload_path .'/gravatar/"' );
}else{
if ( #!mkdir( $this->upload_path.'/gravatar/', 0777 ) && ! is_dir( $this->upload_path.'/gravatar/' ) ) {
NFGC_Messages::add_message( 'error', 'Could not create directory "gravatar". Please set write permissions for "'. $this->upload_path .'/gravatar/"' );
}
}
if ( isset ( $_POST['nf_clear_cache'] ) )
$this->clear_cache();
}
public function get_template_path() {
return $this->plugin_dir_path .'template';
}
// Activate plugin and update default option
public function activate() {
$dir = $this->upload_path.'/gravatar/';
// delete_option('nf_c_a_options');
if ( get_option( 'nf_c_a_options' ) == false ) {
$default_options = array('active' => 1,
'ttl_day' => 10,
'ttl_hour' => 0,
'ttl_min' => 0
);
update_option( 'nf_c_a_options', array( $default_options ) );
}
}
// Deactivate plugin and clear cache
public function deactivate() {
$this->clear_cache();
}
// Notice in plugin options page
public function admin_help_notice() {
global $current_screen;
if ( $current_screen->base == 'settings_page_'. basename( __FILE__,'.php' ) ) {
return true;
}
}
// convert ttl option to second
private function cache_to_second(){
$cache_time = get_option( 'nf_c_a_options' );
$cache_time = array_reverse( $cache_time[0] );
$action = array();
foreach ( $cache_time as $key => $value ) {
if ( $key == 'active' )
continue;
switch ( $key ) {
case 'ttl_min':
$cache_second = $value != 0 ? $value*60 : '';
break;
case 'ttl_hour':
$cache_second = $value != 0 ? ( $value*60*60 ) + $cache_second : $cache_second;
break;
case 'ttl_day':
$cache_second = $value != 0 ? ( $value*60*60*24 ) + $cache_second : $cache_second;
break;
}
}
if ( ! $cache_second ) {
$cache_second = 864000;// TTL of cache in seconds (10 days)
}
return $cache_second;
}
// The main functional
public function get_cached_avatar( $source, $id_or_email, $size, $default, $alt ) {
if ( !is_writable( $this->upload_path.'/gravatar/' ) || is_admin() ) {
return $source;
}
$time = $this->cache_to_second();
preg_match('/d=([^&]*)/', $source, $d_tmp);
$g_url_default_sorce = isset($d_tmp[1]) ? $d_tmp[1] : false;
preg_match('/forcedefault=([^&]*)/', $source, $d_tmp);
$g_forcedefault = isset($d_tmp[1]) ? $d_tmp[1] : false;
preg_match('/avatar\/([a-z0-9]+)\?s=(\d+)/', $source, $tmp);
$garvatar_id = $tmp[1];
$file_name = md5($garvatar_id.$g_url_default_sorce);
$g_path = $this->upload_path.'/gravatar/'.$file_name.'-s'.$size.'.jpg';
//* $g_path_default = $this->upload_path.'/gravatar/default'.'-s'.$size.'.jpg';
$g_url = $this->upload_url.'/gravatar/'.$file_name.'-s'.$size.'.jpg';
//* $g_url_default = $this->upload_url.'/gravatar/'.'default'.'-s'.$size.'.jpg';
// Check cache
static $nf_avatars_cache = null;
if ($nf_avatars_cache === null) $nf_avatars_cache = get_option('nf_avatars_cache');
if (! is_array($nf_avatars_cache)) $nf_avatars_cache = array();
if (isset($nf_avatars_cache[$garvatar_id][$size])) {
$g_url = $nf_avatars_cache[$garvatar_id][$size]['url'];
$g_path = $nf_avatars_cache[$garvatar_id][$size]['path'];
}
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
$curl_url = 'https://www.gravatar.com/avatar/'.$garvatar_id.'?s='.$size.'&r=G&d='.$g_url_default_sorce;
$ch = curl_init($curl_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
// Checking for redirect
$header_array = array();
preg_match('/^Location\: (.*)$/m', $header, $header_array);
$redirect_url = isset($header_array[1]) ? $header_array[1] : false;
if ($redirect_url) {
$g_url = $g_url_default;
$g_path = $g_path_default;
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
copy($redirect_url, $g_path);
}
}
else {
// Check mime type
$mime_str = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
$mime_array = array();
preg_match( '#/([a-z]*)#i', $mime_str, $mime_array );
if (isset($mime_array[1])) {
// Write cache to file
$fp = fopen( $g_path, "wb" );
$body = substr( $response, $header_size );
fwrite( $fp, $body );
fclose( $fp );
}
}
curl_close($ch);
$nf_avatars_cache[$garvatar_id][$size]['url'] = $g_url;
$nf_avatars_cache[$garvatar_id][$size]['path'] = $g_path;
update_option( 'nf_avatars_cache', $nf_avatars_cache );
}
return '<img alt = "'.$alt.'" src=\''.$g_url.'\' class="avatar avatar-'.$size.'" width="'.$size.'" height="'.$size.'" />';
}
// Create plugin option settings menu
public function add_admin_menu() {
// settings menu page
add_options_page( 'Cached Avatar ', $this->plugin_name, 'manage_options', basename( __FILE__ ), array( $this,'view_options_page' ) );
}
// Create page option
public function view_options_page() {
// update options
if ( isset( $_POST['nf_c_a_submit'] ) ) {
$update_val_options = $_POST['nf_c_a_options'];
foreach ( $update_val_options as $option => $value ) {
$update_val_options[$option] = abs( intval( $value ) );
}
if( $update_val_options['ttl_min'] == 0 && $update_val_options['ttl_hour'] == 0 && $update_val_options['ttl_day'] == 0 ) {
$update_val_options['ttl_day'] = 10;
}
update_option( 'nf_c_a_options', array( $update_val_options ) );
}
$options = get_option( 'nf_c_a_options' );
include( $this->get_template_path() .'/main-options-page.php');
}
private function clear_cache() {
$dir = $this->upload_path.'/gravatar/';
$no_permision_to_delete = false;
// Open directory
if ( is_dir( $dir ) ) {
if ( $opendir = opendir( $dir ) ) {
$count = 0;
while ( ( $file = readdir( $opendir ) ) !== false ) {
if ( filetype( $dir . $file ) == 'file' ) {
if ( #unlink( $dir . $file ) ) {
$count++;
}else {
$no_permision_to_delete = true;
}
}
}
if ( $no_permision_to_delete ) {
NFGC_Messages::add_message( 'error','Unable to clear the cache' );
}else{
update_option('nf_avatars_cache', array() );
NFGC_Messages::add_message( 'info','The cache is cleared!' );
NFGC_Messages::add_message( 'info','Removed '.$count.' files' );
}
closedir( $opendir );
}
}
}
// return count and size
public function get_cache_info() {
$dir = $this->upload_path.'/gravatar/';
$skip = array('.','..');
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
if ( is_dir( $dir ) ) {
$file_list = scandir( $dir );
// delete . and ..
foreach ( $skip as $value ) {
unset( $file_list[ array_search( $value, $file_list ) ] );
}
// sum files size
foreach ( $file_list as $file ) {
$size = filesize( $dir . $file );
$all_size = $all_size + $size;
}
}
$readable_form = #round( $all_size / pow( 1024, ( $i = floor( log( $all_size, 1024) ) ) ), 2 ) . ' ' . $unit[$i];
return array( 'amount' => count( $file_list ) , 'used_space' => $readable_form );
}
private function init() {
return false;
wp_enqueue_script( 'nfgc-main-script', plugins_url( '/js/main.js', __FILE__ ), array('jquery') );
wp_enqueue_style( 'nfgc-main-style', plugins_url( '/css/style.css', __FILE__ ) );
}
}// Class
global $nfgc;
$nfgc = new NFGC_Gravatar_Cache();
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script( 'nfgc-main-script', plugins_url( '/js/main.js', __FILE__ ), array('jquery') );
wp_enqueue_style( 'nfgc-main-style', plugins_url( '/css/style.css', __FILE__ ) );
});
`
Try this..
Use file_exists
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
if (file_exists($redirect_url)) {
$g_url = $g_url_default;
$g_path = $g_path_default;
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
copy($redirect_url, $g_path);
}
}
http://php.net/manual/en/function.file-exists.php

Include php file randomly

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 ] );

Categories