PHP define multiple constants in an array - php

Hi I am really bad and a total newbie to PHP. Need some help.
I am trying to define a few constants in my site:
Code 1
define('SITE_ROOT',$_SERVER['DOCUMENT_ROOT'] . '/');
// Check if CORE_PATH is already defined else define here
defined('CORE_PATH') or define('CORE_ROOT', SITE_ROOT . '/CORE');
define('INC_PATH', IAO_ROOT . '/inc/');
define('LAYOUTS_PATH', IAO_ROOT . 'layouts/');
define('BLOCKS_PATH', SECTIONS_PATH . 'blocks/');
define('STATIC_PATH', BLOCKS_PATH . 'static/');
Apart from the above example I have another 10-15 more constants to define. I want to know is it correct to define each constant in one line each or can I do something like below:
Code 2
define (
$constant = array (
'SITE_ROOT',
'CORE_PATH',
'INC_PATH' ,
'LAYOUTS_PATH',
'BLOCKS_PATH',
'STATIC_PATH'
),
$path = array(
$_SERVER['DOCUMENT_ROOT'] . '/',
SITE_ROOT . '/CORE',
CORE_PATH . '/inc',
CORE_PATH . '/layout',
CORE_PATH . '/blocks',
CORE_PATH . '/static'
)
);
define ( $constant, $path);
While Code 1 is working fine on my site, Code 2 is not working for me.
Kindly advise me what is the correct way.
UPDATE:
Updated this question as per #LasVegasCoder. does not work.
<?php
//Create array of paths --example from your path ***use right paths***;
$path = array(
'SITE_ROOT . ' => $_SERVER['DOCUMENT_ROOT'],
'CORE_PATH' => SITE_ROOT . '/core',
'INCLUDE_PATH' => SITE_ROOT . '/inc',
'LAYOUT_PATH' => SITE_ROOT . '/layout',
'BLOCK_PATH' => SITE_ROOT . '/blocks',
'STATIC_PATH' => SITE_ROOT . '/static'
);
//usage:
createPath( $path );
//Testiing
echo SITE_ROOT; ?></br>
<?php echo CORE_PATH; ?></br>
<?php echo INCLUDE_PATH; ?></br>
<?php echo LAYOUT_PATH; ?></br>
<?php echo BLOCK_PATH; ?></br>
<?php echo STATIC_PATH; ?></br>
<?php
function createPath( $path )
{
if( empty( $path ) )
{
die("Array of path required!");
}
foreach( $path as $constant => $path )
{
if(!defined( strtoupper($constant) ) )
{
define( strtoupper($constant), $path . '/');
}
}
}
Well still it does not work. Any idea and solutions?

Create Paths Dynamically
With this tiny function, you can create your paths as array of key => value, pass it to the function to create the paths for your application.
Create array of paths
using example in this question -- use right paths
$path = array(
'SITE_ROOT' => $_SERVER['DOCUMENT_ROOT'],
'CORE_PATH' => '/core',
'INCLUDE_PATH' => '/inc',
'LAYOUT_PATH' => '/layout',
'BLOCK_PATH' => '/blocks',
'STATIC_PATH' => '/static'
);
usage create paths using the function:
createPath( $path );
Testing path
echo CORE_PATH;
OUTPUT
/core/
Create a function to handle paths.
function createPath( $path )
{
if( empty( $path ) )
{
die("Array of path required!");
}
foreach( $path as $constant => $path )
{
if(!defined( strtoupper($constant) ) )
{
// define( strtoupper($constant), $path . '/');
define( strtoupper($constant), realpath( dirname( __FILE__) ) . $path . '/');
}
}
}
youpage.php
<?php
/**Create array of paths array of $constant to $path;
* i.e $path = array( 'THIS_CONSTANT' => '/this/path', 'WEB_ROOT' => '/path/to/webroot' );
* usage:
* `createPath( $path );`
* Test: `echo WEB_ROOT;` OUTPUT: '/path/to/webroot/'
*
* - How to Include another scripts:
* require_once CORE_PATH . 'Config.php';
* require_once INCLUDE_PATH . 'Database.php';
* require_once LAYOUT_PATH 'Header.php';
* require_once LAYOUT_PATH 'Body.php';
* require_once LAYOUT_PATH 'Footer.php';
*/
$path = array(
'SITE_ROOT' => $_SERVER['DOCUMENT_ROOT'],
'CORE_PATH' => '/core',
'INCLUDE_PATH' => '/inc',
'LAYOUT_PATH' => '/layout',
'BLOCK_PATH' => '/blocks',
'STATIC_PATH' => '/static'
);
//usage:
createPath( $path );
// Test. You can echo path, include | require e.g:
echo STATIC_PATH;
function createPath( $path )
{
if( empty( $path ) )
{
die("Array of path required!");
}
foreach( $path as $constant => $path )
{
if(!defined( strtoupper($constant) ) )
{
// define( strtoupper($constant), $path . '/');
define( strtoupper($constant), realpath( dirname( __FILE__) ) . $path . '/');
}
}
}
Test a DEMO Version online
Hope this helps!

