Using include file in a function(variables not reading)?

Good day PHPhelp.com

This is my second question since I joined here

I am trying to use new function I learned “Function” and “include

Below are my codes

(This one Works!)
index.html

[php]

First Name:
Last Name:
[/php]

check.php

[php]<?php

$fname=$_POST[‘fname’];
$lname=$_POST[‘lname’];

if($fname==’’ || $lname==’’) {
include(‘error.php’);
}

else {
include(‘display.php’);
}

echo “”;

?>[/php]

error.php
[php]<?php
echo “input is missing!
”;
?>[/php]

display.php
[php]<?php

echo $fname."
";
echo $lname."
";

?>[/php]

now I am trying to use a “include” inside a “function

check.php

[php]<?php

$fname=$_POST[‘fname’];
$lname=$_POST[‘lname’];

function display() {
include(‘display.php’);
}

function error() {
include(‘error.php’);
}

if($fname==’’ || $lname==’’) {
error();
}

else {
display();
}

echo “”;

?>[/php]

after submitting with some text inside input
this notification message appears

Notice: Undefined variable: fname in C:\xampp\htdocs\function_include\display.php on line 3

Notice: Undefined variable: lname in C:\xampp\htdocs\function_include\display.php on line 4

My Question is
・why won’t include function works the same with when it is not inside a function?
・what is the practical way if I want the include file to be inside function? and properly reads variable on external file?
・is there a better way to do this?

Thanks for taking time reading this and hopefully I get a satisfactory answer :slight_smile:

First, the reason for the errors is the variables are not in scope, meaning inside the function they are undefined, if you want them to have meaning the you would have to do something like display($fname);.

Ah, here’s something directly from php.net that will help you out.
[php]

<?php function foo() { global $color; include 'vars.php'; echo "A $color $fruit"; } /* vars.php is in the scope of foo() so * * $fruit is NOT available outside of this * * scope. $color is because we declared it * * as global. */ foo(); // A green apple echo "A $color $fruit"; // A green ?>

[/php]

Though in my opinion I would avoid using GLOBAL VARIABLES.

Second, using the include the way you are doing is wrong for the most part, well not wrong but a little bit reverse logic in my opinion and causing a lot of logical errors (or just plain errors).

This his how I utilize the include. I have a bunch of chores I want to get done, such as setting up a connection to my database and variables that I want to use on more than one page, etc… I think it better to show you:

