How to send variables from one file to another?

Hi I have been working on my phpmailer files and I have made a validation rule to check if ‘certain’ input fields meet my requirements than once the verification is complete they are ment to send it to the user inserting their email address into our database for means to verify the person putting his/her email address owns the email address

Now I have 2 problems the testing.php file will have a required_once() function pointing to my phpmailer file with the info inserted now where do i generally input the users email address to get it sent to them and not me as that is the default path for my mail sent.

the example shows that 3 fields are all that is edited or not added to my phpmailer file but inserted into testing.php what mail-> do i have to add or remove to get my mail sent to the user for mail verification.

require_once ($_SERVER['DOCUMENT_ROOT'] . '/test.php');

	$head = "Dear ($email)";
	$body = "Attached to this email is a generated key that is used to verify that this email account belongs to $name $srn";
	$foot = "If this is not you or you did not just try to sign up for MrLaptop.co.za email blast than feel free to ignore this email. ";
	$key  = substr(md5(uniqid(rand(), true)), 6, 6);
	
$msg = $head . "<br/><br/>" . $body ."<br/><br/>" . $key . "<br/><br/>" . $foot ;

	$mail->Subject = "From:$name $srn ($email)";
	$mail->Body    = $msg;
	$mail->AltBody = "Sent By Mrlaptop.co.za";

the input field name for email input is $mail I i must add the HTML form just ask as im trying to avoid confusing or messy questions.

The second problem lies in the html form as the page is in .php format now the issue is once the email is sent out to myself in this case it generates a random key and in the html form there is an input field that gets displayed and another function after like this;

if (isset($_POST['FormS'])) {
require_once ('PHP/Testing.php');

echo $results;
}

if (isset($_POST['key'])) {

require_once ('PHP/sent.php');

echo $results;

}

i want to pass the veriable that was created in Testing.php and move it to sent.php so i can create a verification that the generated key matches the input field as it should be copied from his/her email so if i recreate the generated key it will give me a different generated key therefore never matching the input field. so any help would be appriciated please.

Any more info needed just let me know so i can add it.
and also i dont know where i should apply sessions() and how to apply it to the already generated key and not the php script for it as it will random gandomly generate a new key.

If you include/require other files, you don’t need to transfer variables. If you have different requests, like sending a location header, or a link click, ther are two options. If its public data you want to transfer, you can use a form, or attach the variable contents to the URL for a link or location-header. if its private content, you must ensure that the user is not able to change that value, for that you can use sessions.

I know veriables dont need to be transfered but lets say I require() the first function file in the second one just to get the veriable than wont the file execute twice?

Wont it still end up verifying the user and sending the mail again?

And by using Post not Get I have put privacy because the only person that should be seeing the generated key is the person who owns the email address as to avoid anyone from just using bogus email addresses or someone elses email address in the form.

and this form is a normal message to send to the owners of the website for help and stuff im using the verification specificly to be able to reply to the user.

Should I use session() on all 3 files? or which files would I need to apply it because the second required() function verifys the key sent to the user is the same as the one put into the input field and if it is than i just send the message to the main email address inside phpmailer file.

include() and require() are just methods of keeping code easier to deal with - they are basically the equivalent of merging the code into your main code in whatever editor you use to edit PHP. When the server parses your main php code, it looks for any include()s and merges the content of those files in, in that position. So variables that are present in the line before the include() retain their value, as long as variable scope allows it, throughout the included / merged code.

Also, you talk about functions - are the included files actually functions, or just included code? If they are actually functions, then they are only executed when your main code specifically calls them.

If you want to split them into separate files, then you will need to have some way of transferring the variables from one to the next, which could be a session, or it could be via hidden form variables, or as part of the URL, depending on your exact needs. If you do choose to use sessions, then I think you need to use them in all the scripts in the chain.

Others have already explained how passing variables works but I’d like to encourage you to change your approach completely. Do not inlude/require files that contain directly executed code - this will work but with time your code and application will grow messy and disorganized. Include and require don’t have any mechanism of passing variables so everything global is passed - it is not clear what you want to pass because everything is passed (one exception is that include/require allow you to return values from them - but still they always affect global scope). I’ve done this often when I was starting with PHP and the result was horrible when sites and applications grew.

The alternative is require only files with PHP functions and classes. In procedural programming this will be a set of functions and in OOP - classes. Function and class definitions are not executed when you require them so there is nothing to pass and you can require those files at any place before executing those functions or classes. And further, when those files contain classes you can implement autoloading, in which case you don’t need to require anything because it is done automatically!

So in your main code - instead of require_once in your example, you simply execute functions or class methods - and they have built-in means of passing variables through arguments and return statements. For example, first you execute a TestForm() functions which returns some value that you assign to a variable. And in the second step you execute your SendMail() function, passing to it that variable as an argument.

1 Like

