how to properly handle php undefined index - php

I have a script where a user can input some text, view it, and change it. It looks like that:
if(isset($_POST['change']))
{
$text = $_POST['text'];
echo"
<form method='post' action='datei.php'>
<p>You wrote: $text</p>
<input name='text' type='hidden' size='21' value='$text'>
<input name='submit' type='submit' value='Change'>
</form>";
}else
{
$text = $_POST['text'];
echo"
<form method='post' action='datei.php'>
<p>Write some additional Information</p>
<input name='text' type='text' size='21' value='$text'>
<input name='change' type='submit' value='View'>
</form>";
}
When I load the page the first time, I get the following notification
Notice: Undefined index: text in ...
I found two solutions how to fix the problem:
Ignore Notifications
Use isset()
If I would use isset I would have to change two lines from above to:
if(isset($_POST['text']))$text = $_POST['text'];
and
<input name='text' type='text' size='21' value='"; if(isset($_POST['text'])) echo $text; echo"'>
Since my original form has more then 20 input fields, this would make the code less readable and more likly for erros when editing the code. Is there any better way to get around the notification that I currently miss?

First be sure that you define all the variables before using them, like
$text = false;
Plus, checking that a variable is set is always a good practice. Not to mention that you shouldn't be using $_POST directly.

Related

After adding into script echo file_get_contents(myfile.php) some parts of script myfile.php won't work. Any idea why?

echo "<tr><td colspan='5' id='row1-info' class='emarNote'>
<div id='odgovor'>
<form name='form' action='insertodg.php' method='post' onsubmit='return validateForm()' class='odgovor-form frame inbtn rlarge'>
<input type='text' name='odgovor' placeholder='Odgovorite...' class='odgovor-input'/>
<input type='hidden' name='id' value='$id' />
<input name='submitodgovor' type='submit' value='Go' class='odgovor-btn' />
</form>
</div>
</td></tr>";
}
echo "</table>";
The script perfectly work now, but when i exclude whole form outside, and call with file_get_contents() it give me an error - something like myfieldId can not be null, and is not. I really have no idea what is that?
So if I make like this,
echo "<tr><td colspan='5' id='row1-info' class='emarNote'>
echo file_get_contents ("myfile.php");
echo "</td></tr>";
FIrst error is Undefined index: user in C:\wamp\www\insertfile.php on line 26.
This code is from insertfile.php
$sql="INSERT INTO answers
SET answer = '$_POST[answer]',
user = '$_POST[user]',
questionId = (SELECT id FROM questions WHERE id = '$_POST[id]');
";
And second error is Column questionId cannot be null. But when that file wasn't excluded, everything working, and column questionId has some values.
The proper way to include PHP code to execute it is the include construct and related statements:
The include statement includes and evaluates the specified file.
You are using file_get_contents():
Reads entire file into a string
... and then echo:
Output one or more strings
Thus you no longer execute PHP code. You just print strings.

Passing data between PHP webpages from a dynamically generated list

