PHP dynamic require - php

The main issue it's still the same:
This is my proyect
/
| index.php
|-test1
| test.php
The test.php
<?php
echo $variable;
?>
The index.php
<?php
$variable = "<br>index";
echo 'test<br>';
$full_path = dirname(__FILE__)."/test1";
$adm_extension = array( "php");
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
require $item_path;
}
}
}
}
}
And it's works like a charm, the output is:
test
index
If i want to encapsulate this functionality in a function like this:
index1.php
$variable = "<br>index";
echo 'test<br>';
$full_path = dirname(__FILE__)."/test1";
$adm_extension = array( "php" );
function rTest($full_path, $adm_extension){
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
require $item_path;
}
}
}
}
}
}
rTest($full_path, $adm_extension);
I got this:
( ! ) Notice: Undefined variable: variable in C:\wamp\www\sandbox\test1\test.php on line 3
Any clue??

your script probably, when going through files, opens test.php before index1.php so $variable isn't defined yet
test it:
function rTest($full_path, $adm_extension){
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
echo $item_path.'<br />';
require $item_path;
}
}
}
}
}
}

Ok, a friend help me to solve it out.
It's was a really dumb error. The problem was when I made the require, it was made in the function scope.
For my solution I do something like this:
function rTest($full_path, $adm_extension){
$paths = array();
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
$paths[] = $item_path;
}
}
}
}
}
return $paths;
}
foreach(rTest($full_path, $adm_extension) as $path){
require $path;
}

Related

Scan multiple dirs from array

I have the next code but i need scan multiple dir on array.
public static function scanFiles($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if($listDirs){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if($listFiles){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
return $arrayItems;
}
Your use is: scanFiles('path/to/folder')
But I need the path to be an array, example: scanFiles(array('path/to/folder1', 'path/to/folder2')).
Some one help...?
Thank you in advance and sorry for my bad english.
you can change the function like this, just adding foreach with the code block that you have for scanning directory
public static function scanFiles($directories, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
foreach($directories as $directory) {
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if ($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if ($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if ($listDirs) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if ($listFiles) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
}
return $arrayItems;
}

PHP, read line by line, not working

I have this code. The idea with it, is that i reads a big(very big: 300mb) JSON file, line by line and set the JSON data into an SQL table. But the same line of JSON data gets inserted more than once, and after the PHP script has been through all lines, it just starts over.
There is 200268 objects in the JSON file, seperated in lines
Here is my code:
example.php:
<?php
/**
* Licensed under Creative Commons 3.0 Attribution
* Copyright Adam Wulf 2013
*/
include("config-sample.php");
include("include.classloader.php");
$classLoader->addToClasspath(ROOT);
$mysql = new MySQLConn(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASS);
$db = new JSONtoMYSQL($mysql);
$handle = fopen("programoversigter.json", "r");
if ($handle) {
while (($linne = fgets($handle)) !== false) {
$db->save(json_decode($linne)->_source, "igen");
print($iasd . " ");
$iasd = $iasd++;
}
fclose($handle);
} else {
echo "assscsad";
}
die();
?>
include.classloader.php:
<?php
/**
* Licensed under Creative Commons 3.0 Attribution
* Copyright Adam Wulf 2013
*/
class ClassLoader{
protected $classpath;
public function __construct(){
$this->classpath = array();
}
public function addToClasspath($dir){
if(is_dir($dir)){
$this->classpath[] = $dir;
}else{
throw new Exception("cannot find directory: $dir");
}
}
public function load($classname){
$ok = false;
for($i=0;$i<count($this->classpath);$i++){
$path = $this->classpath[$i];
/* echo "load recur \"" . $path . "\";//<br>\n"; */
$ok = $ok || $this->load_recursive($path, $classname);
}
return $ok;
}
protected function load_recursive($classpath, $classname){
$theList = array();
$ret = false;
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$ret = $ret || $this->load_recursive($classpath . $file . "/", $classname);
}else{
if($file == "class.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}else
if($file == "class.Boolean.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}else
if($file == "interface.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}
}
}
}
closedir($handle);
unset($handle);
}
return $ret;
}
public function loadTestFiles(GroupTest $g){
foreach($this->classpath as $c){
$this->loadTestFilesHelper($g, $c);
}
}
protected function loadTestFilesHelper(GroupTest $g, $classpath){
$theList = array();
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$this->loadTestFilesHelper($g, $classpath . $file . "/");
}else{
if(strpos($file, "test.class.") === 0 &&
strpos($file, ".php") == strlen($file)-4){
$g->addTestFile($classpath . $file);
}
}
}
}
closedir($handle);
unset($handle);
}
}
}
class ClassLoaderToString extends ClassLoader{
public function __construct(){
parent::__construct();
}
protected function load_recursive($classpath, $classname){
$theList = array();
$ret = false;
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$this->load_recursive($classpath . $file . "/", $classname);
}else{
if($file == "class.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}else
if($file == "class.Boolean.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}else
if($file == "interface.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}
}
}
}
closedir($handle);
unset($handle);
}
return $ret;
}
protected function printClass($classpath, $file){
if(strpos($classpath, ROOT) === 0){
$classpath = substr($classpath, strlen(ROOT));
echo "include_once(ROOT . \"" . $classpath . $file . "\");\n";
}else{
echo "include_once(\"" . $classpath . $file . "\");\n";
}
}
}
function milestone_autoload($classname){
global $classLoader;
// global $control;
// $str = "classname: ";
// $str .= $classname;
// $str .= "\n";
// if(is_object($control) && !is_int(stripos($classname, "mysql"))){
// $control->getModel()->getLogger()->log($control->getModel(), ALogger::$HIGH, $str);
// }
try{
$ok = $classLoader->load($classname);
// $str .= ":" . $ok;
// if(is_object($control) && !is_int(stripos($classname, "mysql"))){
// $control->getModel()->getLogger()->log($control->getModel(), ALogger::$HIGH, $str);
// }
}catch(Exception $e){
$model->getLogger()->log($model, ALogger::$HIGH, print_r($e, true));
}
}
spl_autoload_register('milestone_autoload');
$classLoader = new ClassLoader();
?>

