use php variable in php file() - php

I have a web site that allows people to upload a csv file and then it loads it into a postgres database. uploading the file is fine and i capture the file name and location ../Data/Uploads/mycsv.csv as $_POST['fname'].
I'm trying to use this variable in $file=file($_POST['fname']) but cant get it to work however if i hard code it in as $file=file("../DATA/Uploads/mycsv.csv") it works. I have attached the code in question. Thanks in advance for any help
Also to clarify echo $_POST['fname']; returns ../DATA/Uploads/mycsv.csv, which is the same as the hard coded value.
please bear with me as im only relatively new to this. I have attached the 2 html forms being used as well. the top one passes the $fname variable containing the file name and path from the php code used to upload the file.
<Form Method="post" Action="../PHP/Loadcsv.php">
<input type="text" value="<?php echo htmlspecialchars($fname);?>" name="fname">
<br />
<Input Type="submit" Value="Continue">
</Form>
this is the php copy the csv into the database
<?PHP
if ($_POST['submit']) {
$file = file(printf($_POST['fname'])); //****doesnt work******
//$file = file("../DATA/Uploads/csv_trial1.csv"); //********This works******
$db = pg_connect("host=localhost dbname=blah user=me password=you");
pg_exec($db, "COPY personaldetails FROM stdin");
foreach ($file as $line) {
$tmp = explode(",", $line);
pg_put_line($db, sprintf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", $tmp[0], $tmp[1], $tmp[2], $tmp[3], $tmp[4], $tmp[5], $tmp[6], $tmp[7]));
}
pg_put_line($db, "\\.\n");
pg_end_copy($db);
?>
below is the html to run the above php.
<form id='form' method='post' action='' >
<input type="submit" name="submit" />
</form>
after running a whole lot of echo to find where the variable is reaching, i dont think it is reaching the inside of the if statement possibly due to the next use of post??
**update**
So after a little playing and bouncing ideas almost literally off my office walls.... i was on the right track and Devon was right too, my problem was the 2 post requests the answer was to have a php variable $filename = $_POST['fname']; to take the variable from the first form and put this into the input for the second form
<form id='form' method='post' action='' >
<input type="hidden" value="<?php echo htmlspecialchars($filename);?>" name="fname">
<input type="submit" name="submit" />
I'm sure there may be other ways to achieve this but at the moment it works.

I'm not sure where you came up with printf(), but any print or echo command will output the arguments to the browser and won't return it to the function at hand. You don't need to use anything special to use a variable as an argument. Just: file($_POST['fname']);
Printf specifically outputs a formatted string and returns the length of the string. So this is the equivalent of calling file(integer) where integer is the length of $_POST['fname']'s value.

Related

Using $_GET in the same file of text field that I GET from

Not sure if I titled it right, however my problem is stated below and I can't, for the life of me, figure it out.
In the same file, write a form consisting of a single text field and a
submit button. The “action” attribute to the form should be the same
page that the form is on (don’t hard code, use $_SERVER[‘PHP_SELF’]).
The form should send the contents of the text field via GET.
Upon submitting the form, you should be redirected to the same page,
but the URL should contain the string from the text field as a GET
request normally behaves.
<!-- I am supposed to pass the value of the text
field over to the url according to the question -->
<form action="questionThree.php" method="get">
<input type="text" name="text"><br>
<input type="submit">
</form>
Have trouble getting the code to display properly. They're supposed to be in html tags, although it's a php file.
Im baffled as to why you're passing it somewhere else however..
I think I have made sense from what you're asking so here goes...
On the submit input field add name="send"
then the HTML and PHP (for the same page) would be:
<form action="" method="get">
<input type="text"><br />
<input type="submit" name="send">
</form>
<?php
if (isset($_GET['send']))
{
$sentence = strtolower("My name is Justin and I am learning PHP programming and C++ programming");
function countWords($sentence)
{
//Using 'explode' to split words, thereby creating an array of these words
$wordsArr = explode(' ', $sentence);
$vals = array_count_values($wordsArr);
echo "<pre>";
print_r($vals);
echo "</pre>";
foreach ($vals as $key => $value)
{
echo "<b>" . $key . "</b> occurs " . $value . " times in this sentence <br/>";
}
}
countWords($sentence);
}
?>
Though I still see no purpose of the input text field?

Send form elements to image generation function

I'm completely up against a wall with this. I've been trying to learn PHP from tutorials to output two form inputs to my function to generate an image.
I've fixed an issue with my mixing up POST and GET but now my script doesn't function at all and I cant understand why - I'm sure this is hilds play for any developer but I'm in a bit over my head.
This is my app.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from text input.
$colour = $_POST['colour']; // data from colour radio.
}
?>
...
<form action="/app.php" method="post">
<input type="text" name="name"/>
<input name="colour" type="radio" value="1">Red<br>
<input name="colour" type="radio" value="2">Blue<br>
<input name="colour" type="radio" value="3">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print $data;?>" alt="">
Calls pngfile.php
<?php
require_once 'functions.php'; // Requires and includes do not need brackets.
$textdata = $_POST['data'];
$colourdata = $_POST['colour'];
process($textdata,$colourdata);
exit;
?>
Which in turn calls functions.php
<?php
/* Generate Image */
function process($textdata, $colourdata)
{
...
All of this was working perfectly before but the only change I have added is updating all elements to use POST and also adding in the code across the three files to add the selected colour to post. However with this tweaked code, I get no image output, even though I know my main image function works fine, so it must be my app.php and pngfile.php at fault.
Can anyone please give me some guidance on where I am going wrong?
Your problem is that you're sending this:
<img src="pngfile.php?data=<?php print $data;?>" alt="">
But your code is looking for this:
$textdata = $_POST['data'];
$colourdata = $_POST['colour'];
There's no post, and there's certainly no $_POST['colour']. There is a $_GET['data'] however; I think that's what you're looking for. Data passed as part of the URL is part of a GET request, and is available in $_GET. $_POST is for data sent with a POST request.

PHP Autofill or something?

I have seen many questions related to auto fill, but none of them worked for me. I'm not even sure if a solution to my problem lies in HTML or PHP. I am new in both of them and I'm still not used to them. I'm working on a simple chat app. What I have now is chat window, text field, and nick name field. Both of them pass the values to the text file (which is how I want this to work, no change here). Problem is that both these fields work as a form, and each time I submit, nick name field refreshes. What I would want is auto completing nickname field so it stays the same (it'd be the best if it stayed even after browser refreshes, but it will be okay if it only goes through the form submit)
code if needed:
PHP:
<?php
$action = $_GET["action"];
$myText = $_POST["mytext"];
$nick = $_POST["nick"];
if($action = "save") {
$targetFolder = "/var/www/html/xami/";
file_put_contents($targetFolder."htmlinput.txt", $nick.">".$myText);
}?>
HTML:
<form action="?action=save" name="myform" method="post">
<label for="nick">Nick:</label>
<input type=text id="nick" name="nick" placeholder="Nick" value="Name" required><br>
<input type=text name="mytext" placeholder="Text" required>
<input type="submit" value="Send.">
</form>
I was fooling around with autocomplete but no positive results.
I'm leaving post for tomorrow, I'll reply then.
Assuming your HTML is on a .php page you could have...
if(0<strlen($nick)){
echo "<input type=hidden id='nick' name='nick' value='$nick'>";
}else{
echo "<input type=text id='nick' name='nick' placeholder='Nick' value='Name' required><br>";
}
Or, use AJAX as #Rishi says.

Set Call to PHP Function, with POST Variables as Parameters, as HTML Form Action

I currently have an HTML file, with a form in it, that when submitted POSTs the form & calls a simple short PHP file that calls a function within another PHP file using the POSTed variables as parameters. The files are both below. What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
Ideally, this would set the call to the function:
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
as the form action. Does anyone know how/if this can be achieved?
HTML:
<FORM ID="FORM1" METHOD="POST" AUTOCOMPLETE="off" ACTION = "writeToDL.php">
<INPUT TYPE="hidden" NAME="Date" STYLE="WIDTH:0px; " MAXLENGTH="8" TITLE="Enter Date" Value="<?php $dt = date('Y-m-d'); echo $dt ?>"/>
<INPUT TYPE="text" NAME="Time" STYLE="WIDTH:70px; " MAXLENGTH="7" ONCHANGE="validateTime();" />
<SELECT NAME = "Result">
<OPTION VALUE = OK></OPTION>
<OPTION VALUE = C>C</OPTION>
</SELECT>
<SELECT NAME = "Participant" STYLE = "WIDTH: 187">
<OPTION SELECTED VALUE = "">Select...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$val = $value->get_id();
echo "<OPTION VALUE='",$val,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
<TEXTAREA NAME='Notes' COLS='28' ROWS='5'></TEXTAREA>
<INPUT TYPE="image" SRC = "images/submit.png" VALUE="Submit Participant"/>
</FORM>
PHP File:
<?php
include_once('database/PE.php');
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
?>
You COULD do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include_once('database/PE.php');
insert_PE(new PE($_POST['Date'],$_POST['Participant'],$_POST['Time'],$_POST['Result'],$_POST['Notes']));
} ?>
<html>
... rest of your page here ...
</html>
That way the PHP code only fires if an POST was actually performed. Some would suggest checking for the presence of a form field, but that's unreliable - you might change the form down the road and forget to update the if(). Checking the request method is guaranteed to be 100% reliable.
What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
No. The client only knows about URIs.
A URI can map to a PHP program. Multiple URIs can map to the same PHP program. You can use logic to determine what functions to run for a given URI. You can't avoid having that logic in your program.
One option is to put method="_the_main_php_file_containing_function_to_be_called_"
I hope it works fine.
I think you could use a hidden field on the form, and populate it with the name of the function you want to run on "destination.php". Then a switch statement on "destination.php" could pull the name of the function from POST variable.

