can require_once() be called in the middle of php execution? - php

I want to write a script that creates a PHP file with some definitions (define(..., ...);) and then within this script i want to run more commands that uses the definitions i just defined in the newly created php file. for this to work i am guessing i could do something like that :
create file (say def.php) and write definitions to it
require_once 'def.php';
run commands that uses definitions from def.php
will this work? if not what is the right way of doing it?

It will work, you can use it but if the file does not exist then it will call exit() in the middle of your page so you will get a half loaded page with an error message.

I think the eval() or anonymous functions (closures) should be better.
http://www.php.net/manual/en/function.eval.php
http://php.net/manual/en/functions.anonymous.php

Related

PHP skips function call output

I have the following problem
require('drawchart.php');
if ( file_exists('drawchart.php')){ cwrapper();}
command using the 'chart.png' from cwrapper;
The cwrapper is a function inside the drawchart.php that accesses a MySQL and draws a Chart. This function works perfectly fine on its own and in a test.php but it stops producing the chart in my main program and I am baffled as to why it just won't work there.
I have tried introducing a sleep(30) to see if it needs to wait for the file to be written in order to succeed. But that doesn't help either. The 2nd command following just never picks up the output file chart.png. Directories are absolute paths in both cases so that's not a problem.
It does pick up an existing chart.png there but just not the updated one that should be generated from the if call. It seems to be skipping this call to cwrapper.
The cwrapper is using pchart to draw the chart And it does that perfectly on its own in a testscript.
How do I solve this problem?
Is there a better way to achieve this?
First of all, make sure the cwrapper() function is invoked.
Because you don't provide the path of drawchart.php, if it doesn't exist in the current directory, require() searches it in the paths specified in include_path in php.ini (it can be changed during the runtime).
file_exist() is not that lucky, it can find the file only if it exists in the current directory.
The best way to handle this situation is to not check if the file exists (who cares about it?, let require() handle it) but to check if the function you want to call exists:
require 'drawchart.php';
if (function_exists('cwrapper')) {
cwrapper();
}
In fact, because require terminates the script if the file cannot be loaded, you don't even need to check if the function exists. If it is defined in the required file then it exists after the require() statement returns (or the script is aborted otherwise).
Your code should be as simple as:
require 'drawchart.php';
cwrapper();

How are include_once loops handled in php?

I have 3 different files-
fileMainIncludeEverywhere.php
...
include_once('fileMinorInclude.php');
?>
fileMinorInclude.php
...
include_once('fileMainIncludeEverywhere.php');
...
fileToRun.php
...
include_once('fileMainIncludeEverywhere.php');
...
I have a lot of files like fileToRun.php.
Currently I'm not facing any errors in my code, but I want to know if there's any case where this would fail?
I think no error in this case. Because include_once will only load the file for the first time then upcoming load request will be rejected for the same file.
So from your example:
fileToRun.php will load fileMainIncludeEverywhere.php (first call)
fileMainIncludeEverywhere.php will load fileMinorInclude.php (first call)
fileMinorInclude.php will call to load fileMainIncludeEverywhere.php but it will be rejected as it has been already loaded in first step.
Hope it will help.
include_once:
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once.
Here "code from a file" also entails the executed PHP file.
Note it's generally best practice to use require_once() instead of include_once() unless you've got a specific reason for using include_once() (like say including optional template components). This because require_once() will terminate (fail fast) if the required resource is not found, and not finding it normally should be a terminal failure.

Open file from a php document, and close it from another?

I am trying to do the following:
Open a file, say "myfile.json" from a php- let's call it "utils.php"; Use it in other php pages; close it from another php.
I have tried to include "utils.php" in the other files and write in the utils file, but it does not seem to work. I suppose this happens because utils.php is never actually executed, only included, but if I should execute it, how can I do it without having to refresh any page, preferably right when the user gets on the main page? This should not be seen by the user, what he sees should remain the main page.
Thanks in advance, I am quite new to php, and am trying to learn.
When you include a file, you are running all code inside it. The functions and classes will not be evaluated but will be defined for future use. If you open your file as this example:
util.php
<?php
$file_hand = fopen('/tmp/file.txt','r');
You will have a handle if the operation is completed. However, the variable $file_hand is global. If you need to use a function to close it, you will need the following code to do it:
other.php
function close_file(){
global $file_hand;
fclose($file_hand)
}
or you can pass the handle as parameter like:
function close_file($file_hand){
fclose($file_hand)
}
Doesn't matter how you will close the file. You have to make sure the variable you are using is the same created in utils.php. If you close like this:
function close_file(){
fclose($file_hand)
}
The variable you've created in until.php file is different of this one.

Using require_once inside a method

From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.

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