PHP or HTML Form Validation - php

I want to validate an HTML form in either HTML or PHP. By validate, I mean ensuring there is at least 1 character of text entered into each of the 2 textboxes. And either only alpha numeric characters entered, or have something that ensures that any punctuation doesn't end up with "/" before it.
At the moment my form is made up of 2 php pages (copied below), and then posted to a txt file.
I'm either after some (very basic) instructions on how to do it, or suggestions on my script below.
//HTML
<form style="" method="post" action="addtopic2.php">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text"><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120"
name="outline"></textarea>
<br><input name="submit" value="Submit" type="submit">
</form>
//HTML
<?php
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>
//ATTEMPTED TO USE FOLLOWING, BUT DOESNT SEEM TO WORK WHEN INSERTING INTO EITHER PAGES.
<?php
if($_POST['Submit'] == "submit")
{
$errorMessage = "";
if(empty($_POST['topic']))
{
$errorMessage .= "<li>A topic needs to be entered</li>";
}
if(empty($_POST['outline']))
{
$errorMessage .= "<li>An outline needs to be entered</li>";
}
$vartopic = $_POST['formtopic'];
$varoutline = $_POST['formoutline'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<?php
if (isset($_POST['topic']) && isset($_POST['outline'])) {
$topic = trim($_POST['topic']);
$outline = trim($_POST['outline']);
}
else {
echo '<p>Fill the form</p>';
}
?>

Try
$file = "users.txt";
$errorMessage = array ();
if ($_POST ['Submit'] == "submit") {
if (empty ( $_POST ['topic'] )) {
$errorMessage [] = "A topic needs to be entered<";
}
if (empty ( $_POST ['outline'] )) {
$errorMessage [] = "An outline needs to be entered";
}
if (count ( $errorMessage ) == 0) {
$data = $_POST ['topic'] . "|" . $_POST ['outline'] . "\n";
$fh = fopen ( $file, "a" );
fwrite ( $fh, $data );
fclose ( $fh );
} else {
print ("<p>There was an error with your form:</p>\n") ;
print ("<ul>") ;
foreach ( $errorMessage as $error ) {
print "<li>" . $error . "<li>";
}
print ("</ul>") ;
}
}
// To Read Your File
$content = file ( $file );
print ("<p>File Details</p>\n") ;
foreach ( $content as $info ) {
list ( $topic, $outline ) = explode ( "|", $info );
print ("<ul>") ;
print "<li>Topic: " . $topic . "<li>";
print "<li>Outline:" . $outline . "<li>";
print ("</ul>") ;
}

Try this (single file) solution:
<form style="" method="post">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text" value='<?= $_REQUEST['topic'] ?>><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120" name="outline"><?= $_REQUEST['outline'] ?></textarea>
<p/>
<input name="submit" value="Submit" type="submit">
</form>
<?php
if ($_REQUEST['submit'] !== 'submit')
{
exit;
}
if ($_REQUEST['topic'] == '')
{
echo "<p>Missing Topic.</p>\n";
exit;
}
if ($_REQUEST['outline'] == '')
{
echo "<p>Missing Outline.</p>\n";
exit;
}
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>

Related

No records displayed in PHP search form

can anyone tell me why this code doesn't give me any records and display my "else" error message instead ? table which I'm trying to get data from( attached) uses two foreign keys ( emp number ,and project code) from two other tabels
( Please note I'm new to PHP )
$emp_no="";
$project_code="";
$p_hours="";
require_once 'connect.php';
function getposts()
{
$posts= array();
if (isset($_POST['EMPNo']))
{
$posts[0] = $_POST['EMPNo'];
}
if (isset($_POST['ProjectCode']))
{
$posts[1] = $_POST['ProjectCode'];
}
if (isset($_POST['Hours']))
{
$posts[2] = $_POST['Hours'];
}
return $posts;
}
if(isset($_POST['search']))
{
#$data = getposts();
#$searchquery = "SELECT * FROM `enrolment` WHERE `EMPNo`='$data[0]' AND
`ProjectCode`='$data[1]'";
#$search_Result =mysqli_query($connect, $searchquery);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($raw = mysqli_fetch_array($search_Result))
{
$emp_no = $raw ['EMPNo'] ;
$project_code = $raw ['ProjectCode'] ;
$p_hours = $raw ['Hours'] ;
}
}else {
echo 'Unable to find the record please check input data!';
}
}else {
echo ' Result Error ';
}
}
//html part
<Form action="updateenrolment.php" method="post" style="color:blue;margin-
left:500px;">
<input type="text" name ="empno" placeholder="Employee No" value="<?php
echo $emp_no;?>"><br><br>
<input type="text" name ="pcode" placeholder="Project Code" value="<?php
echo $project_code;?>"><br><br>
<input type="number" name ="hours" placeholder="Hours" value="<?php echo
$p_hours;?>"><br><br>
<div>
<input type="submit" name ="search" value="Find" >
mysqli_fetch_array print the array result but you are fetching result using string element. you need to change this.
while($raw = mysqli_fetch_array($search_Result))
{
$emp_no = $raw [1] ;
$project_code = $raw [2] ;
$p_hours = $raw [3] ;
}
To replace it.
while($raw = mysqli_fetch_array($search_Result))
{
$emp_no = $raw ['EMPNo'] ;
$project_code = $raw ['ProjectCode'] ;
$p_hours = $raw ['Hours'] ;
}

foreach value from input form

please help me. i have a problem with my code.
This is code input.php :
<form method="POST" action="simpan.php">
NIM : <input type="text" required placeholder="input NIM" name="nim"/><br/>
Name : <input type="text" required placeholder="input name" name="nama"/><br/>
score : <input type="number" required placeholder="input score between 0-100" name="score"/><br/><input type="submit" value="OK"/>
This is code simpan.php :
<?php
session_start();
$_SESSION['nim'][] = $_POST['nim'];
$_SESSION['nama'][] = $_POST['nama'];
$_SESSION['nilai'][] = $_POST['score'];
header("location:index.php")
?>
and This is code show.php :
<?php
session_start();
foreach($_SESSION as $key)
{
foreach($key as $data => $value)
{
echo "NIM : ",$value." ", "Name : ",$value." ", "Score : ",$value." ";
}
}
?>
the result :
enter image description here
And the problem is I want to show the input with format
Nim:
Name:
score:
example = nim:01 name: john score:90
What should I change in show.php in order to appear according to the above format?
thanks :)
#Arif Maulana just change your show.php to like below hope this is what you want:
<?php
session_start();
$echoString = "";
foreach($_SESSION as $key => $sessionArr){
if($key == "nama"){
$echoString .= "name : ";
}
else if($key == "nilai"){
$echoString .= "score : ";
}
else{
$echoString .= $key." : ";
}
foreach($sessionArr as $value)
{
$echoString .= $value." ";
}
}
echo $echoString;
?>
Please check the below example i did https://3v4l.org/CcOOK
<?php
$_POST['nim'] = 'Hrllo';
$_POST['nama'] = 'Data';
$_POST['score'] = '33';
$_SESSION['nim'][] = $_POST['nim'];
$_SESSION['nama'][] = $_POST['nama'];
$_SESSION['score'][] = $_POST['score'];
$string = '';
foreach($_SESSION as $main_key => $key)
{
foreach($key as $data => $value)
{
$string .= $main_key . ":" . $value . ' ';
}
}
$string = rtrim($string, ' ');
echo $string;

