PHP Autoload ignorecase - php

Is there any way to call require_once with some "case insensitive flag" ?
In windows it's okay, but linux is case sensitive. Is there any way to override ?
Thanks

Sure, load
strtolower($className . ".php")
and name your files in lowercase.
Regardless of how you try to load your files, only the lowercase version will ever be loaded.

Just include some where else in you header.php or some other common file.,
<?php
$filename = basename($_SERVER['SCRIPT_FILENAME']);
$request = basename($_SERVER['SCRIPT_NAME']);
if($filename != $request)
die('Case of filename and request do not match!');
?>
I think this may help you resolve your problem. also refer the following location https://superuser.com/questions/431342/linux-both-case-sensitive-and-case-insensitive-and-always-inconvenient

You can use this every time you are loading you auto load the appropriate classes. yu have to change the directories depends on you project. you can you the echo or print_r to print what classes are loaded every time when you are calling something. also all you class names must ot have the same format for example, className.class.php e.g Dashboard.class.php, Category.class.php. you can use
ucwords to make the first letter capital.
function __autoload($className)
{
if (file_exists(__DIR__ . '/../library/' . strtolower($className) . '.class.php'))
{
require_once(__DIR__ . '/../library/' . strtolower($className) . '.class.php');
}
else if (file_exists(__DIR__ . '/../application/controllers/' . strtolower($className) . '.php'))
{
require_once(__DIR__ . '/../application/controllers/' . strtolower($className) . '.php');
}
else if (file_exists(__DIR__ . '/../application/models/' . strtolower($className) . '.php'))
{
require_once(__DIR__ . '/../application/models/' . strtolower($className) . '.php');
}
}

Related

spl_autoload_register() in different directories

