Call a php function in another php file? - php

I need to call a function from index.php in another file example.php. If I use include it also takes all the html from index.php. I just want the result of the function. Any way to do this?
$rs = odbc_exec($con, $sql);
if (!$rs) {
exit("There is an error in the SQL!");
}
$data[0] = array('D','CPU_Purchased_ghz');
$i = 1;
while($row = odbc_fetch_array($rs)) {
$data[$i] = array(
$row['D'],
$row['CPU_Purchased_ghz']
);
$i++;
}
//odbc_close($con); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
echo $json;
Basically that piece of code in index.php takes info from a file which queries a db and encodes it in json. Instead of echoing I wanted to make a function that echos the json and call it in a new file to only get the json displayed on the page

create a functions.php file. Add the function to that file and include the file in your example.php file

Include the file before you call the function.
See below examples:
index.php
<?php
function myFunction() { //function .
return "FirstProgram"; //returns
}
?>
Now Using include http://php.net/include to include the index.php to make its content available for use in the second file:
example.php
<?php
include('index.php');
echo myFunction(); //returns myFunction();
?>

index.php
function myFunction() {
return "It works!";
}
example.php
include('index.php');
echo myFunction();

Related

Get a variable from another file in wordpress

I'm kind of new to wordpress coding and I've been trying to get a variable from another file.
I have this variable $final_cat_url in /custom/last-category.php that I want to reuse in customtemplate.php.
I've read lots of explanations and the codex, but it's still not working.
I've tried to use the following code in customtemplate.php
get_template_part( 'custom/last-category', null, array('my_final_cat_url'=> $final_cat_url));
echo $args['my_final_cat_url'];
Can you help me with that? Thanks a lot.
Add this function to your functions.php file:
function includeWithVariables($filePath, $variables = array(), $print = true){
$output = NULL;
if(file_exists($filePath)){
// Extract the variables to a local namespace
extract($variables);
// Start output buffering
ob_start();
// Include the template file
include $filePath;
// End buffering and return its contents
$output = ob_get_clean();
}
if ($print) {
print $output;
}
return $output;
}
Instead of using get_template_part(), use this:
<?php includeWithVariables('file_to_include.php', array('final_cat_url' => $final_cat_url)); ?>
In the file you included:
<?php echo $final_cat_url; ?>

php include into a variable then echo that variable

I want to include a file entirely into a variable. So that I can call this var multiple times and keep the code as clean as possible. But when I echo the var it only returns a 1 and when I use the include on itself it output the entire file.
I want to output the included file and run all php code inside it.
So what am I doing wrong here.
default.php
$jpath_eyecatcher = (JURI::base(). "modules/mod_eyecatcher/tmpl/content/eyecatcher.php");
$jpath_eyecatcher_path = parse_url($jpath_eyecatcher, PHP_URL_PATH);
ob_start();
$eyecatcher = include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);
ob_end_clean();
echo $eyecatcher . '<br>';
include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);
echo output is
1
include output is
eyecatchertype = 2
fontawesome
envelope-o
insert_emoticon
custom-icon-class
128
images/clientimages/research (1).jpg
top
test
Thanks for the help!
Use file_get_contents instead of include()
include() executes the php code given in the file, whereas file_get_contents() gives you the file content.
include is not a function, and normally only returns the status of the include operation:
docs:
Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files.
e.g.
x.php:
<?php
return 42;
y.php
<?php
$y = 'foo';
z.php
<?php
$z = include 'x.php';
echo $z; // outputs 42
$y = include 'y.php';
echo $y; // ouputs 1, for 'true', because the include was successful
// and the included file did not have a 'return' statement.
Also note that include will only execute the included code if it contains <?php ... ?> code block. Otherwise anything included is simply treated as output.
Use file_get_contents or ob_get_clean, like so:
ob_start();
include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);
$eyecatcher = ob_get_clean();
The following assigns the return value of include() to the variable $eyecatcher.
$eyecatcher = include ($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);
Because the include() was successful, it returns a boolean value of true, which is presented as "1" when you echo it.
If you wish to load the $eyecatcher variable with the contents of the file as a string, you do:
$eyecatcher = file_get_contents($_SERVER['DOCUMENT_ROOT'] . $jpath_eyecatcher_path);

