PHP - Create global flag - php

I am currently trying to find a way to create a flag (or variable) that can be accessed by all scripts. Meaning if I set the flag to true all scripts have that flag as true.
The point behind this that I am writing my own CSS, JS and HTML compressor. This script basically removes all unneccessary information from the code. Like unneccessary whitespace etc. The script is used with a call to require_once. It is working great but sometime I would like to globally disable it.
Is this possible?

There are a couple of ways you can do this but you might be better off creating a file like config.inc.php, including this within your compressor (e.g. compressor.php) and having a boolean flag within this config file like:
$compressorEnabled = true;
Then you include this in your compressor so that even when you have your require_once('compressor.php') in every one of your scripts, at the top of compressor.php you have something like:
if (!$compressorEnabled) {
exit;
}
You could also use a constant rather than a variable, or do a couple of other things. Your main concern with including files this way in all scripts is preventing variable name collisions between the compressor script and whatever script you are including it into.

Related

How to determine if this script was included into some other script

Some time ago, I developed a PHP script to send text messages, log sms usage, and so on. This is working fine.
Now I have modified it so that it may be included within another script via "include" or "require." Again it is working fine but I would like to make it operate slightly differently if "included" versus the command-line call. For example, if it's called from command line, then the parameters are in $argv, but if included in some function, we can assume certain necessary variables have already been set up, SQL connections are established, etc.
The point where I'm stuck, is trying to determine if this code is "include"d or is the main file. I know I can use get_included_files() to retrieve the necessary list. But at present (assuming my script is /path/myscript) the only test I know to use is something like:
$includes = get_included_files() ;
$isMainScript = ($includes[0] == '/path/myscript') ;
And therefore $isMainScript will be true if this was called from the command line. But clearly this is bad form; all one has to do to break it, is to rename the included script, or move it to some other directory. But I don't see any method of finding out the name of this file (/path/myscript) ... only the name of the main file (__FILE__ and its workalikes).
What do others do in order to determine if this script is a main script, or is subordinate to some other?

How to know if a script was included inside another script

I am new to PHP and very likely I am using the incorrect approach because I am not used to think like a PHP programmer.
I have some files that include other files as dependencies, these files need to have global code that will be executed if $_POST contains certain values, something like this
if (isset($_POST["SomeValue"]))
{
/* code goes here */
}
All the files will contain this code section, each one it's own code of course.
The problem is that since the files can be included in another one of these files, then the code section I describe is executed in every included file, even when I post trhough AJAX and explicitly use the URL of the script I want to POST to.
I tried using the $_SERVER array to try and guess which script was used for the post request, and even though it worked because it was the right script, it was the same script for every included file.
Question is:
Is there a way to know if the file was included into another file so I can test for that and skip the code that only execute if $_POST contains the required values?
Note: The files are generated using a python script which itself uses a c library that scans a database for it's tables and constraints, the c library is mine as well as the python script, they work very well and if there is a fix for a single file, obviously it only needs to be performed to the python script.
I tell the reader (potential answerer) about this because I think it makes it clear that I don't need a solution that works over the already existant files, because they can be re-generated.
From the sounds of it you could make some improvements on your code structure to completely avoid this problem. However, with the information given a simple flag variable should do the trick:
if (!isset($postCodeExecuted) && isset($_POST["SomeValue"]))
{
/* code goes here */
$postCodeExecuted = true;
}
This variable will be set in the global namespace and therefore it will be available from everywhere.
I solved the problem by doing this
$caller = str_replace($_SERVER["DOCUMENT_ROOT"], "", __FILE__);
if ($_SERVER["REQUEST_METHOD"] === "POST" and $caller === $_SERVER["PHP_SELF"])
performThisAction();

Are there any downsides from using Include() or nested include's()?

