Autoload files when use require function - php

There's a magic function to autoload classes (__autoload), I want to know if there a way to load a file without a class.
Something like this:
require ('example_file'); // Trigger __autoloadfiles function
function __autoloadfiles($filename)
{
$files = array(
ROOT . DS . 'library' . DS . $filename. '.php',
ROOT . DS . 'application' . DS . $filename . '.php',
ROOT . DS . 'application/otherfolder' . DS . $filename. '.php'
);
$file_exists = FALSE;
foreach($files as $file) {
if( file_exists( $file ) ) {
require_once $file;
$file_exists = TRUE;
break;
}
}
if(!$file_exists)
die("File not found.");
}

You can define own function for requiring:
function require_file($file) {
// your code
}
and then call it
require_file('file');
I guess that there is no way to overload require function.

Related

Directory structures is messed up while unziping a zip file on Linux while zip file created in windows using php zip archive

Directory structures is messed up while unziping on Linux while zip file created in windows using php ZIPArchive
Zip creation on Windows ---> Unzip on Windows --> No isuses
Zip creation on Linux ---> Unzip on Linux --> No isuses
Zip creation on Windows ---> Unzip on Linux ---> Files are not unziping to right directories
Structure of folder to be zipped
b2c
--> data
d.xml
---> metatada
m.xml
Create a zip using code below on windows platform. Now unzip on Linux . Here is the structure, instead of putting d.xml under b2c\data, it is creating a file data\d.xml.
b2c
data\d.xml
metadata\m.xml
Source code
<?php
define('DS', DIRECTORY_SEPARATOR);
/*
$folder_to_zip = 'c:'. DS .'temp'. DS . 'b2c';
$zip_file = 'c:' . DS . 'temp' .DS . 'b2c'. DS . 'b2c.zip';
create_zip($folder_to_zip, $zip_file);
$folder_to_unzip = 'c:' . DS . 'temp1';
$src_zip_file = 'c:'. DS . 'temp' . DS . 'b2c' . DS . 'b2c.zip';
unzip_file($folder_to_unzip,$src_zip_file);
*/
$folder_to_zip = DS. 'home' . DS . 'bitnami' . DS . 'temp' . DS . 'b2c';
$zip_file = DS. 'home' . DS . 'bitnami' . DS . 'temp' . DS . 'b2c'. DS . 'b2c.zip';
create_zip($folder_to_zip, $zip_file);
$folder_to_unzip = DS. 'home' . DS . 'bitnami' . DS . 'temp1' . DS . 'b2c';
$src_zip_file = DS. 'home' . DS . 'bitnami' . DS . 'temp' . DS . 'b2c'. DS . 'b2c.zip';
unzip_file($folder_to_unzip,$src_zip_file);
function create_zip($folder_to_zip, $zip_file) {
$rootPath = realpath($folder_to_zip);
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator /** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
}
function unzip_file($folder_to_unzip,$src_zip_file) {
$zip = new ZipArchive;
$res = $zip->open($src_zip_file);
if ($res === TRUE) {
$zip->extractTo($folder_to_unzip);
$zip->close();
return TRUE ;
} else {
return FALSE ;
}
}

Cake PHP shows Internal Server Error 500

Following CakePHP code is in my index.php file. When it runs on the server, it shows
internal server error 500
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
if (!defined('ROOT')) {
define('ROOT', dirname(dirname(dirname(__FILE__))));
}
if (!defined('APP_DIR')) {
define('APP_DIR', basename(dirname(dirname(__FILE__))));
}
$vendorPath = ROOT . DS . APP_DIR . DS . 'Vendor' . DS . 'cakephp' . DS . 'cakephp' . DS . 'lib';
$dispatcher = 'Cake' . DS . 'Console' . DS . 'ShellDispatcher.php';
if (!defined('CAKE_CORE_INCLUDE_PATH') && file_exists($vendorPath . DS . $dispatcher)) {
define('CAKE_CORE_INCLUDE_PATH', $vendorPath);
}
if (!defined('WEBROOT_DIR')) {
define('WEBROOT_DIR', basename(dirname(__FILE__)));
}
if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (php_sapi_name() === 'cli-server') {
if ($_SERVER['REQUEST_URI'] !== '/' && file_exists(WWW_ROOT . $_SERVER['PHP_SELF'])) {
return false;
}
$_SERVER['PHP_SELF'] = '/' . basename(__FILE__);
}
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
if (function_exists('ini_set')) {
ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path'));
}
if (!include 'Cake' . DS . 'bootstrap.php') {
$failed = true;
}
} else {
if (!include CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php') {
$failed = true;
}
}
if (!empty($failed)) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
}
App::uses('Dispatcher', 'Routing');
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(
new CakeRequest(),
new CakeResponse()
);
Go to your app/Config/core.php and change
Configure::write('debug',0);
to
Configure::write('debug',2);
Visit the same page you will get the detail about the error

File exists always returning false

My image directory is \webroot\files\thumbs
I am trying to add file_exists condition. For that I tried bellow code
$file = WWW_ROOT .'files' . DS . 'thumbs' . DS .'_'.$password->collection_id.'jpg';
$file_exists = file_exists($file);
It's always returning zero.
If I echo $file it's giving me output like this
c:\xampp\htdocs\myproject\files\thumbs\_61.jpg
You're missing the . before the extension. Update your $file definition as follows:
$file = WWW_ROOT .'files' . DS . 'thumbs' . DS .'_'.$password->collection_id.'.jpg';
// This was missing ---^
$file_exists = file_exists($file);

autoloading classes in subfolders

In my PHP project all of the class files are contained in a folder called 'classes'. There is one file per class and as more and more functionality is added to the application the classes folder is growing larger and less organized. Right now this code, in an initialization file, autoloads classes for the pages in the app:
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
If subfolders were to be added to the existing 'classes' folder and the class files organized within these subfolders, is there a way to modify the the autoload code so it still works?
For example - assume the subfolders within the classes folder looks like this:
DB
login
cart
catalog
I recoomend that you look at PSR standards at : http://www.php-fig.org
Also this tutorial will help you build and understand one for yourself.
http://www.sitepoint.com/autoloading-and-the-psr-0-standard/
Snippet that takes all subfolder :
function __autoload($className) {
$extensions = array(".php", ".class.php", ".inc");
$paths = explode(PATH_SEPARATOR, get_include_path());
$className = str_replace("_" , DIRECTORY_SEPARATOR, $className);
foreach ($paths as $path) {
$filename = $path . DIRECTORY_SEPARATOR . $className;
foreach ($extensions as $ext) {
if (is_readable($filename . $ext)) {
require_once $filename . $ext;
break;
}
}
}
}
My solution
function load($class, $paste){
$dir = DOCROOT . "\\" . $paste;
foreach ( scandir( $dir ) as $file ) {
if ( substr( $file, 0, 2 ) !== '._' && preg_match( "/.php$/i" , $file ) ){
require $dir . "\\" . $file;
}else{
if($file != '.' && $file != '..'){
load($class, $paste . "\\" . $file);
}
}
}
}
function autoloadsystem($class){
load($class, 'core');
load($class, 'libs');
}
spl_autoload_register("autoloadsystem");
Root
|-..
|-src //class Directory
|--src/database
|--src/Database.php // Database Class
|--src/login
|--src/Login.php // Login Class
|-app //Application Directory
|--app/index.php
|-index.php
-----------------------------------
Code Of index.php in app folder to Autoload All the Classes from The src folder.
spl_autoload_register(function($class){
$BaseDIR='../src';
$listDir=scandir(realpath($BaseDIR));
if (isset($listDir) && !empty($listDir))
{
foreach ($listDir as $listDirkey => $subDir)
{
$file = $BaseDIR.DIRECTORY_SEPARATOR.$subDir.DIRECTORY_SEPARATOR.$class.'.php';
if (file_exists($file))
{
require $file;
}
}
}});
Code Of index.php in root folder to Autoload All the Classes from The src folder.
change the variable $BaseDIR,
$BaseDIR='src';
autoload.php
<?php
function __autoload ($className) {
$extensions = array(".php");
$folders = array('', 'model');
foreach ($folders as $folder) {
foreach ($extensions as $extension) {
if($folder == ''){
$path = $folder . $className . $extension;
}else{
$path = $folder . DIRECTORY_SEPARATOR . $className . $extension;
}
if (is_readable($path)) {
include_once($path);
}
}
}
}
?>
index.php
include('autoload.php');
Here is the one I'm using
spl_autoload_register(function ($class_name) {
//Get all sub directories
$directories = glob( __DIR__ . '/api/v4/core/*' , GLOB_ONLYDIR);
//Find the class in each directory and then stop
foreach ($directories as $directory) {
$filename = $directory . '/' . $class_name . '.php';
if (is_readable($filename)) {
require_once $filename;
break;
}
}
});
Load files from "inc" subfolder using "glob"
/**
* File autoloader
*/
function load_file( $file_name ) {
/**
* The folder to where we start looking for files
*/
$base_folder = __DIR__ . DIRECTORY_SEPARATOR ."inc". DIRECTORY_SEPARATOR . "*";
/**
* Get all sub directories from the base folder
*/
$directories = glob( $base_folder, GLOB_ONLYDIR );
/**
* look for the specific file
*/
foreach ( $directories as $key => $directory ) {
$file = $directory . DIRECTORY_SEPARATOR . $file_name . ".php";
/**
* Replace _ by \ or / may differ from OS
*/
$file = str_replace( '_', DIRECTORY_SEPARATOR, $file );
/**
* Check for file if its readable
*/
if ( is_readable( $file ) ) {
require_once $file;
break;
}
}
}
/**
* Autoload file using PHP spl_autoload_register
* #param $callbak function
*/
spl_autoload_register( 'load_file' );

Autoload class issue

Trying to autoload classes from <root>/incl/classes folder.
The problem is, when I call some class for ex. ip like that
$ip= new ip();
$ip=$ip->get();
PHP gives error message Notice: Undefined variable: path . But in fact file already exists
I'm declaring all various paths at the top of page.
define("ds", DIRECTORY_SEPARATOR);
$path = array();
$path['root'] = $_SERVER['DOCUMENT_ROOT'];
$path['common'] = $path['root'] . ds . "common";
$path['design'] = $path['root'] . ds . "design";
$path['contents'] = $path['root'] . ds . "contents";
$path['content_images'] = $path['root'] . ds . "content" . ds . "images";
$path['design_images'] = $path['root'] . ds . "design" . ds . "images";
$path['blocks'] = $path['contents'] . ds . "blocks";
$path['includes'] = $path['root'] . ds . "incl";
$path['pages'] = $path['contents'] . ds . "pages";
$path['classes'] = $path['includes'] . ds . "classes";
$files = glob("common" . ds . "*.php");
array_unshift($files, $path['common'] . ds . "settings.php", $path['common'] . ds . "db.php");
foreach ($files as $filename)
require_once $filename;
//Auto loading classes
function __autoload($class_name) {
if (file_exists($path['classes'] . ds . $class_name . '.php')) {
require_once($path['classes']. ds . $class_name . '.php');
} else {
die($path['classes'] . ds . $class_name . '.php');
}
}
For testing purposes added die($path['classes'] . ds . $class_name . '.php'); line. It outputs \ip.php. I wonder, why it doesn't echo $path['classes'] even if I declared it before ?
It's a scoping issue. Your $path variable doesn't exist in your autoload function. It is a global variable, and you need to explicitly "invite" it:
function __autoload($class_name) {
global $path;
You should actually have gotten a notice about this.

Categories