I have a file that auto loads each of my classes.
This is what it contains:
spl_autoload_register(function($class){
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
require_once 'functions/hash.php';
But when I require_once this file from another php file that is inside my ajax folder, it will try looking for the classes, the function will look from my classes with the path: main_folder/ajax/classes instead of just main_folder/classes.
Does anyone know how to fix this?
FIX:
spl_autoload_register(function($class){
if (file_exists('classes/' . $class . '.php')) {
require_once 'classes/' . $class . '.php';
}
elseif (file_exists('../classes/' . $class . '.php')) {
require_once '../classes/' . $class . '.php';
}
elseif (file_exists('../../classes/' . $class . '.php')) {
require_once '../../classes/' . $class . '.php';
}
You should simple use this function just once - in the main file (usually index.php) and not in another files.
However if it's not possible (but I don't see any reason when could it be not possible) you can change it for example that way:
spl_autoload_register(function($class){
if (file_exists('classes/' . $class . '.php')) {
require_once 'classes/' . $class . '.php';
}
elseif (file_exists( $class . '.php')) {
require_once $class . '.php';
}
});
Here is a proper way, It should universally work.
EDIT: Make sure to specify levels on dirname in order to find the correct path.
spl_autoload_register(function ($classname) {
$file_realpath = dirname(realpath(__FILE__), levels: 1 /* Change that? */) . DIRECTORY_SEPARATOR . dirname($classname);
$classpath = sprintf('%s' . DIRECTORY_SEPARATOR . '%s.php', $file_realpath, basename($classname, '.{php,PHP}'));
if (file_exists($classpath)) {
echo "Loading <b>$classpath</b>...<br>";
require($classpath);
}
});
You need to know the absolute path to the classes directory, then just use a full qualified path to get there.
Make sure your document root is correctly configured with your http server. Furthermore this is usually solved by routing all requests to index.php and deriving the base path (document root) from there. Here is your code modified:
spl_autoload_register(function($class) {
$resolved = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . $class . '.php';
if(file_exists($resolved)) {
require_once $resolved;
} else {
// make it known to your that a class failed to load somehow
return;
}
})
Here is another implementation that I use for simple projects

Why isn't wordnik's php api loading the required classes?

I'm getting the following error with wordnik's php api
Fatal error: Class 'Example' not found in Swagger.php on line 212
I've edited Swagger.php to get it to work, below is the original function
function swagger_autoloader($className) {
$currentDir = substr(__FILE__, 0, strrpos(__FILE__, '/'));
if (file_exists($currentDir . '/' . $className . '.php')) {
include $currentDir . '/' . $className . '.php';
} elseif (file_exists($currentDir . '/models/' . $className . '.php')) {
include $currentDir . '/models/' . $className . '.php';
}
}
The working code I changed to is
function swagger_autoloader($className)
{
include $currentDir . '/models/' . $className . '.php';
}
MORE INFO
My file structure is as follows.
WORDNIK (contains start.php)>>>WORDNIK (contains Swagger.php)>>MODELS (contains Example.php)
I'm using wampserver 2.2 with php 5.4.3
UPDATE/EDIT
Using the following code
function swagger_autoloader($className) {
echo "dirname(__FILE__)= ",dirname(__FILE__);
$currentDir = substr(__FILE__, 0, strrpos(__FILE__, '/'));
echo "currentDir=".$currentDir."</br>";
echo "className=".$className."</br>";
echo "__FILE__=",__FILE__."<br/>";
die();
I get the results
dirname(__FILE__)=D:\wamp\www\wordnik\wordnik
currentDir=
className=Example
__FILE__=D:\wamp\www\wordnik\wordnik\Swagger.php
As suggested by vcampitelli, using either __DIR__ or dirname(__FILE__) works.
MY QUESTION
Why doesn't the original function work?
UNIMPORTANT INFO
For people struggling through the examples, here is my start.php file
<?php
require('./wordnik/Swagger.php');
require('./wordnik/WordApi.php');
require('./wordnik/AccountApi.php');
require('./wordnik/WordsApi.php');
require('./wordnik/WordListApi.php');
require('./wordnik/WordListsApi.php');
$myAPIKey = 'replace_this_with_your_real_api';
$client = new APIClient($myAPIKey, 'http://api.wordnik.com/v4');
$wordApi = new WordApi($client);
$example = $wordApi->getTopExample('irony');
print $example->text;
?>
What does $currentDir return? Have you tried using __DIR__ or dirname(__FILE__) (they are the same) instead of that substr?
If you are using the second example just as you posted (without declaring $currentDir), so that is the problem at your original code: $currentDir is not returning the right folder!
With the original code, which file is being included? Because, actually, I think no one is! Use echo inside those if statements to check that!
The original function doesn't work because it is looking for the position of a UNIX-style forward slash '/', whereas you are on Windows and have backslashes '\'. That's a bug! I'll fix the lib to use dirname(FILE) as you do. Thanks for pointing out the error.

How to use __autoload for different folders?

I am trying to autoload classes that are in different folders. Is that possible?
function __autoload($class){
require $class.'.php';
require 'libs/'.$class.'.php';
//this won't work.
}
I want to autoload classes that are either in libs folder or on the root. Any thoughts? Thanks a lot.
First, I suggest you look into spl_autoload_register, which is superior for doing this.
Second, you should use is_file to test whether the file exists, then try to load it. If you require a file that doesn't exist, your script will halt.
spl_autoload_register(function($class) {
if (is_file($class . '.php')) {
require $class . '.php';
} elseif (is_file('libs/' . $class . '.php')) {
require 'libs/' . $class . '.php';
}
});
If you have multiple folders where the file could be, you could do something like this:
spl_autoload_register(function($class) {
$folders = array ('.', 'libs', 'somewhere');
foreach ($folders as $folder) {
if (is_file($folder . '/' . $class . '.php')) {
require $folder . '/' . $class . '.php';
}
if (class_exists($class)) break;
}
});

Zend Framework PHP -> realpath()

im trying to create a Zend Framework custom Provider and here:
if($module == 'default'){
$modelsPath = dirname(__FILE__) . '/../application/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else
if(!$module == ''){
$modelsPath = dirname(__FILE__) . '/../application/' . $module . '/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else {
die('Please enter a module!');
}
when i im trying to create a path to the file and when its default module everything is ok, but when for ex. module is other word no matter what the realpath returns false?! where is the error?
try using the APPLICATION_PATH constant.
if($module == 'default'){
$modelsPath = APPLICATION_PATH . '/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else
if(!$module == ''){
$modelsPath = APPLICATION_PATH . '/' . $module . '/models';
$filePath = realpath($modelsPath) . '/' . $name . '.php';
} else {
die('Please enter a module!');
}
Taken out of the php manual:
realpath() returns FALSE on failure, e.g. if the file does not exist.
Note:
The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.
So the problem most probably is with folder permission or the path simply is wrong!
Double check that the paths exist by simple echoing $filePath. If this checks out to be okay then ensure that the 'user' (apache, www-data, for example) have enough privileges. If you are not sure who your server is operating as you can simply debug by echoing whoami

Strange behaviour for spl_autoload on phpfog

I'm just trying to build my first app on PHP Fog but there's a piece of code that doesn't run properly - works fine on localhost and other regular hosts though.
I use a modified version of TinyMVC, this is the code responsible for setting up autoloading:
/* Set include_path for spl_autoload */
set_include_path(get_include_path()
. PATH_SEPARATOR . FRAMEWORK_BASEDIR . 'core' . DS
. PATH_SEPARATOR . FRAMEWORK_BASEDIR . 'libraries' . DS
. PATH_SEPARATOR . FRAMEWORK_APPLICATION . DS . 'controllers' . DS
. PATH_SEPARATOR . FRAMEWORK_APPLICATION . DS . 'models' . DS
);
/* File extensions to include */
spl_autoload_extensions('.php,.inc');
/* Setup __autoload */
$spl_funcs = spl_autoload_functions();
if($spl_funcs === false)
spl_autoload_register();
elseif(!in_array('spl_autoload',$spl_funcs))
spl_autoload_register('spl_autoload');
Basically, it fails at the first class it should load, which is located in "FRAMEWORK_BASEDIR . 'core' . DS". The class filename is "framework_controller.php" and class name is "Framework_Controller" (tried lowercase as well). If I include the class manually it works but fails with autoload.
Here's the error message that I get:
Fatal error: spl_autoload(): Class Framework_Controller could not be loaded in /var/fog/apps/app7396/claudiu.phpfogapp.com/application/controllers/home.php on line 12
Any ideas as to what could the problem be?
I managed to sort it out:
function framework_autoload($className, $extList='.inc,.php') {
$autoload_paths = array (
FRAMEWORK_BASEDIR . 'core' . DS,
FRAMEWORK_BASEDIR . 'libraries' . DS,
FRAMEWORK_APPLICATION . DS . 'controllers' . DS,
FRAMEWORK_APPLICATION . DS . 'models' . DS
);
$ext = explode(',',$extList);
foreach($ext as $x) {
foreach ($autoload_paths as $v) {
$fname = $v . strtolower($className).$x;
if(#file_exists($fname)) {
require_once($fname);
return true;
}
}
}
return false;
}
spl_autoload_register('framework_autoload');
Thanks to another question here on StackOverflow: spl_autoload problem

Categories