php undefined index with isset $_POST

trying to create a chat and keep getting Undefined index i've tried adding ? $_POST['chat'] : null; but doesn't work
Notice: Undefined index: chat in /Applications/MAMP/htdocs/chat/chat.php on line 8
Line 8:
$sent = $_POST['chat'];
the variable is used here:
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
if(isset($_POST['chat'])){
echo 'Cant send an empty message','<br />';
}
}
}
HTML:
<body>
<iframe id='reload' src='refresh.php'>
<fieldset class="field">
<div id="list"><p><?php
$filename = 'chat.txt';
$handle = fopen($filename, 'r');
$detain = fread($handle, filesize($filename));
$chat_array = explode('=', $detain);
foreach($chat_array as $chat) {
echo $chat.'<br />';
}
?></p></div>
</fieldset>
</iframe>
<form action="chat.php" method="POST">
<input type="text" name="chat" class="textbox">
<input type="submit" value="Send" class="button">
</form>
</body>
Variables:
$sent = $_POST['chat'];
$myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
$txt = ($sent."\n");
$first = getuserfield('username');
$active = ($first.":".$ip_addr);
$activef = fopen("ip-user.txt", 'a');
$myFile = "domains/domain_list.txt";
Edit: This is not a duplicate because this is for a very specific piece of code, i've also already used empty and I would not like to ignore the problem because it is a possible cause of another problem.
Thank you.
Use this code :
<?php
$sent = '';
if(isset($_POST['chat']))
{
$sent = $_POST['chat'];
if (!empty($sent))
{
$txt = ($sent."\n");
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
}
else
{
echo 'Cant send an empty message','<br />';
}
}
?>
You said you tried a ternary conditional, but didn't post an example of what you tried. It should look like this:
$sent = isset($_POST['chat']) ? $_POST['chat'] : null;
In PHP 7.0 or higher, you can simplify this expression with the null coalesce operator:
$sent = $_POST['chat'] ?? null;
did you submit the form ?
PHP:
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
if(isset($_POST['chat'])){
echo 'Cant send an empty message','<br />';
}
}
}
HTML:
<form action="" method="POST">
<input type="text" name="chat">
<input type="submit" name="submit">
</form>
Do something like $sent = isset($_POST['chat']) ? $_POST['chat'] : '';
btw.: There is much redundance in you code.
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else {
echo 'Cant send an empty message','<br />';
}
}
If you don't want to write an isset() condition every time, you could define a short function:
function get(&$var, $default = null)
{
return isset($var) ? $var : $default;
}
Use it like that:
$sent = get($_POST['chat'], '');
or just
$sent = get($_POST['chat']);

