Hiding a paragraph if input is empty - php

I have a small function that grabs the input values from my html page and puts them through a php function that will display them in a list. My goal is that if a field is left blank, the PHP script doesn't echo anything so that it would skip that instance entirely. It's probably better to show you than just talk of course:
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form method="POST" action="test3.php" name="form">
<p>Please enter your name:</p>
<input type="text" name="1"></input>
<br />
<input type="text" name="2"></input>
<br />
<input type="text" name="3"></input>
<br />
<input type="text" name="4"></input>
<br />
<input type="text" name="5"></input>
<br />
<input type="submit" value="Submit" name="subButton" tabindex="50"></input>
</form>
</body>
</html>
PHP
function callNames(){
$body;
for($name = 1; $name <= 6; $name++){
if($name <= 5){
echo "Your name is " . $_POST[$name] . ".<br />";
}
elseif($name =? ){
?;
}
else {
echo "Your out of names!";
}
};
}
callNames();
I left the elseif function blank, as I thought that is where my solution would go. In other words, if you put in a name for everything but field 3, it would only echo "Your name is " 4 times but not leave an extra break where it would have been. Would I not use an elseif to solve this?

First off, as Fred -ii pointed out in the comments, in PHP field names cannot start with a number, but if they could here is how you would do it:
function callNames(){
$body;
for($name = 1; $name < 6; $name++){
if(isset($_POST[$name])){
echo "Your name is " . $_POST[$name] . ".<br />";
}
}
echo 'You are out of names!';
}
However, this assumes that the post variables go up sequentially until there are no more names.
If you explain what this is for, maybe someone can provide a better way to tackle the problem all together.
P.s the body variable seems unused?

Have you tried adding a condition that looks for $_POST[$name] length > 0 or that looks for $_POST[$name] != '';
function callNames(){
$body;
for($name = 1; $name <= 6; $name++){
if($name <= 5){
if ( $_POST[$name] != '' ) {
echo "Your name is " . $_POST[$name] . ".<br />";
}
}
elseif($name =? ){
?;
}
else {
echo "Your out of names!";
}
};
}
callNames();
You can even merge the two conditions in one with &&

function callNames(){
if ($_POST['name'] != ""){
echo "Your name is " . $_POST[$name] . ".<br />";
}
elseif($_POST['name'] == "?"){
echo "?";
}
else {
echo "Your out of names!";
}
}

Related

My form is not working, please do tell me where it went wrong(PHP validation)

