preg_match help from an input box [duplicate] - php

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.

Related

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" />

Uploading html file to server - breaks [duplicate]

This question already has answers here:
Process HTML files like PHP
(5 answers)
Closed 7 years ago.
(First time posting, sorry if formatting is bad :( )
I patched together an html/php page. It works on this live test environment I used phpfiddle.org
Working there it looks like this
When I save the code and upload the file to my server (I've tried two servers, same problem on both), it's broken
I suspect the problem might be with the header, but I have no clue.
This is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$potErr = $stackErr = "";
$pot = $stack = "";
$p = $s = $g1 = $g2 = $b11 = $b12 = $b21 = $b22 = $b23 = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["pot"])) {
$potErr = "Pot size is required";
} else {
$pot = test_input($_POST["pot"]);
if (!preg_match("/^\d+$/",$pot)) {
$potErr = "Only integers allowed (might work with decimals though, I haven't tested it')";
}
}
if (empty($_POST["stack"])) {
$stackErr = "Stacksize is required";
} else {
$stack = test_input($_POST["stack"]);
if (!preg_match("/^\d+$/",$pot)) {
$stackErr = "Only integers allowed";
}
}
$p = $pot;
$s = $stack;
$g1 = pow(($p+2*$s)/$p,1/2);
$g2 = pow(($p+2*$s)/$p,1/3);
$b11 = ($p*$g1-$p)/2;
$b21 = ($p*$g2-$p)/2;
$b12 = $p*$g1*($g1-1)/2;
$b22 = $p*$g2*($g2-1)/2;
$b23 = $p*$g2*$g2*($g2-1)/2;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Geometric Sizing Calculator</h2>
<p>
<i>Shoutout to AlexMartin's pokernerdz.com which is unfortunately offline. A quick geo calc in his honor! - Paul lnternet Otto </i>
</p>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Pot: <input type="text" name="pot" value="<?php echo $pot;?>">
<span class="error">* <?php echo $potErr;?></span>
<br><br>
Stack: <input type="text" name="stack" value="<?php echo $stack;?>">
<span class="error">* <?php echo $stackErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Geo Sizing:</h2>";
echo "<b>2-street sizing plan:</b> <br>";
echo "Bet " . round($b11) . " then bet " . round($b12) .".";
echo "<br><br>";
echo "<b>3-street sizing plan:</b> <br>";
echo "Bet " . round($b21) . " then bet " . round($b22) . " then bet " . round($b23) .".";
?>
</body>
</html>
With the html extension your PHP instance doesn't know to process it, so it doesn't. You can modify your server so html and htm files are processed as PHP as well; or you can just rename the file to .php.
For the latter solution see this thread; Process HTML files like PHP.

Hiding a paragraph if input is empty

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!";
}
}

Using strip_tags function

I want to preface this question with the fact that I am a student and this is my first PHP class. So, the following question might be a bit novice...
Okay so the point of this program was for me to filter results from a form through regular expressions along with clean up the text area content...
Well as of right now, all works fine except for the strip_tags bit. I have it set to allow the tags <b> and <p>, and when I enter regular text into the text area, it returns perfectly. If I enter something such as <b>lucky</b> you, all that is returned is 'b'.
I'll post my code. If anyone can give me a hand, I'd love it. At this point I'm overly frustrated. I've studied the examples my instructor supplied (mine is almost identical) and I've looked throught the PHP.net manual and from what I read it should work...
The working code is at http://www.lampbusters.com/~beckalyce/prog3b.php
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'GET' )
{
echo <<<STARTHTML
<div class="content"><h1>Site Sign Up</h1>
<h3>Enter Information</h3>
<hr />
<form method="post" action="$_SERVER[PHP_SELF]">
<p>Full Name: <input type="text" name="fullName" size="30" /></p>
<p>Password: <input type="password" name="password" size="30" maxlength="12" /></p>
<p>Email: <input type="text" name="email" size="30"/></p>
<p>Tell us about yourself:<br />
<textarea name="aboutYou" rows="5" cols="40"></textarea><br />
<input type="submit" name="submitted" value="submit" /> <input type="reset" /></p>
</form></div>
STARTHTML;
}
elseif ( $_SERVER['REQUEST_METHOD'] == 'POST')
{
$errors = array();
$dirtyName = $_POST['fullName'];
$filterName = '/(\w+ ?){1,4}/';
if (preg_match($filterName, $dirtyName, $matchName))
{
$cleanedName = ucwords(strtolower(trim(strip_tags(stripslashes($matchName[0])))));
}
else
{
$errors[] = "Enter a valid name. <br />";
}
$dirtyPass = $_POST['password'];
$filterPass = '/[a-zA-Z0-91##$%^&*]{8,12}/';
if (preg_match($filterPass, $dirtyPass, $matchPass))
{
$cleanedPass = $matchPass[0];
}
else
{
$errors[] = "Enter a valid password. <br />";
}
$dirtyEmail = $_POST['email'];
$filterEmail = '/^(?:\w+[.+-_]?){1,4}(?:\w+)#(?:\w+\.){1,3}\w{2,4}/';
if (preg_match($filterEmail, $dirtyEmail, $matchEmail))
{
$cleanedEmail = $matchEmail[0];
}
else
{
$errors[] = "Enter a valid email address. <br />";
}
$dirtyText = $_POST['aboutYou'];
$filterText = '/((\w+)[ ."\'?!,-]{0,3})+/';
if (preg_match($filterText, $dirtyText, $matchText))
{
$validText = $matchText[0];
$ignore = '<b><p>';
$notags = strip_tags($validText,$ignore);
$cleanedText = preg_replace('/fuck|shit|ass|bitch|android/i',"*****",$notags);
}
else
{
$errors[] = "Enter information about yourself. <br />";
}
if (count($errors) == 0)
{
echo <<<STARTHTML2
<div class="content"><h1>Site Sign Up</h1>
<h3>Verify your information</h3>
<hr />
Name: <span class="choices"> $cleanedName <br /></span>
Password: <span class="choices">$cleanedPass <br /></span>
Email: <span class="choices">$cleanedEmail <br /></span>
About you: <span class="choices">$cleanedText <br /></span>
STARTHTML2;
}
else
{
echo "<div class=\"content\">Please correct the following errors:<br />\n";
$errnum = 1;
foreach ($errors as $inderr)
{
echo "$errnum. $inderr";
$errnum++;
}
}
echo '<br />Back to Form';
echo '</div>';
echo '<p style="text-align: center">' . date('l, F d, Y') . '</p>';
}
?>
It doesn't look like your regular expression allows for the < and > characters, also, if it was meant to match the entire text, it should start with ^ and end with $, otherwise it will just match on a small section of the input as best it can according to the pattern which is likely what happened to simply return 'b' in $match[0] when supplying <b>TextHere

Categories