Issue Passing JS variable to PHP include file - php

I have a php file where I am using it to setup dynamically generated pages based on the input variables. It starts on and index.html page where the variables are gathered some of which are not simple strings but complex Google Earth objects. On the submit of that page it is posted to another page and you are redirected to the created file. The trouble is coming when I try to use that variable within the php include file that is used to generate the pages.How do i properly get a variable from this form and then pass it through to be able to use it on the new generated page. Here is what I am trying currently.
On the click of this button the variable flyto1view is set.
$("#flyto1").click(function(){
if (!flyto1view){
flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
$("#flyto1view1").val(flyto1view)
}
else {
ge.getView().setAbstractView(flyto1view);
}
});
Then from here I have tried setting the value to an hidden field but Im not sure if that kinda of variable has a value that can be set like that. Whats the best way to get this variable to here after post
<?
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address'])) {//if submit button clicked and name field is not empty
$flyto1view1 = $_POST['flyto1'];
$address = $_POST['address']; //the entered name
$l = $address{0}; // the first letter of the name
// Create the subdirectory:
// this creates the subdirectory, $l, if it does not already exists
// Note: this subdirectory is created in current directory that this php file is in.
if(!file_exists($l))
{
mkdir($l);
}
// End create directory
// Create the file:
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name
$fh = fopen($fileName, 'w') or die("can't open file");
// The html code:
// this will outpout: My name is (address) !
$str = "
<? php include ('template.php') ?>
";
fwrite($fh, $str);
fclose($fh);
// End create file
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
die();
}
// The form:
?>