I would like to know where in my code the form went wrong.
<?php
if(isset($_POST['submit'])) {
$arrayName = array("TeacherA", "TeacherB", "TeacherC" , "TeacherD", "TeacherE");
$minimum = 5;
$maximum = 10;
$name = $_POST['yourName'];
$email = $_POST['yourEmail'];
if(strlen($name) < $minimum) {
echo "Your name should be longer than 5 characters";
}
if(strlen($name) > $maximum) {
echo "Your name should not be longer than 10 characters";
}
if(!in_array($name,$arrayName)){
echo "Please do register with us before you can login";
} else {
echo "Welcome!";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blank</title>
</head>
<body>
<form action="form.php" method="post">
<label>Your Name: </label>
<input type="text" name="yourName"> <br>
<label for="">Your E mail:</label>
<input type="email" name="yourEmail" id=""><br>
<!-- <textarea name="yourMessage" id="" cols="30" rows="10"></textarea><br> -->
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
I run through the localhost, however, I could not get result that I wanted.
The result that I wanted is if I didn't enter the names in the "Your Name" field, then it should show the result:
Please do register with us before you can login
if the the "Your Name" field is empty, then its strlen($name) should be 0 and the first if statement is true and it will show Your name should be longer than 5 characters
you can try this :
<?php
if (isset($_POST['submit'])) {
$arrayName = array("TeacherA", "TeacherB", "TeacherC", "TeacherD", "TeacherE");
$minimum = 5;
$maximum = 10;
$name = $_POST['yourName'];
$email = $_POST['yourEmail'];
if (empty($name)) {
echo "Please do register with us before you can login";
} else {
if (strlen($name) < $minimum) {
echo "Your name should be longer than 5 characters";
} else {
if (strlen($name) > $maximum) {
echo "Your name should be less than 10 characters";
} else {
if (in_array($name, $arrayName)) {
echo "Welcome!";
} else {
echo "Your login is not correct";
}
}
}
}
}
?>
i used empty() to test if the field empty
and i used if-else statements because i want the script to stop if it founds a 'true' condition
in your script you can use return; but that will exit the rest of your script
have a nice code :)
Try this:
if(!isset($name)){
echo "Please do register with us before you can login";
}
else{
echo "Welcome";
}
And also:
<input type="text" name="yourName" required>

User Input from HTML form being cut off

We have an HTML form that takes in user input for an application, and uses PHP to process and send it to HR. The issue is it cutting off the text in the final result (picture below). There are no text limits set anywhere. Any help or ideas would be greatly appreciated.
Parts being cut off:
Cut Off
The form declaration and code for the fields being cut off:
<form id="application" name="application" method="post" action="sendresults.php" align="left">
<p>Work Performed<br />
<label>
<textarea name="workperform1" id="workperform1" tabindex="62" cols="50" rows="3"></textarea>
</label>
</p>
<p>Reason for Leaving<br />
<label>
<input name="reasonleaving1" type="text" onkeypress="return noenter()" id="reasonleaving1" tabindex="63"size="66" />
</label>
<br />
</p>
The PHP code:
<?php session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Results</title>
</head>
<body>
<?php
//--------------------------Set these paramaters--------------------------
$subject = 'Application for Employment';
$emailadd = 'blahblah#randomemail.org';
// Where to redirect after form is processed.
$url = 'http://www.randomwebsitename/random.html';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
die('The code you entered was incorrect. Go back and try again.');
}
foreach( $_POST as $key => $value ){
if ($req == '1'){
if( $value == '' ){
echo "$key is empty";
die;
}
}
$j = strlen($key);
if( $j >= 20 ) {
echo "Name of form element $key cannot be longer than 20 characters";
die;
}
$j = 20 - $j;
for ($i = 1; $i <= $j; $i++){
$space .= ' ';
}
$value = str_replace('\n', "$line", $value);
$conc = "{$key}:$space{$value}$line";
$text .= $conc;
$space = ' ';
}
mail($emailadd, $subject, $text, 'From: '.$emailadd.'');
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
?>
</body>
</html>

SongOrganzier Isnt Adding Song To txt File or Html Table