whats wrong with my php script

hello to all at stackoverflow. (my first post) : )
i wrote this script
$file = glob("*.php"); // list all .php files
$findfile = array_search("index.php", $file); // search array for index.php
unset($file[$findfile]); // remove index.php from array
sort($file, SORT_NUMERIC); // sort array
foreach($file as $file){ include_once($file);} // include files in page
the files are 1.php,2.php,3.php etc
everytime i run it the files get included at the top of the page.
i need the files in the middle,
what am i doing wrong.
Thats the whole page as it looks for now
<?php
if(isset($_POST['ta'])){
$ta = $_POST['ta'];
if($ta != "" && strlen($ta) > 1 ){
$ta = preg_replace('#[^a-z0-9 !?.,]#i', '', $ta);
$usertextinput = '<p class="important">'.$ta.'</p>';
$pho = count(glob('*.php'));
$username_file = ($pho + 1) . ".php";
$createuser = fopen($username_file, 'w');
fwrite($createuser, $usertextinput);
header("location: index.php#bottom");}}
$userpage = '<p class="important"><span>Posts\'s:</span><br />
[username] Has 1 post's To Date.</p>';?>
$file = glob("*.php");
$findfile = array_search("index.php", $file);
unset($file[$findfile]);
sort($file, SORT_NUMERIC);
foreach($file as $file){ include_once($file);}
$userpage .= '<form name="text" method="post" action="">
<textarea name="ta" placeholder=" Enter Your Comment\'s Here ">
</textarea><br />
<a name="bottom"></a>
<p class="sub"><input type="submit" value="Post To Page" /></p>';
?>
im building a post wall (no database)
Give this a go. It will have the form's input on top,
then the Posts's: [username] Has 1 post's To Date. followed by the included files.
It's basically a placement issue.
<?php
if(isset($_POST['ta'])){
$ta = $_POST['ta'];
if($ta != "" && strlen($ta) > 1 ){
$ta = preg_replace('#[^a-z0-9 !?.,]#i', '', $ta);
$usertextinput = '<p class="important">'.$ta.'</p>';
$pho = count(glob('*.php'));
$username_file = ($pho + 1) . ".php";
$createuser = fopen($username_file, 'w');
fwrite($createuser, $usertextinput);
header("location: index.php#bottom");
}
}
$userpage = '<form name="text" method="post" action="">
<textarea name="ta" placeholder=" Enter Your Comment\'s Here ">
</textarea><br />
<a name="bottom"></a>
<p class="sub"><input type="submit" value="Post To Page" /></p>';
$userpage .= '<p class="important"><span>Posts\'s:</span><br />[username] Has 1 post\'s To Date.</p>';
echo $userpage;
$file = glob("*.php");
$findfile = array_search("index.php", $file);
unset($file[$findfile]);
sort($file, SORT_NUMERIC);
foreach($file as $file){
include_once($file);
}
?>
The reason why it isn't working, is because you are terminating the php code here:
[username] Has 1 post's To Date.</p>';?>
Remove the ?> and escape the single quote near post's; so the code block will look like this:
$userpage = '<p class="important"><span>Posts\'s:</span><br />
[username] Has 1 post\'s To Date.</p>';
$file = glob("*.php");
$findfile = array_search("index.php", $file);
unset($file[$findfile]);
sort($file, SORT_NUMERIC);
foreach($file as $file){ include_once($file);}

Using PHP to read msword and find specific elements e.g. numbering and bullets, underline sentence...?

I tried to use the PHP code from the following link
I tried the below code but it displays only text. How can i find specific element e.g. numbering and bullets, underline sentence...?:
Is there any trick by using chr() function to solve my problem?
<?php
function content($file){
$data_array = explode(chr(0x0D),fread(fopen($file, "r"), filesize($file)));
$data_text = "";
foreach($data_array as $data_line){
if (strpos($data_line, chr(0x00) !== false)||(strlen($data_line)==0))
{} else {if(chr(0) || chr(149)) {
$data_text .="<br /> ";
$data_text .= preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t#\/\_\(\)]/","",$data_line);
}
}
}
$data_text = str_replace('Responsibilities','<strong>'.Responsibilities.': </strong>',$data_text);
$data_text = str_replace('Requirements','<strong>'.Requirements.': </strong>',$data_text);
return $data_text;
}
$destination = str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']);
$destination.= "upload/";
$maxsize = 5120000;
if (isset($_GET['upload'])) {
if($_FILES['userfile']['name'] && $_FILES['userfile']['size'] < $maxsize) {
if(move_uploaded_file($_FILES['userfile']['tmp_name'], "$destination/".$_FILES['userfile']['name'])){
$file = $destination."/".$_FILES['userfile']['name'];
$data = content($file);
echo $data;
}
}
}else{
echo "<form enctype='multipart/form-data' method='post' action='index.php?upload'>
<input name='userfile' type='file'>
<input value='Upload' name='submit' type='submit'>
</form>";
}
?>

Categories