I have a file called utilities.inc.php
[php]<?php
if ($_SERVER[“SERVER_NAME”] != ‘localhost’) {
if ($_SERVER[“HTTPS”] != “on”) { // Redirect to a secure website ( https )
header(“Location: https://” . $_SERVER[“HTTP_HOST”] . $_SERVER[“REQUEST_URI”]);
exit();
}
}

utilities.inc.php

include ‘functions.secret.token.php’;

// Autoload classes from “classes” directory:
function class_loader($class) {
require(‘lib/classes/’ . $class . ‘.php’);
}

spl_autoload_register(‘class_loader’);

header(‘Content-Type: text/html; charset=utf-8’);
// Start the session:
$seconds = 60;
$minutes = 60;
$hours = 24;
$days = 14;

session_set_cookie_params($seconds * $minutes * $hours * $days, “”);
session_start();

$db = Database::getInstance();
$pdo = $db->getConnection();

// Check for a user in the session:
//$user = (isset($_SESSION[‘user’])) ? $_SESSION[‘user’] : NULL;
$current_id = (isset($_SESSION[‘current_id’])) ? $_SESSION[‘current_id’] : 1;

function html_escape($raw_input) {
// important! don’t forget to specify ENT_QUOTES and the correct encoding
return htmlspecialchars($raw_input, ENT_QUOTES | ENT_HTML401, ‘UTF-8’);
}

[/php]

that is used practically for every page to I write. If I didn’t use the include then I would have to type that exact code over and over again. That would get very time consuming and not to mention boring.
Hope that helps.

A great practical way of doing getting experience is doing some like the following.

[php]<?php
require(‘lib/includes/utilities.inc.php’);
$pageTitle = ‘J.R. Pepp | Website Design & Development’;
include ‘lib/includes/header.inc.php’; // Top Portion of HTML5
?>

<h4 class="container span12 websiteName">Website Design &amp; Development</h4>

<div class="container">    
	<figure class="span7 homePage">
		<figcaption class="intro">J.R. Pepp, based in Livonia, Michigan is a small Web Design &amp; Development company. John R. Pepp, Web Designer &amp; Developer designs and develops responsive Web sites coded in HTML5/CSS3, JQuery, and PHP at reasonable prices. All Web sites will have lively color themes, images, videos and many other great enhancements giving the website a professional, modern, clean feel to it. The mobile phone and tablet market is growing in popularity, so don't be left behind with an outdated Website! Pepster's Place will make sure your website site is capable of being seen by the vast majority of media devices that are out there.</figcaption>
		<img class="homePicture" src="lib/images/img-john-pepp.png" alt="John Pepp - Owner of J.R. Pepp">
	</figure>      		
<div class="span3 amazonAd">  
		<script type='text/javascript'>
   amzn_assoc_ad_type = 'banner';
   amzn_assoc_tracking_id = 'jrpewedede-20';
   amzn_assoc_marketplace = 'amazon';
   amzn_assoc_region = 'US';
   amzn_assoc_placement = 'assoc_banner_placement_default';
   amzn_assoc_linkid = '7NTFUWIVA6FDG7V6';
   amzn_assoc_campaigns = 'electronicsrot';
   amzn_assoc_p = '12';
   amzn_assoc_banner_type = 'rotating';
   amzn_assoc_width = '300';
   amzn_assoc_height = '250';
  </script>
  <script src='//z-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1'></script>
</div>
</div>  
</section>
<?php
include 'lib/includes/footer.inc.php'; // Bottom Portion of HTML5

[/php]
Notice how I use the include(s) to write the top portion and bottom portion of HTML5 this way I don’t have to repeat myself for every page and I even have my header and navigation in the top portion of my include.
Hope this also helps.
P.S. Notice on the bottom I don’t close the <?php statement off, this is intentional. You don’t want to close off if there is not HTML going on below it, this is for security reasons.

Thank you Mr.Strider64 for your opinion and with some examples, it really helped me alot.

though I don’t understand why it is not recommended to use global variables and the logic is wrong?

but that is just your opinion, people have different style of coding and different opinions.

anyway what I wanted to has been achieved, thanks! :slight_smile:

If you choose not to use global variables which are just fine to use in my opinion, then you have to declare your functions to use the outside data in some other way. Such as $_SESSION variables. As Strider said, you really can not include a file that includes a function if the included file and functions can not see the variables it uses. So, just use Globals and you will be all set. They are not as secure as the more correct ways, but, should work for your tests.

One issue, if you load an include file, the scope of the variables are global from there on. But, if you include “FUNCTIONS”, they do not work with the ones above where you inserted them unless the previous variables are global in scope. That is why most programmers define all of their functions at the top of their code before any of them are used. Hope I got that straight. Here is a link that talks about it and also has the two PHP.net links to explain. You might want to read both those links with the discussions on each.
http://stackoverflow.com/questions/3508517/php-how-to-call-included-file-functions
Good luck…

If you choose not to use global variables which are just fine to use in my opinion, then you have to declare your functions to use the outside data in some other way. Such as $_SESSION variables. As Strider said, you really can not include a file that includes a function if the included file and functions can not see the variables it uses. So, just use Globals and you will be all set. They are not as secure as the more correct ways, but, should work for your tests.

Think of functions as outside your program. They have their own variables but can use outside global ones.
They can also use the standard outside global variables such as the arrays $_POST, $_GET, $_SESSION and others of the system status level. So, you can do it the way you show it except the two variables $fname, etc are not available loaded inside the function. Just replace the display.php echos to use the $_POST values instead.

One issue, if you load an include file, the scope of the variables are global from there on. But, if you include “FUNCTIONS”, they do not work with the ones above where you inserted them unless the previous variables are global in scope. That is why most programmers define all of their functions at the top of their code before any of them are used. Hope I got that straight. Here is a link that talks about it and also has the two PHP.net links to explain. You might want to read both those links with the discussions on each.
http://stackoverflow.com/questions/3508517/php-how-to-call-included-file-functions
Good luck…

Thank you Mr.ErnieAlex for sharing some ideas, more knowledge more power :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service