Firstly. creating files from user input is pretty risky. Maybe this is only an abstract of your code but doing a mkdir from the first letter of the input without checking that the first letter is actually a letter and not a dot, slash, or other character isn't good practice.
Anyway, on to your question. I would probably use $_GET variables to pass to the second file. So in the second file you use <?php $_GET['foo'] ?> and on the first file you do:
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
You could also echo the variable into your template like so:
$str = '
<?php
$var = \'' . $flyto1view1 . '\';
include (\'template.php\')
?>';

Related

random(non- repeating) file generator on click of button in php

i want to display 5 php files content randomly but non repeating when clicked a button [NEXT] using php/javascript (that works in php desktop as well).
the code i used did displayed random web page on page load but i did came across repeated web page
this is the code i used for index.php file:
<?php
$RandomList = array();
$RandomList[] = "/review/review-a1.php";
$RandomList[] = "/review/review-a2.php";
$RandomList[] = "/review/review-a3.php";
$RandomList[] = "/review/review-a4.php";
readfile($_SERVER['DOCUMENT_ROOT'].$RandomList[rand(0,count($RandomList)-1)]);
?>
please suggest how to get non repeated files .
Just save paths you already used in the session:
//Read visited paths from session or create a new list.
//?? works only in PHP7+. Use isset()?: instead of ?? for previous versions
$visitedPaths = $_SESSION['visitedPaths'] ?? [];
//Your list, just slightly changed syntax. Same thing
$randomList = [
"/review/review-a1.php",
"/review/review-a2.php",
"/review/review-a3.php",
"/review/review-a4.php"
];
//Remove all paths that were already visited from the randomList
$randomList = array_diff($randomList, $visitedPaths);
//You need to check now if there are paths left
if (!empty($randomList)) {
//The user did not load all files, so we can show him the next one
//Use array_rand() rather than $array[rand(0, count($array) -1)]
$randomPath = $randomList[array_rand($randomList)];
readfile($_SERVER['DOCUMENT_ROOT'] . $randomPath);
//Now we need to save, that the user loaded this file
$visitedPaths[] = $randomPath;
//And we need to save the new list in the session
$_SESSION['visitedPaths'] = $visitedPaths;
} else {
//TODO: Add some logic in case all paths have been visited
}

If isnt set open txt name else

Essentially what I'm trying to achieve is, if the user hasn't selected one of the dropdown options, then a default .txt is opened, read and displayed. When the user does decide on a drop down option, it echos the users option. It works by getting the value of the option and setting that to a variable to set the open path.
Instead of opening my default which is 'example' when the user hasnt selected, it seems to pick one of the values at random and select it.
If the user hasnt selected an option, the default file path is p-changelog/example.txt
If the user has chosen and option, the file path becomes p-changelog/$userOp.txt (UserOp being the users option from the drop down).
if(!isset($_POST['userDateOp'])) {
$userOp = "example";
}else{
$userOp = $_POST['userDateOp'];
}
if(!isset($_POST['submit'])) {
$changelog = fopen("p-changelog/$userOp.txt", 'r');
$pageTxt = fread($changelog, 25000);
echo nl2br($pageTxt);
}
Entire Page: Code
I am new to PHP before criticising anything I've done.
userDateOp is always going to be set, as its posted every time.
What you are looking for is its value being empty
That function is
if(empty($_POST['userDateOp'])) {
You don't need to check if submit is set because you've already validated the existence of userDateOp. So this will only lead to an undefined variable notice for $changelog for default.
Your simplified script should be
if(!isset($_POST['userDateOp'])) {
$userOp = "example";
}else{
$userOp = $_POST['userDateOp'];
}
$changelog = fopen("p-changelog/$userOp.txt", 'r');
$pageTxt = fread($changelog, 25000);
echo nl2br($pageTxt);

PHP - Stop while loop after reading every single line from text file

I want the Code below to read individual line of text from dataFile.txt and show it in input field.
Problem is After reading first line from text document it shows all remaining lines of text from text file into input field. But on clicking submit it should show second line only then again on submitting it should show third line only, inside input field. please help.
<?php
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$array1 = array();
<form action="datagGet.php" method="get">
<input type="text" value="
<?php while ( $line = fgets($f, 100) )
{
$nl = mb_strtolower($line);
echo $nl;
if(isset($_GET['done']))
{
$nl++;
}
else
{
break;
}
}
?>"
name="someText">
<input type="submit" name="done" >
</form>
You have several problems with you code. And the first comment above points to many of the. Key is the fact that the $_GET['done'] is set for the form submit and therefore you will echo all the lines of the output. It never breaks.
Also there is the fact that you are opening the file for reading each submit of the form. Although I don't see a simple way around this unless you store the file contents between requests.
One possible option is to use 'file()' to read the entire contents into an array. And then use sessions to store which line has been read. Then on each submit, look for the index of the array from the session read; advance it by one read the file again and return that line. Wow wasteful. But okay for simple site.
so use file to get the lines in an array.
output the first line into the value.
store the next index to be read in the $_SESSION variable like $_SESSION['next_line'] = 1
then upon further submissions. read it all back in. look up the 'next_line', and output that line.
so, for example
$array = file('your file name');
$output = $array[0];
if (isset($_SESSION['next_line']))
$_SESSION['next_line'] = intval($_SESSION['next_line']) + 1;
else
$_SESSION['next_line'] = 1;//prime the pump
echo the form with $output
then rinse and repeat. e.g. read, get output (next_line) with file, set $_session = next_line + 1; render output in form.
ps. some extra notes
* of course you'll need to start session on each request.
* you'll need to check if the $_SESSION['next_line'] is set. if not, set it to 1 (prime it)

Get user input from form, write to text file using php

As part of a subscriber acquisition I am looking to grab user entered data from a html form and write it to a tab delimited text file using php.The data written needs to be separated by tabs and appended below other data.
After clicking subscribe on the form I would like it to remove the form and display a small message like "thanks for subscribing" in the div.
This will be on a wordpress blog and contained within a popup.
Below are the specific details. Any help is much appreciated.
The Variables/inputs are
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$leader is a two option radio button with 'yes' and 'no' as the values.
$country is a drop down with 40 or so countries.
All other values are text inputs.
I have all the basic form code done and ready except action, all I really need to know how to do is:
How to write to a tab delimited text file using php and swap out the form after submitting with a thank you message?
Thanks again for all the help.
// the name of the file you're writing to
$myFile = "data.txt";
// opens the file for appending (file must already exist)
$fh = fopen($myFile, 'a');
// Makes a CSV list of your post data
$comma_delmited_list = implode(",", $_POST) . "\n";
// Write to the file
fwrite($fh, $comma_delmited_list);
// You're done
fclose($fh);
replace the , in the impode with \t for tabs
Open file in append mode
$fp = fopen('./myfile.dat', "a+");
And put all your data there, tab separated. Use new line at the end.
fwrite($fp, $variable1."\t".$variable2."\t".$variable3."\r\n");
Close your file
fclose($fp);
// format the data
$data = $Fname . "\t" . $email . "\t" . $leader ."\t" . $industry . "\t" . $country . "\t" . $zip;
// write the data to the file
file_put_contents('/path/to/your/file.txt', $data, FILE_APPEND);
// send the user to the new page
header("Location: http://path/to/your/thankyou/page.html");
exit();
By using the header() function to redirect the browser you avoid problems with the user reloading the page and resubmitting their data.
To swap out the form is relatively easy. Make sure you set the action of the form to the same page. Just wrap the form inside a "if (!isset($_POST['Fname']))" condition. Put whatever content you want to show after the form has been posted inside the "else{}" part. So, if the form is posted, the content in the "else" clause will be shown; if the form isn't posted, the content of the "if (!isset($_POST['Fname']))", which is the form itself will be shown. You don't need another file to make it work.
To write the POSTed values in a text file, just follow any of the methods other people have mentioned above.
This is the best example with fwrite() you can use only 3 parameters at most but by appending a "." you can use as much variables as you want.
if isset($_POST['submit']){
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$openFile = fopen("myfile.ext",'a');
$data = "\t"."{$Fname}";
$data .= "\t"."{$email}";
$data .= "\t"."{$leader}";
$data .= "\t"."{$industry}";
$data .= "\t"."{$country}";
$data .= "\t"."{$zip}";
fwrite($openFile,$data);
fclose($openFile);
}
Very very simple:
Form data will be collected and stored in $var
data in $var will be written to filename.txt
\n will add a new line.
File Append Disallows to overwrite the file
<?php
$var = $_POST['fieldname'];
file_put_contents("filename.txt", $var . "\n", FILE_APPEND);
exit();
?>

PHP - include a php file and also send query parameters

I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.
if(condition here){
include "myFile.php?id='$someVar'";
}
Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.
Can someone please tell me how to achieve this?
Thanks.
Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).
You could do something like this to achieve the effect you are after:
$_GET['id']=$somevar;
include('myFile.php');
However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).
In this case, why not turn it into a regular function, included once and called multiple times?
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
If you are going to write this include manually in the PHP file - the answer of Daff is perfect.
Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:
<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
// find ? if available
$pos_incl = strpos($phpinclude, '?');
if ($pos_incl !== FALSE)
{
// divide the string in two part, before ? and after
// after ? - the query string
$qry_string = substr($phpinclude, $pos_incl+1);
// before ? - the real name of the file to be included
$phpinclude = substr($phpinclude, 0, $pos_incl);
// transform to array with & as divisor
$arr_qstr = explode('&',$qry_string);
// in $arr_qstr you should have a result like this:
// ('id=123', 'active=no', ...)
foreach ($arr_qstr as $param_value) {
// for each element in above array, split to variable name and its value
list($qstr_name, $qstr_value) = explode('=', $param_value);
// $qstr_name will hold the name of the variable we need - 'id', 'active', ...
// $qstr_value - the corresponding value
// $$qstr_name - this construction creates variable variable
// this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
// the second iteration will give you variable $active and so on
$$qstr_name = $qstr_value;
}
}
// now it's time to include the real php file
// all necessary variables are already defined and will be in the same scope of included file
include($phpinclude);
}
?>
I'm using this variable variable construction very often.
The simplest way to do this is like this
index.php
<?php $active = 'home'; include 'second.php'; ?>
second.php
<?php echo $active; ?>
You can share variables since you are including 2 files by using "include"
In the file you include, wrap the html in a function.
<?php function($myVar) {?>
<div>
<?php echo $myVar; ?>
</div>
<?php } ?>
In the file where you want it to be included, include the file and then call the function with the parameters you want.
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)
In your myFile.php you'd have
<?php
$MySomeVAR = $_SESSION['SomeVar'];
?>
And in the calling file
<?php
session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;
?>
Would this circumvent the "suggested" need to Functionize the whole process?
I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:
<?php
include('references.php');`
?>
User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:
<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>
I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.
<?php
function include_get_params($file) {
$parts = explode('?', $file);
if (isset($parts[1])) {
parse_str($parts[1], $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($parts[0]);
}
?>
The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.
Here is an example on the form page when called:
<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
include_get_params(DIR .'references.php?count='. $i);
} else {
break;
}
}
?>
Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.
You can use $GLOBALS to solve this issue as well.
$myvar = "Hey";
include ("test.php");
echo $GLOBALS["myvar"];
If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:
one.php:
<?php
$vars = array('stack','exchange','.com');
include('two.php'); /*----- "paste" contents of two.php */
testFunction(); /*----- execute imported function */
?>
two.php:
<?php
function testFunction(){
global $vars; /*----- vars declared inside func! */
echo $vars[0].$vars[1].$vars[2];
}
?>
Try this also
we can have a function inside the included file then we can call the function with parametrs.
our file for include is test.php
<?php
function testWithParams($param1, $param2, $moreParam = ''){
echo $param1;
}
then we can include the file and call the function with our parameters as a variables or directly
index.php
<?php
include('test.php');
$var1 = 'Hi how are you?';
$var2 = [1,2,3,4,5];
testWithParams($var1, $var2);
Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :
if(condition){
$someVar=someValue;
include "myFile.php";
}
As long as the variable is named $someVar in the myFile.php
I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:
<?php
header("Location: http://localhost/planner/layout.php?page=dashboard");
exit();
?>

Categories