My include() and require() are not activated right away they require the use of a function from them to run meaning my script only runs if I click on certain submit buttons this way it is pretty well organized meaning the first scrip verifies the input as valid and not empty than sends a user an email based on what is asked in this case a randomly generate key.

if the message was sent successfully than my php executes results with the appropriate info which is another form with an input field that requires the key if it passes through another submit the next function activates and thats where my problem lies I need to use all my variables that was filtered in the first function to pass through the second function to verify that the key input into the input field is the same as the one that was generated for the email upon success it requires() phpmailer and sends a message to the web owners email address so meaning everything is verified twice before actually sending.

I could just verify once but the problem is people will start using bogus email address and applying the email blast with other peoples email address as they were not asked to verify the email address themselves I already had that issue I was registered to some unknown site which i never heard of and when i checked it out they dont require u to verify your email address.

if I make use of hidden input fields bots could read them meaning they might as well use the answers to validate the input field I don’t know how smart bots are but I don’t think they would be that stupid not to use the generated key in the hidden input field.

I know bots cant read php yet but they can read html and since use of hidden input fields has to be attached to an html element meaning it can be read like normal text as if it is pasted like a piece of paper with password on a shop window.

but the session() I tried an keeps giving me errors that the header has already been sent and makes no sense as I don’t know they mean by that?

Every file that uses a $_SESSION variable must open sessions with session_start();.

Problems arise if a session has already been opened by a parent file that includes or requires a file that uses session variables.

To prevent errors always test for isset( $_SESSION ) - if it is false then use session_start() otherwise do not use session_start();

Edit:

Ponderism for today… both include_once() and require_once() functions exist. Why is there not a session_start_once function?

So if I use session_start() on the required page will the session_start() automaticly be added to the page that requires the file that has session_start()?

so what if I applied session_start() to the page that has required() attributes will those required pages also have the session start?

The reason I ask is if I add the require() inside a function meaning it will only open session_start() than but as soon as the function is finnished than doesn’t it like remove the session_start() as it was not inserted on the page with the required page meaning the sessions wont be active for the second function therfore applying a new one on another function would just open a different set of veriables?

If session_start() saved veriables on the page after being used than would it be advisable to turn those sessions into Global veriables so the second function can also use them?

Why not create a couple of files and test the results?

file: first.php

<?php  // file:  first.php
if( ! isset( $_SESSION ) ):
  session_start();
endif;
$_SESSION['MICROTIME'] =  microtime( true ) ;

echo '<h1>' . __FILE__  .'</h1>';
echo '<br>' .$_SESSION['MICROTIME'];

require 'second.php';

### file: second.php ``` <?php // file: second.php if( ! isset( $_SESSION ) ): session_start(); endif; echo '

' . __FILE__ .'

'; echo '
' .$_SESSION['MICROTIME']; echo '
' .microtime( true ) ; ```

Play about with these two files until you understand exactly how sessions work

1 Like

Alright thanks it’s just adding session_start() didn’t work when I was working on it what I mean is I tried creating session veriables inside a function and they worked inside the function but when I accessed them inside another function it just shows undefined.

But if I make them global sessions by applying them outside the function it does its job applying the $_POST[‘name’] and so on inside the first function but the second function is another submit form so when submit those names and stuff don’t exist therfore giving me undefine.

BTW I managed to narrow it down into one page that is now required by the use of just calling php functions on submit.

The point is the second function rewrites when submit is used again but in a second form when defining the $post veriables creating a new one but ignores them when only placing them inside the first function meaning they were never set unless the first function is actvated with the second function.

What I want to do is try to get the answers about 4 input fields into the second function without rewritting the input results but taking them to the second function.

Ok this deserves an update I have tried session veriables and it didnt work so I tried use of function and would like to know:

  • Would creating a php class for function transfer variables between function.(form variables) since everytime the submit execute it applies new info for the variables,

  • how to add previous result variables into another function without overwritting the variables.(when variables are submitted they get overwritten with input field data but no input fields exist with the names so they turn blank)

  • How to activate a function within a function because the results turn blank and I dont know why?

The idea is that onsubmit the submit buttons have names so on certain submits the action start the function using require_once() and function name.

But after the first function activates it should result with a new input field that asks for a generated key that was sent to the user (I need to find out what to edit to use a users email address and not my default email address in PHPmailer)

The second function than activates on submit of new input field and than verifies that generated key is the same as the one attached to the email so in total there should be 6 input fields excluding the new input field,

The first three are used in the function such as name surname and email than the rest gets taken to the second function with the key aswel as the new input field.

The problem I’m having is after the first function takes the variables and sends the email out but they are only local if I made them global the second function would overwrite them like $_POST['name'] since it doesnt exist in the second function it returns blank.

the generated key generates 6 random numbers and letters if i made it global the second function would generate a new random key therfore never matching the email.

