Disable warning when trying to declare a global constant that already exists - php

I am currently dealing with a third-party library that defines a global username/password constants in a global namespace. I do not want to modify the library source code at the same time I need to connect with different credentials (i.e. more than one set). Therefore, editing the library source code is not the solution. To be honest even without this requirement this is not a good practice to modify the 3rd-party libraries source code as it may lead to unexpected results when updating.
define('OSRS_USERNAME', $credentials[self::USERNAMETAG]);
define('OSRS_KEY', $credentials[self::PASSWORDTAG]);
$host = isset($credentials['testmode']) ? self::TESTHOST : self::LIVEHOST;
define('OSRS_HOST', $host);
define('OSRS_SSL_PORT', self::PORT);
//only now we can require the openSRS loader as it otherwise would define other values as contants for username & password
//# is here to supress warnings about redefining the credentials constants in the 3rd party config file
//this is safe as just including the file shoould not throw if the script does not have any syntax errors
#require_once('OpenSRS/openSRS_loader.php');
This, however, still outputs the warning in CLI
Is there any way to suppress those warnings?

This is their config file:
https://github.com/OpenSRS/osrs-toolkit-php/blob/master/opensrs/openSRS_config.php.template
From their documentation you are meant to define these constant in a renamed copy of that.
Check your dist for an existing file called: openSRS_config.php

Related

Natively profile multiple scripts in PHP7