Problem:
Create a Song Organizer script that stores songs in a text file. Include functionality that allows users to view the song list and prevents the same song name from being entered twice. Also, include code that sorts the songs by name, deletes duplicate entries, and randomizes the song list with the shuffle() function.
How Come my code isnt adding the song to the txt file or the table?
My Solution - > Broken, song isnt being appending to song list
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
"http://w...content-available-to-author-only...3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://w...content-available-to-author-only...3.org/1999/xhtml">
<head>
<title>PHP Code Blocks</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Song Organizer</h1>
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if (isset($_GET['action'])) {
if ((file_exists("SongOrganizer/songs.txt"))
&& (filesize("SongOrganizer/songs.txt")
!= 0)) {
$SongArray = file(
"SongOrganizer/songs.txt");
switch ($_GET['action']) {
case 'Remove Duplicates':
$SongArray = array_unique($SongArray);
$SongArray = array_values($SongArray);
break;
case 'Sort Ascending':
sort($SongArray);
break;
case ’Shuffle’:
shuffle($SongArray);
break;
} // End of the switch statement
if (count($SongArray)>0) {
$NewSongs = implode($SongArray);
$SongStore = fopen("SongOrganizer/songs.txt","wb");
if ($SongStore === false)
echo "There was an error updating the song file\n";
else {
fwrite($SongStore, $NewSongs);
fclose($SongStore);
}
}
else
unlink("SongOrganizer/songs.txt");
}
}
if (isset($_POST['submit'])) {
$SongToAdd = stripslashes(
$_POST['SongName']) . "\n";
$ExistingSongs = array();
if (file_exists("SongOrganizer/songs.txt")
&& filesize("SongOrganizer/songs.txt")
> 0) {
$ExistingSongs = file(
"SongOrganizer/songs.txt");
if (isset($_POST['submit'])) {
$SongToAdd = stripslashes($_POST['SongName']) . "\n";
$ExistingSongs = array();
if (file_exists("SongOrganizer/songs.txt")
&& filesize("SongOrganizer/songs.txt")> 0) {
$ExistingSongs = file("SongOrganizer/songs.txt");
}
}
}
}
if ((!file_exists("SongOrganizer/songs.txt"))
|| (filesize("SongOrganizer/songs.txt")
== 0))
echo "<p>There are no songs in the
list.</p>\n";
else {
$SongArray = file(
"SongOrganizer/songs.txt");
echo "<table border=\"1\" width=\"100%\"
style=\"background-color:lightgray\">\n";
foreach ($SongArray as $Song) {
echo "<tr>\n";
echo "<td>" . htmlentities($Song) .
"</td>";
echo "</tr>\n";
}
echo "</table>\n";
}
?>
<p>
<a href="SongOrganizer.php?action=Sort%20Ascending">
Sort Song List</a><br />
<a href="SongOrganizer.php?action=Remove%20Duplicates">
Remove Duplicate Songs</a><br />
<a href="SongOrganizer.php?action=Shuffl e">
Randomize Song list</a><br />
</p>
<form action="SongOrganizer.php" method="post">
<p>Add a New Song</p>
<p>Song Name: <input type="text" name="SongName"
/></p>
<p><input type="submit" name="submit"
value="Add Song to List" />
<input type="reset" name="reset"
value="Reset Song Name" /></p>
</form>
</body>
</html>
I just ran your code locally. You're never sending an action in the form so none of the code is executing.
Inside the form, add something like:
<input type="hidden" name="action" value="literally anything can go here" />

preg_match help from an input box [duplicate]