so yeah I hope someone can help me on this I have been looking for over a week now and can’t find answers how do use it like this function new($data) when the $data can only be used localy in a function it returns empty.

It’s hard to help without seeing any code. Generally speaking, session variables do work, so there must be something specific in your implementation that is causing an issue.

I personally don’t think that creating a class is going to help here. I have little experience of classes, though, so that might be wrong.

Alright It’s just I tried making use of sessions but they pick up nothing or they get over written like a regular php variable because both are submitted forms.

PHP

function Veri(){
/* Filter Remove extra spacing */
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

$user = test_input($_POST["name"]);
$users = test_input($_POST["surname"]);
$sender = test_input($_POST["send"]);
$msg = test_input($_POST['message']);

/* Filter empty fields and unauthorised charactures and applying variables appropriately */
if(!empty($user)){
	
	if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
			$name = "User";
			$valN = 0;
			$errname = "*Your name contains elements other than text";
		}else{
			$name = test_input($_POST["name"]);
			$valN = 1;
			$errname = "";
		}
		
}else{
	$name = "User";
	$errname = "* Please Fill in Your name<br/>";
	$valN = 0;
}

if(!empty($users)){
	if (!preg_match("/^[a-zA-Z ]*$/",$users)) {
			$srn = "";
			$valS = 0;
			$errsrn = "* Your Surname contains elements other than text<br/>";
		}else{
			$srn = test_input($_POST["surname"]);
			$valS = 1;
			$errsrn = "";
		}
		
}else{
	$srn = "";
	$valS = 1;
	$errsrn = "";
}

if(!empty($sender)){
	if (!filter_var($sender, FILTER_VALIDATE_EMAIL)) {
			$email = "* Please fill in a valid email address<br/>";
			$valE = 0;
		}else{
			$email = test_input($_POST["send"]);
			$valE = 1;
		}
		
}else{
	$email = "* Please fill in a valid email address<br/>";
	$valE = 0;
}

if($valN + $valS + $valE >= 3){
	
/* Verify email address */
require_once ($_SERVER['DOCUMENT_ROOT'] . '/test.php');

	$head = "Dear ($email)";
	$body = "Attached to this email is a generated key that is used to verify that this email account belongs to $name $srn";
	$foot = "If this is not you or you did not try to send an email to Mrlaptop.co.za using our contact Page than feel free to ignore this message ";
	$key  = substr(md5(uniqid(rand(), true)), 6, 6);
	
$msg = $head . "<br/><br/>" . $body ."<br/><br/>" . $key . "<br/><br/>" . $foot ;

	$mail->Subject = "From:$name $srn ($email)";
	$mail->Body    = $msg;
	$mail->AltBody = "Sent By Mrlaptop.co.za";

/* echo after verify if mail is sent */
	if($mail->send()) {
		
	/* If verify was successful */
		$head = "Dear $name $srn ($email)";
		$body = "Please Fill in the key that was sent to $email";
		$inpt = '<form method="post"><label for="key">Input Key</label><input type="text" id="key" name="key" /><br/><input type="submit" name="sub" style="cursor:pointer;" /></form>';

		$results = $head ."<br/>"."<br/>". $body ."<br/>"."<br/>". $inpt;
		echo $results;

	}else{
	
	/*If verify was not successful */
		$head = "Dear $name $srn";
		$body = "Your Email was Not successfully delivered for the following reasons:";
		$inpt = "$errname <br/> $errsrn <br/> $email <br/> You may have lost Internet connection";

		$results = $head ."<br/>"."<br/>". $body ."<br/>"."<br/>".'<b style="color:red;font-size:15px;">'. $inpt.'</b>';
		echo $results;

	}
	
}else{
	
	/*If verify was not successful */
		$head = "Dear $name $srn";
		$body = "Your Email was Not successfully delivered for the following reasons:";
		$inpt = "$errname <br/> $errsrn <br/> $email <br/>";

		$results = $head ."<br/>"."<br/>". $body ."<br/>"."<br/>".'<b style="color:red;font-size:15px;">'. $inpt.'</b>';
		echo $results;

	}
}