Related

Have PHP Video Gallery include subfolders and display the videos?

I'm using a php video gallery from codeboxx in an attempt to see all the videos my security camera is uploading to my hosting. My camera makes many subfolders for dates and hours which I can't keep anticipating. What I've been trying to get is for this script to include subfolders:
<body>
<div id="vid-gallery"><?php
// (A) GET ALL VIDEO FILES FROM THE GALLERY FOLDER
$dir = __DIR__ . DIRECTORY_SEPARATOR . "gallery" . DIRECTORY_SEPARATOR;
$videos = glob($dir . "*.{webm,mp4,ogg}", GLOB_BRACE);
// (B) OUTPUT ALL VIDEOS
if (count($videos) > 0) { foreach ($videos as $vid) {
printf("<video src='gallery/%s'></video>", rawurlencode(basename($vid)));
}}
?></div>
</body>
I think I can get the first part to work in scanning 4 subfolders deep by me doing this:
$dir = __DIR__ . DIRECTORY_SEPARATOR . "{gallery,gallery/**,gallery/**/**,gallery/**/**/**,gallery/**/**/**/**}" . DIRECTORY_SEPARATOR;
Now I think this line is giving me a problem as I can't seem to get this src get videos in the subdirectories and wildcards don't seem to work:
printf("<video src='gallery/%s'></video>", rawurlencode(basename($vid)));
I've tried to look up how to do it and I've seen array/echo/recursive functions, but I don't know how to implement anything. I appreciate any help.
Untested but along the right lines - a combination of recursiveIterator & recursiveDirectoryIterator ought to be enough to list all the files - when combined further with pathinfo to find the file extension you can do away with the glob or preg_match
$dir=sprintf('%s/gallery',__DIR__);
$exts=array('webm','ogg','mp4');
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir ), RecursiveIteratorIterator::SELF_FIRST );
if( is_object( $files ) ){
foreach( $files as $name => $file ){
if( !$file->isDir() && !in_array( $file->getFileName(), array('.','..') ) ){
if( in_array( pathinfo( $file->getFileName(), PATHINFO_EXTENSION ),$exts ) ){
echo $file->getFileName() . '<br />';
}
}
}
}
An update that loads the videos as per the request
$dir=sprintf('%s/gallery', __DIR__ );
$exts=array('webm','ogg','mp4');
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir ), RecursiveIteratorIterator::SELF_FIRST );
if( is_object( $files ) ){
foreach( $files as $name => $file ){
if( !$file->isDir() && !in_array( $file->getFileName(), array( '.', '..' ) ) ){
if( in_array( pathinfo( $file->getFileName(), PATHINFO_EXTENSION ),$exts ) ){
/*
For my test the script is running within an `aliased` folder
outside of the directory root. The gallery folder and it's
sub-folders are within this alised directory.
Roughly the structure is:
c:\wwwroot\sites\myWebsite ~ this is the directory root
The aliased folder - as `demo`:
c:\wwwroot\content\
The working directory:
c:\wwwroot\content\stack
with the gallery
c:\wwwroot\content\stack\gallery etc
So - I needed to remove the absolute portion of the returned filepaths
c:\wwwroot\content
*/
$rel_filepath=str_replace(
array( realpath( getcwd() ), '\\' ),
array( '', '/' ),
$file->getPathName()
);
$rel_filepath=ltrim( $rel_filepath, '/' );
printf( '<h5>%1$s</h5><video src="%1$s" controls></video>', $rel_filepath );
}
}
}
}
Which resulted in the following display:

PHP: Path is getting changed without any modification

I am setting file include path dynamically based on URI segments as below
URI is something like
http://script/profile/
code
$segments = explode( '/', $uri );
$file = end( $segments ) . '.php';
foreach ( $segments as $segment ) {
$dirs[] = $segment;
}
$include_path = rt_trailingslash_dir( root()->template_dir ) . implode( DIRECTORY_SEPARATOR, $dirs );
print_r($include_path . '/' . $file);
Output Something like this
c:/xampp/htdocs/.../template\profile\profile.php
Using that path in include
include $include_path . DIRECTORY_SEPARATOR . $file;
Output
template\profile.php
Which is wrong. It should be rather
template\profile\profile.php
I don't know what wrong I am doing..?

PHP - JPath Moving Multiple files to correct directory

See my last question as this links to it: PHP - Moving multiple files with different files names to own directory
So i decided to using the Joomla API however, the documentation was for 1.5 and 2.5 system only but i'm using 3.0. I have a number of files that look like this:
"2005532-JoePharnel.pdf"
and
"1205121-HarryCollins.pdf"
Basically I want to create a PHP code that when someone ftp uploads those files to the upload folder that it will 1) Create a directory if it doesn't exist using there name 2) Move the files to the correct directory (E.g. JoePharnel to the JoePharnel Directory ignoring the number at the beginning)
Updated: 23/10/14 - 14:05:
My new code creates the folder but won't move the file in the upload into that new folder, code is below:
<?php
define( '_JEXEC', 1);
define('JPATH', dirname(__FILE__) );
if (!defined('DS')){
define( 'DS', DIRECTORY_SEPARATOR );
$parts = explode( DS, JPATH );
$script_root = implode( DS, $parts ) ;
// check path
$x = array_search ( 'administrator', $parts );
if (!$x) exit;
$path = '';
for ($i=0; $i < $x; $i++){
$path = $path.$parts[$i].DS;
}
// remove last DS
$path = substr($path, 0, -1);
if (!defined('JPATH_BASE')){
define('JPATH_BASE', $path );
}
if (!defined('JPATH_SITE')){
define('JPATH_SITE', $path );
}
/* Required Files */
require_once ( JPATH_SITE . DS . 'includes' . DS . 'defines.php' );
require_once ( JPATH_SITE . DS . 'includes' . DS . 'framework.php' );
require_once ( JPATH_SITE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' );
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.path');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.user.user');
//First we set up parameters
$searchpath = JPATH_BASE . DS . "upload";
//Then we create the subfolder called png
if ( !JFolder::create($searchpath . DS ."Images") ) {
//Throw error message and stop script
}
//Now we read all png files and put them in an array.
$png_files = JFolder::files($searchpath,'.png');
//Now we need some stuff from the JFile:: class to move all files into the new folder
foreach ($png_files as $file) {
JFile::move($searchpath. DS . ".png" . $file, $searchpath . DS. "Images" . $file);
}
//Lastly, we are moving the complete subdir to the root of the component.
if (JFolder::move($searchpath . DS. "Images",JPATH_COMPONENT) ) {
//Redirect with perhaps a happy message
} else {
//Throw an error
}
}
?>
Only error i get is Notice: Use of undefined constant JPATH_COMPONENT - assumed 'JPATH_COMPONENT' in /upload.php on line 70. But doesn't stop it working, am so close on this any help is greatly appreciated. I want to know where its taking the image, i think i have worked out the "DS" now.
Thanks

How do i find root url in php similar to server.mappath in .net

i have a page where i need to pass multiple arguments via the url
i need to get the relative root path of the public_html folder .
I tried some of the functions
$path=$_SERVER['DOCUMENT_ROOT'];
echo __FILE__;
$docRoot = $_SERVER['DOCUMENT_ROOT'];
echo "<br>";
$thisFile = str_replace('\\', '/', __FILE__);
$webRoot = str_replace(array($docRoot, 'library/config.php'), '', $thisFile);
$srvRoot = str_replace('library/config.php', '', $thisFile);
echo $docRoot."<br>".$webRoot."<br>".$srvRoot;
$p=getcwd();
echo "<br>".dirname ( $p );
$my_folder = dirname( realpath( __FILE__ ) ) ;
echo "<br>".$my_folder;
echo "<br>".basename($_SERVER["SCRIPT_FILENAME"], '.php');
i get the path as "/home/elitenua/public_html/gallitest/index.php"
i want the path as "/gallitest/index.php"
Please help.
Thanks in advance.
$basedir = $_SERVER['PHP_SELF'];
Thats what you are searching for.