I am not an expert in PHP. I am trying to increase the use of include() to make my website code as clean as possible instead of just copying, for example, code of the header in all the pages. I have two questions
1 . Is it good practice to use include() a lot in terms of server requests, speed, ...etc ?
index.php
(bunch of code)
<? include("connect.php") ?>;
(bunch of code)
<? include("header.php") ?>;
(bunch of code)
<? include("footer.php") ?>;
2 . Is it fine also to use nested include's()? example:
header.php
(some code)
<? include("searchFormInput.php") ?>;
now index.php will include header.php, then header.php will include searchFormInput.php as well
is this fine?
Thanks a lot
Yes, including is a common practice.
Yes, including gives you slight performance penalty (very small).
But including gives you readibility gain and thanks to it will be easier to employ DRY rule. Just remember the following:
if the file contains some code that should be executed only once (some setup, class definitions, function definitions etc.), use include_once() (it will have no effect if invoked again on the same filename),
if the file contains some code executed multiple times (eg. some template for a form), use simple include(),
if something is required for your application to work (eg. some security code, some setup etc.), use require() instead of include() or require_once() instead of include_once() - if the file will not be found, PHP will throw fatal error and will stop executing your script,
The principle downside to nesting includes is that you are likely to run into situations when cross-dependencies cause a file to be include more than once. That is easily solved by the use of include_once(), though.
In your example however, with header.php including searchFormInput.php, you probably won't have problems assuming these files both mostly produce HTML output rather than parsing classes and dependencies.
On the other hand, if you had some structure like
connect.php includes config.php
session.php includes config.php
you would need to use include_once('config.php').
include,require will read file and excute codes inside it.
i made some tests on speed of include and file_get_contents
results was include and require is slow in compare
so my advice don't increase numbers of inclusion.
I think you should look at autoload with PHP once. You should not need to care the include of every and each file. Just adjust your autoload and that will take care of all these. You needs to do object oriented programming with this.
It's fine to that in terms of performance and it keeps your code clean and reusable to a certain extent. However, I recommend that you use templates for this kind of code inclusion, where you load all your information into variables and then call them in your template. Consider a template engine http://www.smarty.net/ or maybe a PHP framework or CMS http://drupal.org/ which should make your life easier in the short and long run!

php include problem with urls with options ?view=task&others file not found

I really have read the other articles that cover this subject. But I seem to be in a slightly different position. I'm not using modrewrite (other articles).
I would like to 'include' a webpage its a 'Joomla php' generated page inside a php script. I'd hoped to make additions on the 'fly' without altering the original script. So I was going to 'precomplete' elements of the page by parasing the page once it was included I hadent wanted to hack the original script. To the point I can't include the file and its not because the path is wrong -
so
include ("/home/public_html/index.php"); this would work
include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
I've tried a variety of alternates, in phrasing, I can't use the direct route "http:etc..." since its a current php version so must be a reference to the same server. I tried relative, these work without the ?option=com_k2&view=item&task=add
It may be the simple answer that 'options' or variables can be passed.
Or that the include can't be used to 'wait' for a page to be generated - i.e. it will only return the html.
I'm not the biggest of coders but I've done alot more than this and I thought this was so basic.
this would work include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
And it never will: You are mixing a filesystem path with GET parameters, which can be passed only through the web server (utilizing a http:// call... But that, in turn, won't run the PHP code the way you want.)
You could set the variables beforehand:
$option = "com_k2";
$view = "item";
$task = "add";
include the file the normal way:
include ("/home/public_html/index.php");
this is assuming that you have access to the file, and can change the script to expect variables instead of GET parameters.

custom php function creation and install

I would like to know how to create a php function that can be installed in php
just like the already built in functions like :
rename
copy
The main point I would like to achieve is a simple php function that can be called from ANY php page on the whole host without needing to have a php function within the php page / needing an include.
so simply I would like to create a function that will work like this :
location();
That without a given input string will output the current location of the file via echo etc
Well, there are a couple of options here. One of them is to actually extend the language by writing an extension. You'd have to muck around with the PHP source code, write it in C, and deal with the Zend Engine internally. You probably wouldn't be able to use this on a shared host and it would be quite time consuming and probably not worth it.
What I would do is put all of your functions into a separate PHP file, say helper_functions.php. Now, go into your php.ini and add the directive: auto_prepend_file = helper_functions.php. This file should be in one of the directories specified in your include_path (that's a php.ini directive too).
What this does is basically automatically put include 'helper_functions.php'; on every script. Each and every request will have these functions included, and you can use them globally.
Read more about auto_append_file.
As others have said, there's probably an easier, better way to do most things. But if you want to write an extension, try these links:
http://docstore.mik.ua/orelly/webprog/php/ch14_01.htm
http://www.tuxradar.com/practicalphp/2/3/0
So you want to extend PHP's core language to create a function called location(), written in C, which could be done in PHP by:
echo __FILE__;
Right. Have fun doing that.

Categories