Executing another PHP file and return the output from a method, is that possible?

Suppose if I have a PHP script test.php which have a method
<?php
function execute($filename){
//do something
return $output;
}
?>
and I also have another PHP script executable.php
<?php
echo "I am executed";
?>
then can i run any code to excute the second file and return the output from the first method execute when i call echo execute('executable.php'); ?
I guess you guys can understand what I meant.
You can use output buffering, as long as the file being included doesn't already do that:
ob_start();
require $filename;
$content = ob_get_contents();
ob_end_clean();
return $content;
Use ob_Start and ob_get_contents to capture the output of the script. Something like this should work:
<?php
function execute($filename){
ob_start();
include $filename;
$output = ob_get_contents();
ob_end_clean();
return $output;
}
<?php#test.php
include 'executable.php';
echo $test;
?>
<?php#executable.php
$test = "I am executed";
?>
function execute($filename){
include_once($filename);
}
$filename is the name of your file to be included.. I think this will help you...
This is the function call..
execute('abc.php');

How do I use PHP to supply info to JavaScript?

I have a simple image-looping script that changes the src of an image.
function cycleNext()
{
++imgIndex;
if(imgIndex>imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.
How can I use PHP to supply this script with the number of images in the folder?
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>
Repeat the 2nd line for each extension you wish to count.
function cycleNext()
{
++imgIndex;
if (imgIndex > <?php echo $filecount;?>)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
That should do it.
EDIT:
function cycleNext(imgCount)
{
++imgIndex;
if (imgIndex > imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
Then when you call cycleNext, call it with the variable.
cycleNext(<?php echo $filecount; ?>);
if the .js file is a separate file. then you can do this:
change the .js for a .php
then you can add <?php ?> tags just like you do in your .php files.
just don't forget to add the header in the code, indicating that the file is a javascript file. like that:
<?php header("Content-type: text/javascript"); ?>
and you will call the file with it's actual name src="file.php"
You can do it in three ways:
Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
include the javascript to the <head> tag of your page
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
<script type="text/javascript">
var imgCount = <?php echo $imagecount ?>
</script>;
During the generation of the HTML code, simply insert a <script> line, for instance
echo '<script type="text/javascript">';
echo 'var imgCount=' . $NumberOfImages . ';';
echo '</script>';
Just ensure that line is provided before cycleNext() is called (or imgCount is used).

How to pass the require_once output to a variable?

I want to call require_once("test.php") but not display result and save it into variable like this:
$test = require_once('test.php');
//some operations like $test = preg_replace(…);
echo $test;
Solution:
test.php
<?php
$var = '/img/hello.jpg';
$res = <<<test
<style type="text/css">
body{background:url($var)#fff !important;}
</style>
test;
return $res;
?>
main.php
<?php
$test = require_once('test.php');
echo $test;
?>
Is it possible?
Yes, but you need to do an explicit return in the required file:
//test.php
<? $result = "Hello, world!";
return $result;
?>
//index.php
$test = require_once('test.php'); // Will contain "Hello, world!"
This is rarely useful - check Konrad's output buffer based answer, or adam's file_get_contents one - they are probably better suited to what you want.
“The result” presumably is a string output?
In that case you can use ob_start to buffer said output:
ob_start();
require_once('test.php');
$test = ob_get_contents();
EDIT From the edited question it looks rather like you want to have a function inside the included file. In any case, this would probably be the (much!) cleaner solution:
<?php // test.php:
function some_function() {
// Do something.
return 'some result';
}
?>
<?php // Main file:
require_once('test.php');
$result = test_function(); // Calls the function defined in test.php.
…
?>
file_get_contents will get the content of the file. If it's on the same server and referenced by path (rather than url), this will get the content of test.php. If it's remote or referenced by url, it will get the output of the script.

Categories