Since the release of PHP 7 it is now not possible to profile an entire selection of scripts using declare(ticks=1) in your base file and then using register_tick_function() to monitor each tick as it no longer follows include paths. According to the PHP bug filed at https://bugs.php.net/bug.php?id=71448 this will never be available again in PHP 7.
Due to an implementation bug, the declare(ticks=1) directive leaked into different compilation units prior to PHP 7.0. This is not how declare() directives, which are per-file or per-scope, are supposed to work.
Are there any alternatives to this approach using native PHP (not C or pear extensions etc.) that are available to me in PHP 7 that will allow me to profile each function or file called in a page load, getting details of the actual file path at least.
My original question that led to finding the bug can be found at How to avoid redeclaring ticks on every file in PHP 7, this question is now about alternative methods.
One common way to do this without declare(ticks=1) is to use a profiler. A profiler will take notice of any method/function called, file loaded etc. and even take timing information so you not only can say which function was called when and by what code and which files were opened but also which part of the program took how long.
A well known profiler in PHP comes with the famous Xdebug extension. It also ships with a debugger:
https://xdebug.org/
One benefit is that you don't need to change the code to do the profiling, it is just the PHP configuration you need to adopt so you can switch it on and off as you need it (e.g. debug / profiling session).
PHP Userland (tick function)
As a work-around not having declare(ticks=1); at the beginning of each file (after #71448), it is possible to add this on-the-fly via a stream-wrapper on the file protocol (for files in the local file-system which is common) that injects it.
This is technically feasible by creating a stream-wrapper that is registered on the file protocol to proxy standard file i/o operations. In this PoC (Gist on Github) the bare-minimum implementation is shown to demonstrate that it works for includes. When test.php is executed and despite that other.php has not declare(ticks=1); in it on disk, the registered tick function is called on the include as the print of the backtraces show:
...
tick_handler() called
#0 tick_handler(1) called at [/home/hakre/stream-wrapper-default-files/test.php:18]
#1 tick_handler() called at [/home/hakre/stream-wrapper-default-files/other.php:2]
#2 include(/home/hakre/stream-wrapper-default-files/other.php) called at [/home/hakre/stream-wrapper-default-files/test.php:24]
...
The output is generated from the registered tick function (here: test.php):
<?php
/**
* Inject declare ticks on include
*/
declare(ticks=1);
require __DIR__ . '/streamwrapper.php';
FileStreamWrapper::init();
// using a function as the callback
register_tick_function('tick_handler', true);
// Function which is called on each tick-event
function tick_handler()
{
echo "tick_handler() called\n";
debug_print_backtrace();
}
register_tick_function('tick_handler');
include "other.php";
include "another.php"; # file does not exists
The stream wrapper in the gist example has only implemented as little as needed to work for the two include statements, as PHP scripts normally do more file i/o it needs to be extended as needed. When it goes about seeking etc., the dynamic insertion needs to be taken into account etc. but there is state per file operation (handle) as there is one instance per each one so this should be well encapsulated. The global state is used for registering/unregistering the stream wrapper for each operation to proxy into the real file-system functions as otherwise it creates endless recursion (wrapper uses the wrapper uses the wrapper ...). The PoC so far shows how it works on principle.
This can be (mis-)used for other things as well, but this PoC is for your specific declare ticks and include use-case.

PHP Function Scope Failure

I am struggling to understand scope and what's preventing my new code from working (assuming it is a scope issue).
The following function is in a file PATH.'/includes/custom-functions.php' that references a class:
function infusion() {
require_once(PATH.'/classes/infusion.php'); //PATH is defined in WordPress from ~/wp-content/themes/theme/
return new infusion();
}
The class is reliant on PATH.'/api/isdk.php' and connection credentials from another file within /api/ directory. From within PATH .'/includes/custom-functions.php', I have many other functions that call $infusion = infusion(); and work perfectly.
PROBLEM
I have created a new file: PATH.'/includes/report.php' which I need to access $infusion = infusion();but can't get to work by either repeating the function infusion() definition from above; using require_once();; or using include();. All 3 of those options simply kill the rest of the code and I can only come to the conclusion - well, I have no conclusion.
Any help would be greatly appreciated.
I'm assuming the code isn't using namespaces, therefore you aren't permitted to redeclare the infusion function (either by redefining the function, or re-including the class).
Your includes/report.php file should simply have:
require_once PATH.'/includes/custom-functions.php';
// your other code here ...
$infusion = infusion();
It may be the case that other files / classes that you're including in your file are already requiring custom-functions.php along the line, so you may be able to skip that entirely. Also note that the PATH constant should have already been defined somewhere (either directly or via an included file) before you attempt to use it. If you set your error_reporting to include E_ALL, you'll get a notification in your error log if that constant doesn't exist.
If that fails, your error log(s) may provide some additional background on what your issue is.

Is there an alternative for compiler directives in PHP in order to use app version?

Here is the thing, I have a running application and my client has been asking me to add features over time. Now he hasn't implemented all the features that I've developed, but he wants to implement one feature recently developed. The thing is that there could be some incompatibility issues between the versions of the application that I made.
I am wondering if I can add some sort of version directives to the methods of a class in php and somehow execute the ones that match with the web application version?
I would appreciate greatly any kind of help that you could give me.
You can get PHP's currently running version from the version constant PHP_VERSION and use version_compare which might help you out with w/e you are trying to do: http://php.net/manual/en/function.version-compare.php
You can set you own version and then declare the appropriate class like this (your code need to know which copy of the class is running:
define("APPLICATION_VERSION", "1.23");
define("APPLICATION_VERSION_MAJOR", "1.");
define("APPLICATION_VERSION_MINOR", "23");
if (APPLICATION_VERSION_MAJOR == "1") {
//version 1 class declaration here
class hello {}
} else {
//not version 1 class declaration here
class hello {}
}
Create a settings.php file and add constants to it.
setting.php
// Valid constant names
define("VERSION", "1");
class.php
include('settings.php')
if (defined('VERSION') && VERSION == "1") {
//run code
}
PHP is not a compiled language; just like it's client-side siblings (HTML et al.), each file is evaluated individually each time a page must be generated. So, the concept of having something in the file processed before the rest of the file loses its value rapidly.
That said, there are some variables that can be set before this process and stay constant throughout, and those are in php.ini. These are, by the literal definition, pre-processor directives. However, I know they're not what you're looking for.

Defining Application Constants in Codeigniter

I want to know a clean way of defining Application Constants in Codeigniter. I don't want to change any native file of codeigniter. Hence I don't want to define it in application/config/constants.php as when I need to migrate to newer version of code-igniter I will not be able to copy the native files of codeigniter directly.
I created a file application/config/my_constants.php and defined my constants there. 'define('APP_VERSION', '1.0.0');'
I loaded it using $this->load->config('my_constants');
But I am getting a error
Your application/config/dv_constants.php file does not appear to contain a valid configuration array.
Please suggest me a clean way of defining application level constants in code-igniter.
Not using application/config/constants.php is nonsense! That is the only place you should be putting your constants. Don't change the files in system if you are worried about upgrading.
just a complete answer. (None of the answers show how to use the constants that were declared)
The process is simple:
Defining a constant. Open config/constants.php and add the following line:
define('SITE_CREATOR', 'John Doe')
use this constant in another file using:
$myVar = 'This site was created by '.SITE_CREATOR.' Check out my GitHub Profile'
Instead of using define(), your my_constants.php file should look something like this:
$config['app_version'] = '1.0.0';
Be careful with naming the array key though, you don't want to conflict with anything.
If you need to use define(), I would suggest doing it in the main index.php file, though you will still need to use APP_VERSION to get the value.
config file (system/application/config/config.php) to set configuration related variables.
Or use
constant file (system/application/config/constants.php) to store site preference constants.
=======================
DEFINE WHAT YOU WANT
=======================
$config['index_page'] = 'home';
$config['BASEPATH'] = 'PATH TO YOUR HOST';
Please refer this:
http://ellislab.com/forums/viewthread/56981/
Define variable in to constants & add value on array
$ORDER_STATUS = array('0'=>'In Progress','1'=>'On Hold','2'
=>'Awaiting Review','3'=>'Completed','4'
=>'Refund Requested','5'=>'Refunded');
You can accomplish your goal by adding constants to your own config file, such as my_config.php.
You would save this file in the application/config folder, like this:
application/config/my_config.php.
It is very common to have a separate config file for each application you write, so this would be easy to maintain and be understood by other CI programmers.
You can instruct CI to autoload this file or you can load it manually, as needed. See the CI manual on "Config class".
Let me suggest that you use composer.json to autoload your own Constants.php file, like this:

Constant server variables?

What's the easiest way of storing a single number on a server so that any script can access it, using PHP? Currently, I have a number stored in a file, but this seems somewhat inelegant.
There's no right answer here, but most modern PHP systems for building web applications have some kind of Configuration object. This is often implemented as a singleton
//brain dead config object
class NamespaceConfiguration {
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public static function set($key,$value){
//code to set $key/$value paid
}
public static function get($key){
//code to get a $value based on a $key
}
}
$config = NamespaceConfiguration::getInstance();
$config->set('myNumber',42);
....
function somewhereElse(){
$config = NamespaceConfiguration::getInstance();
$myNumber = $config->set('myNumber');
}
This class is loaded on every page requiest. This gives every developer a standard API to call when they want to get or set single configuration values, and allows a single developer to control the where of storage and the how of retrieval (which may be a flat file, XML file, memory cache, MySQL database, XML file stored in a MySQL Database, XML File stored in a MySQL Database that contains a node which points to a file that contains the value, etc.)
The where and how of retrieval is going to depend on your application environment, although by using a configuration object you can create some efficiencies up front (storing already retrieved values in a property cache, pre-fetching certain values on instantiation, etc.)
Since your application probably already have some sort of include-file on the top "header.php" or simular, you could just create a constant/variable in that file, and all the files that include the header will also have access to the constant.
This may help you to define the constant:
http://php.net/constant
That depends on the characteristics of the number. Is it updated/modified often? Is it the only such number? If it isn't changed it's probably better to do as Espo suggests and store it as a php constant that can be included when necessary. If you have other such numbers you can put them all in that file. If they are updated often it's probably better to put it in the database.
But. If it's a single number, that is subject to change, and you don't forsee any need for storing other numbers, why not use a file? Just remember to use flock() when updating it to avoid concurrency issues.
Your best bet would be to put it in a MySQL table for fetching later. That's probably the best way to store information in PHP.
If it is a variable that is more of a environmental nature you could always use set those in Apache
in your httpd.conf file you can set the following:
SetEnv myVar myValue
You can then use $_SERVER to fetch it
$_SERVER['myVar']
I usually set varibles on this if i am to setup same application on a few different virtual hosts but dont want them to have different parameters in the config file.
A config file will also meet your needs.
There is some easy to use classes in Zend framework that can help out
http://framework.zend.com/manual/en/zend.config.html
more specific section 7.3 and 7.4 describes how you can write config parameters in a plain text file or in XML.
if you prefer plain old php you have the function parse_ini_file that lets you read in config parameters from a text file
http://us.php.net/parse_ini_file
You can also use the Alternative PHP Cache or other caching options.
http://www.php.net/manual/en/function.apc-add.php
And you can use this in combination with the other solutions listed above, e.g saving a config to cache.

Categories