This question already has answers here:
php date validation
(13 answers)
Closed 9 years ago.
I need to validate a Date from an input box.
The regular expression is fine but that is about it.
First where in the scope does it go, and second can you help make this work?
When it validates I dont want it to echo anything and when it doesnt I would like it to
tell the user that they must enter it in mm/dd/yyyy format. If you can do this in an alert box that would be even better! Thank you fellow developers!!! The COMPLETE code follows the tag. Youll see my preg_match is commented out. Thank you fellow developers!!!
$input = '<input value="Date" type="text" name="date">';
if (preg_match('/^(|(0[1-9])|(1[0-2]))\/((0… $input)) {
echo "";
} else {
echo "You must Re-enter date in mm/dd/yyyy format.";
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<embed src="Songs/nature.mp3" width=10 height=10 autostart=true repeat=true loop=true></embed>
<title>Post Song</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Post New Song</h1>
<hr />
<br />
<body background="Songs/back.jpg">
<form action= "Postsong.php" method="POST">
<span style="font-weight:bold">Song:</span>
<input value="" type="text" name="song" />
<span style="font-weight:bold">Artist Name:</span>
<input value="" type="text" name="name" />
<span style="font-weight:bold">Date:</span>
<input value="" type="text" name="date" /><br />
<br />
<br />
<input type="submit" name="submit"
value="Post Song" />
</form>
<hr />
<p>
View Songs
</p>
<?php
/*
$input = '<input value="Date" type="text" name="date">';
if (preg_match('/^(|(0[1-9])|(1[0-2]))\/((0[1-9])|(1\d)|(2\d)|(3[0-1]))\/((\d{4}))$/', $input)) {
echo "";
} else {
echo "You must Re-enter date in mm/dd/yyyy format.";
}
*/
if (isset($_POST['submit'])) {
$Song = stripslashes($_POST['song']);
$Name = stripslashes($_POST['name']);
$Date = stripslashes($_POST['date']);
$Song= str_replace("~", "-", $Song);
$Name = str_replace("~", "-", $Name);
$Date = str_replace("~", "-", $Date);
$ExistingSubjects = array();
if (file_exists(
"Songs/songs.txt") &&
filesize("Songs/songs.txt")
> 0) {
$SongArray = file(
"Songs/songs.txt");
$count = count($SongArray);
for ($i = 0; $i < $count; ++$i) {
$CurrSong = explode("~",
$SongArray[$i]);
$ExistingSubjects[] = $CurrSong[0];
}
}
if (in_array($Song, $ExistingSubjects)) {
echo "<p>The song you entered
already exists!<br />\n";
echo "Please enter a new song and
try again.<br />\n"; // Do I need another if statement saying if empty echo you need to enter something?...
echo "Your song was not saved.</p.";
$Song = "";
}
else {
$SongRecord =
"$Song~$Name~$Date~\n";
$SongFile = fopen(
"Songs/songs.txt",
"ab");
if ($SongFile === FALSE)
echo "There was an error saving your
song!\n";
else {
fwrite($SongFile,
$SongRecord);
fclose($SongFile);
echo "Your song has been
saved.\n";
$Song = "";
$Name = "";
$Date = "";
}
}
}
else {
$Song = "";
$Name = "";
$Date = "";
}
?>
</body>
The following regex matches for mm/dd/yyyy
(0[1-9]|1[0-2])/(0[1-9]|1[0-9]|2[0-9]|3(0|1))/\d{4}
The first part i.e. (0[1-9]|1[0-2]) checks for two digits ranging from 01 to 12.
Next part i.e. (0[1-9]|1[0-9]|2[0-9]|3(0|1)) checks for two digits ranging from 01 to 31.
Next part i.e. \d{4} checks for 4 digits.
/ between the parts checks for / as separator.

Problems with guess a number game

Hey, I am so close to fininshing my guess a number game, very simple in PHP, but for some reason I am stuck. I am storing the variable in a hidden form, but obviously each time the page is sent it resets the number so you can never get the right one.
Any ideas? My code is below.
<?php
// generate a random number for user to guess
$number = rand(1,100);
if($_POST["guess"]){
// grab the user input guess
$guess = $_POST['guess'];
$numbe = $_POST['number'];
if ($guess < $number){
echo "Guess Higher";
}elseif($guess > $number){
echo "Guess Lower";
}elseif($guess == $number){
echo "You got it!";
}
echo "<br />Random Number:".$number."<br />";
echo $guess;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Guess A Number</title>
</head>
<body>
<form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number">
<label for="guess">Guess A Number:</label><br/ >
<input type="text" name="guess" />
<input name="number" type="hidden" value="<?= $number ?>" />
<input name="submit" type="submit" />
</form>
</body>
</html>
Change:
// generate a random number for user to guess
$number = rand(1,100);
To:
if(isset($_POST['number'])) {
$number = $_POST['number'];
} else {
$number = rand(1,100);
}
Is it because of this typo?
$numbe = $_POST['number'];
//numbe -> number
I realise you're probably just starting out but the earlier you learn this stuff, the better:
echo "<br />Random Number:".$number."<br />";
This is leaving you open to an XSS attack - I could send $_POST['number'] as <script> doSomethingBad(); </script>
You should either cast it to an integer ($number = (int)$_POST['number']) or escape your output (echo htmlspecialchars($_POST['number']);)
The same goes for $guess of course.
Interestingly, if you're using mod_rewrite, $_SERVER['PHP_SELF'] could also be manipulated to do the same thing.
Do something like:
$number = $_POST['number'];
if ($number == null) {
$number = rand(1,100);
}

Categories