Strict Standards: "Only variables should be passed by reference"

In the php function below I have on line 31 the error "Strict Standards: Only variables should be passed by reference"
As I read the answers on the forum I must change the explode(..). But I don’t have any idea how..
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'png'))
{
if (substr($directory, -1) == 'uploads/') {
$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) // Line 31
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
According to the PHP Manual for end:
This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.
Parameter should be sent as an array variable only.
ToDo:
Break this statement inside if:
is_file($path) && in_array(end(explode('.', end(explode('/', $path)))), $exts)
to something like this:
$path1 = explode('/', $path);
$path2 = end($path1);
$path3 = explode('.', $path1);
$path4 = end($path3);
is_file($path) && in_array($path4, $exts)
Alternatively,
Since you are getting extension from the path, you can use pathinfo:
pathinfo($path)['extension']
You can try this code:
<?php
<?php
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'png'))
{
if (substr($directory, -1) == 'uploads/') {
$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);
}
$path_info = pathinfo($path);
$ext = strtolower($path_info['extension']);
if (is_file($path) && in_array($ext, $exts)) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
try to separate your code in the if statement like this, this should work :
// other code
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
$explode_1 = explode('/', $path);
$explode_2 = explode('.', end($explode_1));
if (is_file($path) && in_array(end($explode_2), $exts)) {
// the rest of the code

opening two folders and displaying images php

I've got the problem of trying to display two albums of photos from a db using php. Currently the following code works but for just one album. Basically I need it to display photos from 'mount-everest-part-2' aswell.
<?php
$path = "images/galleries/";
$album = 'mount-everest-part-1';
if ($handle = opendir($path.$album.'/thumbs/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$files[] = $file;
}
}
closedir($handle);
}
asort($files);
foreach($files as $file) {
echo '<li><img src="../' . $path . $album . '/thumbs/' . $file . '" /></li>';
}
?>
How can I use this code to open two files and spit the files out using the same foreach loop?
This sounds like one of those things that OOP would suit nicely. Here's an example:
<?php
class Album_Picture_File {
private $fileName;
private $path;
private $album;
public function __construct($fileName, $path, $album) {
$this->fileName = $fileName;
$this->path = $path;
$this->album = $album;
}
private function getAlbumPath() {
return '../' . $this->path . $this->album;
}
public function getPicturePath() {
return $this->getAlbumPath() . '/images/' . $this->fileName;
}
public function getThumbnailPath() {
return $this->getAlbumPath() . '/thumbs/' . $this->fileName;
}
}
function fetchFiles($path, $album) {
$files = array();
if ($handle = opendir($path.$album.'/thumbs/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$fullPath = $path . $album . '/thumbs/' . $file;
$files[$fullPath] = new Album_Picture_File($file, $path, $album);
}
}
closedir($handle);
}
ksort($files); //sort after key (out file path)
return $files;
}
$files = array_merge(
fetchFiles('images/galleries/', 'mount-everest-part-1'),
fetchFiles('images/galleries/', 'mount-everest-part-2')
);
foreach($files as $file) {
echo '<li><img src="' . $file->getThumbnailPath() . '" /></li>';
}
?>
Note that instead of pushing $files with strings, we push it with Album_Picture_File objects.
Create a global array :
$all = array();
Then, make 2 loops and push the global array (create a function that reads the directory for example)
$files_dir_one = getFiles("your_dir");
$files_dir_two = getFiles("your_dir2");
$all = array_merge($files_dir_one, $files_dir_two);
function getFiles($directory) {
$files = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$files[] = $file;
}
}
closedir($handle);
}
//asort($files);
return $files;
}
And then, the last step : populate the view
How can I use this code to open two files and spit the files out using the same foreach loop?
Taking your question literally it works like this. First of all extract a function with the two input variables:
/**
* #param string $path
* #param string $album
*/
function list_images($path, $album) {
$files = [];
if ($handle = opendir($path . $album . '/thumbs/'))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._')
{
$files[] = $file;
}
}
closedir($handle);
}
asort($files);
foreach ($files as $file)
{
echo '<li><img src="../' . $path . $album . '/thumbs/' . $file . '" /></li>';
}
}
Then you can just iterate over your two albums and output both:
$path = "images/galleries/";
$albums = ['mount-everest-part-1', 'mount-everest-part-2'];
foreach ($albums as $album)
{
list_images($path, $album);
}

How to display all my files by date modified?

I'm new to PHP and i was just wondering if someone could help. I want my code to read files from a directory/sub directory and display all of them by the date they were modified! My code displays only one file, which is the one that I recently changed. So how do I list all the files? I hope this question makes some sense..
<?php
$last_mtimes = array();
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);
$lmtime = filemtime($dir . "/" . $file) ;
$last_mtimes[$lmtime] = $dir . "/" . $file;
}
}
}
krsort($last_mtimes);
closedir($dh);
return ($last_mtimes);
}
}
foreach (ListFiles('folder/folder/') as $key=>$file);
echo array_shift(ListFiles('folder/folder/'));
?>
There is an extra semi colon which makes the loop do nothing:
foreach (ListFiles('folder/folder/') as $key=>$file);
^ remove this

Categories