I have a PHP code which generates a dynamic list inside a form like the following, note that the list is built dynamically from database:
echo '<form name="List" action="checkList.php" method="post">';
while($rows=mysqli_fetch_array($sql))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='hidden' name='SessionID' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
What I need is to POST the data corresponding to the user choice when he clicks on the button for that row to another page.
If we use hyperlinks with query strings there will be no problem as I'll receive the data from the other page using a GET request and the hyperlinks would be static when showed to the user.
Also I need to obtain the user input from a textbox which is only possible with POST request.
Simply from the other page (checkList.php) I need these data for further processing:
$SessionID=$_POST['SessionID'];
$Code=$_POST['code'];
As I have a while loop that generates the fields, I always receive the last entry form the database and not the one corresponding to the line (row) that the user chosed from the LIST.
I'm going to recommend that you clean up the names of variables so that your code can
at least tell us what it's supposed to do. It should be rare that someone looks at your code
and has a lot of trouble trying to see what you're trying to accomplish :P, ESPECIALLY when you need help with something ;]. I'm going to try some things and hope that it makes doing what you want easier to comprehend and perhaps get you your answer.
It's good to try your best to not echo large amounts of HTML unnecessarily within a script , so firstly I'm going to remove the
echos from where they are not necessary.
Secondly, I'm going to use a mysql function that returns an easier to process result.
$user = mysqli_fetch_assoc($sql)
Third, I don't know if form having a name actually does anything for the backend or frontend of php, so I'm
just going to remove some of the extra crust that you have floating around that is either invalid HTML
or just doesn't add any value to what you're trying to do as you've presented it to us.
And yes, we "note" that you're building something from the database because the code looks like it does =P.
I'm also sooo sad seeing no recommendations from the other answers in regard to coding style or anything in regard to echoing html like this :(.
<?php while($user = mysqli_fetch_assoc($sql)): ?>
<form action="checkList.php" method="post">
<input type='password' name='code' value='<?php echo $user['code'] ?>' />
<input type='hidden' name='SessionID' value='<?php echo $user['id'] //Whatever you named the field that goes here ?>' />
<input type='submit' value='Take Survey' />
</form>
<?php endwhile; ?>
i not sure this is correct
echo '<form name="List" method="post">';
while($rows=mysqli_fetch_array($result))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='button' value='Take Survey' onclick=show($rows[0])>";
echo "<br>";
}
and javascript
<script>
function show(id)
{
alert(id);
window.location="checkList.php?id="+id;
}
</script>
On checkList.php
$id=$_GET['id'];
echo $id;
You can just check in checkList.php whether $_POST['code'] exists and if exists retrieve $_POST['SessionID'] which will be generated from database. But one thing, if You have all hidden fields in one form, they all will be sent, so You need to think how to correct that - maybe seperate forms for each hidden field, submit button and maybe other POST fields.
And afterwards, You will be able to get data in the way You need - $SessionID=$_POST['SessionID'];
I suppose it is the easiest way to solve that.
You can try something like this:
while($rows=mysqli_fetch_array($sql))
{
$index = 1;
echo "<input type='password' name='code' id='code'>";
//Attach $index with SessionID
echo "<input type='hidden' name='SessionID_$index' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
On checkList.php
<?php
$num = explode('_', $_POST['SessionID']);
$num = $num[1];
//in $num you will get the number of row where you can perform action
?>
$form = 1;
while($rows=mysqli_fetch_array($sql))
{
echo '<form name="List_$form" action="checkList.php" method="post">';
echo "<input type='password' name='code' id='code_$form'>";
echo "<input type='hidden' name='SessionID' id='SessionID_$form' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
echo '</form>';
$form++;
}

im trying to add an if else statement for when the form is posted and wether or not the user include files or not?

how would I do an if / else statement for such? the user has the option of adding images or not. if the add images, i want the if to run and if they dont I want the else to run because depending on whether or not the add an image they will have two different end.
if (isset($_POST['formsubmitted'])) {
if (isset($_POST['name'])){ }else{ }
if (isset($_POST['state'])){ }else{ }
if (isset($_FILES['images']['name'])) { echo 'images'; exit;} else {echo 'no images'; exit;}
} #end main form submitted
if (isset($_FILES['images']['name'])) dosnt work because as of now even when no images are submitted it still says images submitted.
the html file fields are:
<form>
<input type='file' name='images[]' id=''>
<input type='file' name='images[]' id=''>
<input type='file' name='images[]' id=''>
<input type = "submit">
</form>
You should try this
Submit.php
<pre>
<?php
// those index are empty the array filter remove this
echo "without filter"."<br>";
print_r($_FILES['images']['name']);
echo "filter"."<br>";
$usersFileUpload = array_filter($_FILES['images']['name']);
print_r($usersFileUpload);
$usersFileUploadCount = count($usersFileUpload);
for($i=0;$i<=$usersFileUploadCount;$i++){
echo $usersFileUpload[$i]."<br>";
// insert Table
}
?>
HtmlForm.php
<form action="submit.php" method="post" enctype="multipart/form-data" name="images">
<input type='file' name='images[]' id=''><br />
<input type='file' name='images[]' id=''><br />
<input type='file' name='images[]' id=''>
<input name="" type="submit" />
</form>
See the image for verification 1
See the image for verification 2
im not sure i understand, i think you are trying to do this.
if (isset($_FILES['name']) && isset($_FILES['images']))
Try checking to see if $_FILES['images']['error'][$x] is equal to 4. If I recall correctly, that's indicative of an error with the upload.
Obviously, do that for each iteration of your images uploader, so essentially replace $x with the key for the uploader array.
Remember, an empty array is still a set array.
See: http://uk3.php.net/manual/en/features.file-upload.errors.php
Also: http://uk3.php.net/manual/en/features.file-upload.php <-- Manuals. Handy!
Try this
if($_FILES['your-name-file']['error'] == 4) {
//process your error
}
It's work for me!

Problem in sending values between pages in PHP

I want to send data from one page to the other via a form in PHP. In the initial page I have included the following PHP script that generates an input form with hidden fields. The names of these hidden fields are generated by the PHP:
<?php
echo "<form class='available-form' name='available_os' method='get' action='process-results.php'>";
echo "<input type='hidden' name='$software'></input>";
echo "<input type='hidden' name='$version'></input>";
echo "<input type='submit' name='available-button' value='Find Available Libraries for this Software'></input>";
echo "</form>";
?>
In the second page, named process-results.php, I would like to get the names of these hidden fields via the $_GET method but of course using $_GET[$software] and $_GET[$version] wouldn't work...Can someone tell me if there is a solution to this issue or if there is a better alternative? Thanks in advance
Instead of
"<input type='hidden' name='$software'></input>";
you should use
"<input type='hidden' name='software' value='".$software."'></input>";
for each. This way, you can use $_GET['software'] to retrieve the value. Do this for each of your hidden inputs.
I think you may want something like:
<form ... >
<input type="hidden" name="software" value="<?php echo $software ?>" />
<input type="hidden" name="version" value="<?php echo $version ?>" />
</form>
and then
$_GET['software'];
$_GET['version'];
I'm not sure what you're trying to accomplish, but this looks odd to me. Isn't the below code more of what you're looking for?
<?php
echo "<form class='available-form' name='available_os' method='get' action='process-results.php'>";
echo "<input type='hidden' name='software' value='$software'></input>";
echo "<input type='hidden' name='version' value='$version'></input>";
echo "<input type='submit' name='available-button' value='Find Available Libraries for this Software'></input>";
echo "</form>";
?>
That way you will get a query string in form of ?software=yoursoftwarename&version=yourversion and it will be available via $_GET["software"] and $_GET["version"] on the next page.
You could iterate over each of the items in the $_GET array on process-results.php. The problem is that the keys for the value will be whatever $software and $version are set to on the first page. Try something like this:
foreach($_GET as $key=>$string) {
// Do stuff with them
}
Add
enctype="multipart/form-data"
To the tag... so it looks like
<form enctype="multipart/form-data" method......
If you really need to have the dollar-sign inside the name, escape it:
echo "<input type='hidden' name='\$software'>";
or put the string in single-quotes:
echo '<input type="hidden" name="$software">';
Otherwise PHP is looking for a variable named "$software", if you look inside the browser-source you will see that the name-attributes are empty(except you're having those variables defined somewhere).

problems with htmlspecialchars

I am generating links from the following php code. The links appear in the browser, and the generated html code seems fine, however the links are not click-able. I have tested this in IE and FF, and tried to see with FireBug to no avail.
The code to generate my form
$uploadhtml = htmlspecialchars(json_encode("<form action='up.php' method='post'
enctype='multipart/form-data'>
<label for='file'>Filename:</label>
<input type='file' name='file' id='file'/>
<br />
<input type='hidden' name='pk' value='".$pk."'>
<input type='hidden' name='username' value='".$USERNAME."'>
<input type='submit' name='submit' value='Submit' onclick=\"setTimeout(function() {
updateByPk('Layer2', '".$pk."', '".$brand."', '".$pg."'); } ),1250);\" />
</form>"), ENT_QUOTES);
The resultant html code:
<a onclick="makewindows('"<form action='up.php' method='
post'\r\nenctype='multipart\/form-data'>\r\n<label for='
`file'>Filename:<\/label>\r\n<input type='file' name='file' id='`file'\/> \r\n<br \/>\r\n<input type='hidden' name='pk' value='
380118179930'>\r\n<input type='hidden' name='username' value='
janmaybach'>\r\n<input type='submit' name='submit' value='
Submit' onclick=\"setTimeout(function() { updateByPk('Layer2',
'380118179930', 'Ed Hardy', '1'); } ),1250);\"
\/>\r\n<\/form>"'); return false;" href="#">Upload files</a>
I guess it's a JavaScript error, but I don't know how to pinpoint it?
edit: The html code without ENT_QUOTES:
<a href="#" onclick="makewindows('"<form action='up.php' method='post'\r
\nenctype='multipart\/form-data'>\r\n<label for='file'>Filename:<\/label>\r\n<input
type='file' name='file' id='file'\/> \r\n<br \/>\r\n<input type='hidden' name='pk'
value='380118185183'>\r\n<input type='hidden' name='username' value='janmaybach'>\r
\n<input type='submit' name='submit' value='Submit' onclick=\"setTimeout(function()
{ updateByPk('Layer2', '380118185183', 'Ed Hardy', '1'); } ),1250);\"
\/>\r\n<\/form>"'); return false;">Upload files</a>
It still is not clickable..., everything seems to be quoted correctly?
When I try without htmlspecial chars, the following html output is produced:
<input type='submit' name='submit' value='Submit' onclick=" settimeout(function()="" {="" updatebypk(="" layer2="" 380118179930="" ed="" hardy="" ,="" 1="" );="" }="" ),1250);="">
'); return false;">Upload files</a>
As said in the comment to the question, this is absolutely horrendous code, and you're suffering the consequences. The main problem is the number of code levels: server code that renders Javascript, that renders HTML - and difference escapes at every level and interfere with each other.
To improve the situation, have a separate PHP page with the form and have your popup link open that page - no Javascript required. If you really want to avoid having that separate page at all costs, at least have the Javascript function that generates the form in the header of the page (non-dynamic) and have the link contain only a call to that function with your variables as parameters.
The parameter in your makewindows function ist not quoted. Your quotes are escaped (%#39). Replace it with ' and you're done.
Your ENT_QUOTES flag is screwing up the output. If you look closely you'll see that there are no actual quotes in the HTML output - just escaped entities. Make a test that doesn't use htmlspecialchars(). You should escape the quotes with a backslash OR better still add the javascript functionality unobtrusively. jQuery might help you to achieve that http://jquery.com

Categories