Namespace Autoload works under windows, but not on Linux

I have the following php code:
index.php
<?php
spl_autoload_extensions(".php");
spl_autoload_register();
use modules\standard as std;
$handler = new std\handler();
$handler->delegate();
?>
modules\standard\handler.php
<?php
namespace modules\standard {
class handler {
function delegate(){
echo 'Hello from delegation!';
}
}
}
?>
Under Windows 7, running WAMP, the code produces the message "Hello from Delegation!" however under Linux, I get the following:
Fatal error: spl_autoload(): Class modules\standard\handler could not be loaded in /var/www/index.php on line 15
Windows is running PHP 5.3.0 under WAMP, and Linux is running the 5.3.2 dotdeb package under Ubuntu 9.10.
Is this a configuration issue on my linux box, or just a difference in the way namespaces and autoloading is handled on the different operating systems
The SPL autoloader is extremely primitive - it has no knowledge of namespaces, so it tries to load a file with \ in it's name while on Linux/Unix the path separator is / not .
Herman Radtke says he has submitted a patch :
http://www.hermanradtke.com/blog/hidden-features-with-spl_autoload-and-namespaces/
:s
I'm hoping it'll be implemented soon.
For now I use this workaround :
<?php
set_include_path( './classes/' . PATH_SEPARATOR . get_include_path() );
spl_autoload_extensions( '.php , .class.php' );
spl_autoload_register();
function linux_namespaces_autoload ( $class_name )
{
/* use if you need to lowercase first char *
$class_name = implode( DIRECTORY_SEPARATOR , array_map( 'lcfirst' , explode( '\\' , $class_name ) ) );/* else just use the following : */
$class_name = implode( DIRECTORY_SEPARATOR , explode( '\\' , $class_name ) );
static $extensions = array();
if ( empty($extensions ) )
{
$extensions = array_map( 'trim' , explode( ',' , spl_autoload_extensions() ) );
}
static $include_paths = array();
if ( empty( $include_paths ) )
{
$include_paths = explode( PATH_SEPARATOR , get_include_path() );
}
foreach ( $include_paths as $path )
{
$path .= ( DIRECTORY_SEPARATOR !== $path[ strlen( $path ) - 1 ] ) ? DIRECTORY_SEPARATOR : '';
foreach ( $extensions as $extension )
{
$file = $path . $class_name . $extension;
if ( file_exists( $file ) && is_readable( $file ) )
{
require $file;
return;
}
}
}
throw new Exception( _( 'class ' . $class_name . ' could not be found.' ) );
}
spl_autoload_register( 'linux_namespaces_autoload' , TRUE , FALSE );
?>
function __autoload($class_name) {
$paths[] = dirname(__FILE__) . "/../libs/misc/";
$paths[] = dirname(__FILE__) . "/../../libs/misc/";
$paths[] = dirname(__FILE__) . "/../../libs/helpers/";
$paths[] = dirname(__FILE__) . "/../../libs/simpleimage/";
foreach($paths as $path)
{
if(file_exists($path.strtolower($class_name).'.class.php')){
require_once($path.strtolower($class_name).'.class.php');
}
}
}
function __autoload($class_name)
{
$class_name = strtolower(str_replace('\\', DIRECTORY_SEPARATOR, $class_name));
include $class_name . '.php';
}
The srttolower is needed on Apache because it is (contrary to IIS) case sentive.
This is a common problem occurs when autoloading. The fix is to use DIRECTORY_SEPARATOR constant in the autoload function.
So your autoload function will look like following
<?php
spl_autoload_register(function($className) {
$className = str_replace("\", DIRECTORY_SEPARATOR, $className);
include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';
});
If you need to learn more on namespace/class autoloading visit here
Thanks.

Categories