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.
Related
Sorry if my question is not clearly understandable, I don't know how to express well what I want to say in English.
This is not a problem with code per se, as it is working as shown, but mostly a doubt of the behaviour of PHP.
When I call a function from another php file, it seems to read the function itself i.e. function loademp(){}
however, if I access the file containing the function from an ajax, it seems to need a call to the function i.e loademp() to be in the same file.
Since I had this issue I ended having this code in order to make it work from both origins, with the call for the ajax inside an if condition, otherwise it would be called twice from the php file:
<?php
if ($_POST['runFunct']=="loademp"){ //call from ajax needs 'loademp()' to access the function;
loademp();
}
function loademp(){ //loaded from another file apparently.
try{
//PDO code
print_r(json_encode($results));
}catch(PDOException $e){
echo $e;
}
}
My other file just look like this:
require __DIR__.'loademp.php';
loademp();
Isn't there a more practical way to just use the code for both cases with no conditioning depending on the origin? Since I can't call a specific function from ajax without the use of POST variables, I guess this is the best case for it, but I would appreciate if you could point out the good practices about it.
I think your confusion here is between defining a function and executing a function.
To define a function, you write something like this:
function say_hello_world() {
echo "Hello, World!\n";
}
This doesn't cause anything to happen immediately, it just defines how to do something. In this case, it's basically like saying:
Whenever I ask you to "say hello world", output to the screen "Hello, World!\n"
To make something actually happen, you have to execute the function, which looks like this:
say_hello_world();
That's basically saying:
Do the actions I gave you for "say hello world"
In your example, your file 'loademp.php' defines a function called loademp - it says "whenever I ask you to 'loademp', here's what I want you to do". In your other file, you include that file, so the function is defined. Then, you run it with this line:
loademp();
An AJAX call is no different from any other page load, so you need to do the same thing there - first, define the function, or include the file that does; then, execute the function.
So, rather than calling loademp.php directly, you could call a PHP script like define_and_execute_loademp.php with exactly the lines you've mentioned:
require __DIR__.'loademp.php';
loademp();
I've got an Ajax call that runs a function from, say, file1.php and that works fine. But when I call another function from, say, file2.php file it doesn't run and returns an error.
my simplified setup:
//functions.php
require('dir1/php1.php');
require('dir2/php2.php');
//php1.php
function func1(){
echo 'Hello world';
echo func2();
}
//php2.php
function func2(){
return 'Hello again';
}
Now, func1() is already run on the first pageload. So I know func1() and func2() work fine. But it looks like the Ajax call forgets all the require()s. Because when I change my func1() to this and add the require it works fine:
//php1.php
function func1(){
require('dir2/php2.php');
echo 'Hello world';
echo func2();
}
At first I thought, meh if it works it works for this call. But now I come to a point I want to call more and different functions from more files. Should I re-require all those files all the time? This feels like the wrong approach. Plus I also want to call functions from plugins I don't know the path of. (I could find out, but that's not the point)
--EDIT--
I found out is doesn't re-load any of the required files when running the ajax call. Doesn't Ajax re-run the code including all your code from theme -> functions.php? This has vital code for the call.
Yes, you should call require in the file that actually needs that resource. When including php1 from functions it will pull the dependency.
But since you are using wordpress, you should register your ajax functions using wp_ajax instead of calling the file directly yourself.
If you are using wordpress ajax (wp_ajax), then this is logical.
Your first code:
You are making the request from the browser link, so the file DIR path is correct.
From the current file directory to the file you are requiring.
Your second code:
You are making the request through ajax (wp-admin/admin-ajax.php), then the directory would not be the same. Cause, wordpress is just firing the function in this admin-ajax.php file and search for your file from that directory.
So I suggest to put a full dir path with the path/to/file.
require(full/dir/path/to/file).
This is what I ended up doing.
On the main functions.php I've required an external file called includes.php From this file I require all the files I need in general (not just for func1() ). Whenever I do an Ajax call I first address the includes.php now. This re-runs all the requires. I do have to note they have to be require_once() otherwise it will find the file you are calling it from and crash. It will try to re-declare the functions it already has.
I've got the feeling this is not the most clean way to do it. But I'll have to check this out later, when I have more time to see how WP actually handles Ajax.
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();
Hello let's say that I have the following structure in my application .
<?
include('includes/functions.php');
include('includes/classes/login.class.php');
$login = new login();
?>
What I want is inside the login class to call a function that is defined in functions.php . But I can't get it to work.
PHP does not care in which file you have storred what function or class definition. Only namespaces, order or processing and of course where inside classes or functions you have what definitions matter.
What you are doing is correct.
Including php-code just adds the content of that file in the file where you execute the include. If this is not working there is something else wrong with your code.
You should close this question and make a new one. Include the content of the files you are including and the errors that are displayed.
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.