function mailing(){
	
	$veri = $_POST['ans'];
	
if($veri = $key){
	
	/* Do some stuff */

}

HTML form:

<form method="POST" action="contact.php" Onsubmit="javascript:note()">
<h2> Contact form </h2>
<label for="name">Name</label>
<input type="text" id="name" name="name" />
<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" /></br>
<label for="send">Email</label>
<input type="email" id="send" name="send" /></br>
<label for="website" style="display:none !important;">Website</label>
<input type="text" id="website" name="website" /></br>
<label for="message">Message</label>
<textarea id="message" name="message"></textarea></br>

<input type="submit" id="formS" name="FormS" value="send" Onsubmit="javascript:notify()"/>
</form>

HTML/PHP results:

<div id="php">
<ul>
<h1>Welcome<a href="javascript:notify()" style="font-size:29px;color:maroon;background-color:#050505;padding:5px 10px;float:right;margin-top:-10px;margin-right:-10px;">X</a></h1>
<li style="text-align:center !important;">
<?php

if (isset($_POST['FormS'])) {
require_once ('PHP/Testing.php');

	veri();
}

if (isset($_POST['sub'])) {
	require_once ('PHP/Testing.php');
	
	mailing();
}
?>
</li>
</ul>
</div>

So the Html form is submitted and than the results are using required_once() to find the file needed to find the function than the stuff gets filtered and sent out to the user at this point my default email address (I need to add another mail-> for the users address not mine and I dont know what to put there)

Than it echos $results back to the html page with the new input field

$inpt = '<form method="post"><label for="key">Input Key</label><input type="text" id="key" name="key" /><br/><input type="submit" name="sub" style="cursor:pointer;" /></form>';

		$results = $head ."<br/>"."<br/>". $body ."<br/>"."<br/>". $inpt;
		echo $results;

and submits that for the second function which doesnt pick up anything from the first function.

I tried applying the second function inside the first function but than after second submit it returns blank instead of echoing the results i need some php is commented but the echo is just to see if the info went throught.

The second form is going to verify the remaining 3 fields and 1 variable.

But you show no code example of your attempt at using sessions.

Here’s one:

function mailing(){
	
	$veri = $_POST['ans'];
	
if($veri = $key){
	
	/* Do some stuff */
  1. Where does $key come from?
  2. Did you mean to assign it’s value, or compare it, to $veri?

And yes, what I really meant was “show us how you use sessions and have problems with them”.

Functions only have access to either values that you pass into them, or global variables. Hence, your veri() function can see the $_POST variables because, by their nature, they are global variables. But any other values needed must either be declared global (a Bad Thing, IMO) or passed in as parameters.

I think the flaw here is that you don’t store the generated key that your user has to enter to confirm their registration, so there is a problem in checking it when the user completes the second form. Normally what I’d expect to see is that, on completion of the initial form, the users details are stored in a database table, and the generated key stored along with them either in the same table, or another one. You then stick the unique id of the user row into the form as a hidden variable, or hash their email, or some unique means of identifying the user. When they fill in the second form, your verification code grabs that, loads the generated key from where it was stored, compares it to the user input, and says yes or no.

1 Like

I tried Using Sessions when I apply them inside the first function ONLY than the second function returns nothing.

If I try them in the second function Also than it says _Session Undefined at line so it shows nothing.

I tried $_Session['name'] = $name or $_Session['name'] = $_POST['name'] in the first function and tried both echo and print_r but the results dont show on the second function results after calling echo or print_r on $_Session['name'] or $name;

I had Session_start() on the php page it threw header error so i added Session_delete(); at the end of the page I also tried ignoring header error and still continue but nothing no matter what i do on the form page with Session_start() it always throws an error therfore not loading the page.

So I gave up on Sessions and tried the use of functions and global variables and GLOBALS['']; variable still nothing gives undefined global errors;

so here I am trying to figure out how to apply the $data as part of the second function name like function new($data) containing the results of the first function.

The key sits there only is only applied after the form verification returns true i want to check the key that was generated and sent with the email.

the second function had echo $name it kept coming undefined

That will be because you had it after you’d already output something to the browser. session_start() must come before any output. Looking at your last piece of code, there’s loads of output before you require_once() the testing / verification code, so you can’t put the session_start() inside the included file. It has to go at the top.

In fact your last bit of code might be better as:

<?php
session_start();
require_once ('PHP/Testing.php');
?>
<div id="php">
<ul>
<h1>Welcome<a href="javascript:notify()" style="font-size:29px;color:maroon;background-color:#050505;padding:5px 10px;float:right;margin-top:-10px;margin-right:-10px;">X</a></h1>
<li style="text-align:center !important;">
<?php

if (isset($_POST['FormS'])) {
	veri();
}
if (isset($_POST['sub'])) {
	mailing();
}
?>
</li>
</ul>
</div>

Because testing.php only has function in it, you only need to include it once at the start of the code.

Immediately after your veri() function renders the second form, the server finishes executing your PHP code and the task on the server, including all variables and pointers, does not exist any more. So when your user submits the second form, there is no retrieving the variables that were in memory when the form was drawn. So the process is:

server draws first form
user fills out form and hits 'submit'
server runs `testing.php` and calls veri(), checks things, all is OK so sends email and draws the second form, and exits
user waits for email with second form on screen.
user fills out second form and hits submit
server runs 'testing.php' and calls 'mailing()' which does whatever it does.

There’s no persistent task sitting there with the variables still in memory, by the time the user sees the form (generally) the server has already finished running the PHP code and closed the task.

1 Like