So I have an HTML file that is a basic form. Say
<form method="POST" action="test1.php">
Name: <input type="text" name="name" id="name" />
<input type="submit" value="Submit" />
</form>
Now I have that execute my test1.php file which goes as follows:
<?php
$name = $_POST['name'];
?>
So all it is doing is getting the value from the HTML form. Now I have a second PHP file test2.php that needs to get the value from the first test1.php file $name and output it via an echo statement.
I'm new to PHP and am fine with using one PHP file to output values from an HTML form, but I don't know how to approach a second one.
I'm aware that you can use the include statement to carry over the variables and their values, but it didn't seem to work in my instance. I'm almost positive the issue is that I don't have test2.php actually being executed. And I don't know how to approach that. Any help is appreciated.
EDIT: This is all I want test2.php to do. $name has to be the same value as retrieved from the HTML form in test1.php
<?php
echo $name;
?>
Just use include your file test2.php inside test1.php:
<?php
$name = $_POST['name'];
include('test2.php');
?>
Whenever you include a file using either include() or require(), the file always gets "executed", so maybe there's something else wrong in you code.
EDIT
test1.php:
<?php
$name = $_POST['name'];
include('test2.php');
?>
test2.php:
<?php
echo $name;
?>
I would suggest starting a session in test1, assign the var $name to the session and then picking the session up on test2.
test1.php
session_start();
$name = filter_var($_POST['name'],FILTER_SANITIZE_STRING);
$_SESSION['test1']['name'] = $name;
test2.php
session_start();
$name = $_SESSION['test1']['name'];
Try that.
#bloodyKnuckles, Your assignment was left open ended because there are a number of ways you can accomplish what you're looking to do.
include('test2.php');
Is one option. Another would be
header("Location: test2.php");
exit();
Using the header option, $_SESSION variable would work. If test1.php had any HTML output, you could consider an AJAX call or urlencode() your string.
test1.php
echo 'Click Me';
test2.php
$name = $_GET['name'];
I'm guessing your assignment task was designed to demonstrate various ways to pass values from script to script.
Good Luck
Related
i am trying to make a page for form action handler using php
the the problem is that i want the action to be saved on that page
here's my form on index.php
<form method="get" onSubmit="return val()" action="han.php">
<label>Name:</label>
<input type="text" id="name" name="name" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
and here's my php code on han.php
<?php
$name = $_GET['name'];
echo "Your Name is:".$name;
?>
i need that name to be saved on han.php file like this every time i submit a name:
Your Name is: Brian
Your Name is: Jack
Your Name is: Daniel
Your Name is: Bob
What you can do is to create another file for saved names for example names.txt then in your han.php you could write this to save the name each time the form is submitted:
<?php
$name = $_GET['name'];
$file = fopen("names.txt","a");
echo fwrite($file,"$name, \n");
fclose($file);
return header('Location: index.php'); // to redirect to index.php page
?>
You can save them in the current session
<?php
session_start();
if(!isset($_SESSION['names']))
$_SESSION['names'] = array();
if(isset($_GET['name']))
array_push($_SESSION['names'], $_GET['name']);
if(isset($_SESSION['names']))
foreach($_SESSION['names'] as $name)
echo $name."<br>";
?>
It is not fully clear, what you mean by save, but here are some possible solutions:
1. Every name schould be saved "for ever" (big amount of names expected):
Use a Database like MySQL (see here)
2. The current name should be saved for a period of time:
Use session variables for this case
if(!isset($_SESSION['name']) {
$_SESSION['name'] = $_GET['name'];
$_SESSION['name'] = date();
}
you can also check befor this, if a period of time has expired and overwrite the name variable.
3. One or more names should be saved for all calls of the script (from any user):
You can use a file and save the names in this file:
create and write to file
read from file OR get whole file (file_get_contents)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Okay, my code is simple:
<?php include 'formvalidation.php';
echo $name; ?>
I want to make only the $name appear, but the whole 'formvalidation.php' shows up.
How can I fix that?
"I want that after I pressed the button, the function I had written will be excute to check the input, and then if the input is right, it'll redirect to another page, which can display the input."
If you wish to redirect after a form has been submitted and show a name afterwards, you will need to use sessions and a header.
Here is an example, (see comments in code) to be added inside formvalidation.php:
<?php
session_start();
// all other codes you already have
$name = "John"; // this is an example
// replace above with your POST variable
// such as $name = $_POST['name'];
$_SESSION['showname'] = $name;
header("Location: your_other_file.php");
exit; // keep this
N.B.: Make sure there is nothing else above <?php session_start(); such as your form, because this will throw a warning, stating Headers already sent...
your_other_file.php
<?php
session_start();
if(isset($_SESSION['showname'])){
$name = $_SESSION['showname'];
echo $name;
}
$name = "John"; // this is an example
Replace above in code with your POST variable.
Such as $name = $_POST['name']; as an example, since you have not provided additional code as to what your superglobal variable is for the name.
You can use session feature to call the variable instead of including a page, because it will indeed load an entire page. Please be more specific about your goal, perhaps we can help more by knowing more.
The whole HTML content of formvalidation.php will come up on the screen (so everything outside of <?php ?> just like all the outputs (echo etc ...) of the included file will come up on the screen.
You can avoid that by removing the outputs and only putting functions and variable declarations into the included file formvalidation.php.
The content of formvalidation.php could eg. be:
<?php
$name = 'test';
?>
It's going to execute whatever's in formvalidation.php. All the include function does is basically replace that line with the contents of your included file.
So if you don't want to show what's in that file - enclose the entire file in a function, or multiple functions. This is the way your library files (that you include) should be. Nothing in that file should be outside of a function definition.
Example (it's a crappy programming practice, but for example) -
formvalidation.php was ->
<?php
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
?>
Everything gets shown when I include it.
formvalidation.php now ->
<?php
function validate_form() {
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
}
?>
Now the way I've changed the file - nothing will get printed until I call validate_form();
Does that make sense?
When you use include 'someFile.php'; it's like you are taking all the contents of that file and pasting it in the code. For example if I had:
someFile.php
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
then:
include 'someFile.php';
echo $name;
Is the same as:
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
echo $name;
As others have said, that's what include does. I assume that you define $name inside the formvalidation.php file and that is why you are including it.
The right solution here would be to seperate the code in formvalidation.php into a function/class/file which does the data processing and another which creates the output. The you include/call only the first in the situation where you don't want the output
However, it is possible to capture the output and then discard it, using output buffering:
<?php
ob_start(); //Start capturing output
include 'formvalidation.php';
ob_end_clean(); // Stop capturing output and discard whatever was captured
echo $name;
?>
That said I would really not recommend this. The recommended way to fix this is to seperate your back-end code from your output generating code and only call what you actually need in any given situation.
Edit
An example of how to seperate the issues properly could be the following.
Lets assume your current formvalidation.php is something like:
<?php
$name = $_REQUEST['name'];
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
In a new file validator.php you could do:
<?php
class MyValidator{
public $name;
function read_data(){
$this->name = $_REQUEST['name'];
}
function validate(){
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
}
}
Then you change you formvalidtion.php to
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
$val->validate();
While the file you have above becomes
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
echo $val->name;
I have a simple question, with maybe not so simple of an answer. I want to be able to set a variable in one script and pass that value and variable to another script. Without passing it through the url, and having the ability to pass an array.
So I have index.php in there I have a variable
<?php
$myvariable = '';
<form action=editRecord.php>
do some form actions here and submit moving to editRecord.php
</form>
?>
Now in editRecord.php
<?php
header('Location: go back to index.php);
run functions and edit the Mysql DB
//Ok now here is where I want to assign a value to $myvariable and pass it back to index.php
?>
Is this possible? I am sorry for the amateurish question, but I am very green when it comes to php.
Thank You.
you can set it in the $_SESSION variable:
<?php
session_start();
$_SESSION["myVar"] = "blabla";
....
Of course you can store an array() in this variable too.
Just pass that information in the querystring. Then you can access it via $_GET. If it doesn't exist, just set the value to an empty string or whatever default value you want it to have.
// editRecord.php
<?php
// do db dtuff
header('Location: index.php?myvariable=somevalue');
?>
// index.php
<?php
$myvariable = (isset($_GET['myvariable'])) ? $_GET['myvariable'] : '';
<form action="editRecord.php" >
</form>
?>
You can also use session variables:
// editRecord.php
<?php
session_start();
// do db stuff
$_SESSION['myvariable'] = 'somevalue';
header('Location: index.php');
?>
// index.php
<?php
session_start();
$myvariable = (isset($_SESSION['myvariable'])) ? $_SESSION['myvariable'] : '';
<form action="editRecord.php" >
</form>
?>
You can use sessions, POST data, GET data, cookies and database data.
say i have a main file :
<form id="form1" name="form1" action="" method="post">
<input title="Masukkan kalimat disini" type="text" />
<?php
//main.php
$a = ...;
$b = ....;
?>
and included file
<?php
//included.php
include 'main.php';
?>
certainly included.php file will load all parts of main.php, so how to include some variable, such as include $a only, and not showing the textfield
Thanks.
If you want to include just a variable (or set of variables), they need to be in their own file. Ideally, you would also put them in a different scope (such as a class), so they're not cluttering up the global namespace.
E.g.,
config.php:
<?php
class Foo {
public $a = "I am a variable";
public $b = "I am also a variable";
const $c = "I am an immutable variable!";
}
?>
main.php:
<form id="form1" name="form1" action="" method="post">
<input title="Masukkan kalimat disini" type="text" />
<?php
#require_once "config.php";
?>
included.php:
<?php
#require_once "config.php";
?>
Programming is just driving your thoughts :)
So what i want to say that your question is how you can include just some part of an included file and my answer is that you can achieve that by doing a test each time the main file is included from withing this file to see if the file is included internally or not and you can be more precise in a way that you split your main file into block which are loaded due suitable variable
Take a look for this workaround and hope you will understand what i mean
Supposing we have the main file named main.php contains that contents
<?php
echo 'I am a java programmer';
echo 'I know also PHP very well';
echo 'When the jquery is my preferred toast !';
?>
now i have three external files that will include that file each file is specific for one of this 3 programming language
So i will create my 3 files in this way :
File : java.php
<?php
$iamjavadevelopper = 1;
include_once("main.php");
?>
File : phpfav.php
<?php
$iamphpdevelopper = 1;
include_once("main.php");
?>
File : jquery.php
<?php
$iamjquerydevelopper = 1;
include_once("main.php");
?>
and my main.php will be coded in this way
<?php
if(isset($iamjavadevelopper))
echo 'I am a java programmer';
if(isset($iamphpdevelopper))
echo 'I know also PHP very well';
if(isset($iamjquerydevelopper))
echo 'When the jquery is my preferred toast !';
?>
By this way each one of our three external files will show just a part of the included file :)
Hope that was clear and helpfull :) Any help needed i am just ready :)
Providing you are including the page, you will beable to use your set variables which are set on a different page (if that makes sense)
Global.inc.php
<?php
$Var_1 = "This will work";
$Var_2 = "Another set variable.";
?>
index.php
<?php
include "Global.inc.php";
echo $var_1; // This will output 'This will work'
?>
As you have included a file, all the contents will be usable; You just have to work with the variables that you want. There will be no performance hits for including a 300 line page, to use less than 50 lines of code for example.
Update:
Show within HTML Structures:
Inputs:
<input type='text' name='Name' value='<?php echo $Var_1; ?>'>
Text Box:
<textarea><?php echo $Var_1; ?></textarea>
When I post my form data:
<form action="layouts.php" method="post">
<input type="text" name="bgcolor">
<input type="submit" value="Submit" align="middle">
</form>
to a php page, "layouts.php", it returns the string, as expected.:
$bgcolor = $_POST['bgcolor'];
echo $bgcolor; //returns "red"
echo gettype($bgcolor); // returns "string"
But when I include "layouts.php" in another page it returns NULL.
<?php
include("php/layouts.php");
echo $bgcolor; //
echo gettype($bgcolor); //returns "NULL"
?>
How do I pass the variable to another page?
You'll have to use a session to have variables float around in between files like that.
It's quite simple to setup. In the beginning of each PHP file, you add this code to begin a session:
session_start();
You can store variables inside of a session like this:
$_SESSION['foo'] = 'bar';
And you can reference them across pages (make sure you run session_start() on all of the pages which will use sessions).
layouts.php
<?php
session_start();
$bgcolor = $_POST['bgcolor'];
$_SESSION['bgcolor'] = $bgcolor;
?>
new.php
<?php
session_start();
echo $_SESSION['bgcolor'];
?>
Give the form two action="" and see what happens. I just tried that on a script of mine and it worked fine.
A more proper way to solve this might exist, but that is an option.