Basic problem of getting values of my textbox

I am just trying to learn PHP and want to get the value of the textbox using $_post function, but its not working. I am using wamp 2.1 and the code is simple as below
<form method="POST" action="c:/wamp/www/test/try.php">
<input type="text" name="nco" size="1" maxlength="1" tabindex="1" value="2">
<input
tabindex="2" name="submitnoofcompanies" value="GO"
type="submit">
</form>
<?php
if (!isset($_POST['nco']))
{
$_POST['nco'] = "undefine";
}
$no=$_POST['nco'];
print($no);
However in no way I get the value of the textbox printed, it just prints undefined, please help me out.
You first assigned the word "undefine" to the variable $_POST['nco'].
You then assigned the value of the variable $_POST['nco'] (still "undefine" as you stored there) to the variable $no.
You then printed the value stored in the variable $no.
It should be clear that this will always print the word "undefine".
If you want to print the value of the textbox with the name nco, fill out the form with that textbox, and in the page that process the form,
echo $_POST['nco'];
...is all you do.
You need to setup a form or something similar in order to set the $_POST variables. See this short tutorial to see how it works. If you click the submit button, your $_POST variables will be set.
what for you are using this line $_POST['nco'] = "undefine"; } ..?
and please cross check whether you are using form method as post and make sure that your text name is nco ... or else use the below code it will work.
<?php
$no = $_POST['nco'];
echo $no;
?>
<form name='na' method='post' action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type='text' name='nco'>
</form>
thanks
Your action is wrong.
Change it to
action="try.php"

Categories