i am beginner php programmer, iv been trying to create a small program that takes input from a forum and then after submission i want it to be printed on the screen. simple and easy i thought, iv been trying and suspiciously it seems to work fine for 1 text field, when i added the remaining 2 text fields called [fam][user] my code stops returning the content to the screen. also i started to recieve an error of an unindex array, therefore i had to use isset to counter this problem, and also, why does my code call the destructor although i never implicitly set my destructor. i dont know how to ask these questions because the errors arent consistent.
code doesnt print my [name][fam][user]
code prints [name] when everything about [fam][user] are ommited from the code.
-code sometimes called the destructor
-code doesnt clear html previous input(e.g, when working with the one text field, lets say i input the [name] john, and click submit it
displays submit, then,i refresh the page, and the name john is still
displayed, why doesnt the destructor clear the memory of name from my
submission.
<form class="nameform" action="book.php" method="post">
<input type="text" name="Name" value="1">
<input type="text" name="Fam" value="2">
<input type="text" name="User" value="3">
<input type="button" name="submit" value="Submit">
</form>
private $name; private $familyName; private $userName;
function __construct($names,$familyNames,$userNames)
{
$this->name = $names;
$this->familyName = $familyNames;
$this->userName = $userNames;
}
function getName()
{
return $this->name;
}
function getFamilyName()
{
return $this->familyName;
}
function getUserName()
{
return $this->userName;
}
public function __destruct()
{
echo "destroyed again";
$this->name;
$this->familyName;
$this->userName;
}
}
if(!isset( $_POST["Name"])||!isset($_POST["Fam"])||!isset($_POST["User"]))
{
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
// $n = $_POST["Name"];
// $f = $_POST["Fam"];
// $u = $_POST["User"];
// $p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
?>
code doesnt print my [name][fam][user]
You never echo them out of the destuctor
public function __destruct()
{
echo "destroyed again";
$this->name; //<---- does nothing
$this->familyName;
$this->userName;
}
So I am not sure what this is supposed to do. You have them down at the bottom
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
But the only thing you'll get from the destruct method is
"destroyed again"
And you will only see that if everything in the form is set. Which it always is when the form is submitted, because type text is always submitted with its form.
Which brings me to this, you should be checking empty instead of isset there
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
if(empty($_POST["Name"])||empty($_POST["Fam"])||empty($_POST["User"])){
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Note that anything falsy will be empty, false, [], '', 0, '0', null etc.
I don't know if this solves all of you problems, but these things could produce some of the behaviour you are experiencing.
Another more advance way to check these is like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
$post = array_filter( $_POST, function($item){
return strlen($item); //any thing of a length of 0 is removed
});
if(count($post) != count($_POST)){
foreach(array_diff_key( $_POST, $post) as $missing=>$empty) {
echo "Please fill in $missing\n";
}
}else{
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Output
Please fill in Name
Please fill in Fam
You can test it online Here
Cheers!
Related
I have an Input submit form and i want if an user enters an number thats match with my array value, the Card Brand saves to PHP Session on next site.
<?php
$submitbutton= $_POST['btnLogin'];
$number= $_POST['Kreditkartennummer'];
function validatecard($number)
{
global $type;
$cardtype = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($cardtype['visa'],$number))
{
$type= "visa";
return 'visa';
}
else if (preg_match($cardtype['mastercard'],$number))
{
$type= "mastercard";
return 'mastercard';
}
else if (preg_match($cardtype['amex'],$number))
{
$type= "amex";
return 'amex';
}
else if (preg_match($cardtype['discover'],$number))
{
$type= "discover";
return 'discover';
}
else
{
return false;
}
}
validatecard($number);
?>
The Question now, works it with my Code? or needs an "If Submit"?
The other question how can i echo the return and save it to my php Session?
To save something to your session variable all you have to do is declare it so.
$_SESSION['card_type'] = $_POST['card_type'];
for example let's say this is your form. This is only an example.
<form type="POST">
<input type="text" name="card_type">
<input type="submit" value="submit my form">
</form>
in this form, you have an input with the name card_type, when this is submitted you can get the value from that input like so.
if(isset($_POST['card_type'])) {
$_SESSION['card_type'] = $_POST['card_type']; //you are taking the post and making a session variable.
}
I know this only explains the last part of your questions, I just did not understand the first part.
edit..I also wanted to point out that you do not just want to accept the user input without some type of validation. Put you validation code after you check if there has been a post.
i am looking at building my first real class, i've played around with bits and bobs but its time to try it for real :)
what i am trying to do is have a form class which handles all my form submissions, checks the data entered and returns with either an error message or success message.
so here one of my forms, (i have 5 of these on 1 page)
<form action="include/mform.php" method="post" name="business_listing">
<input name="biz_name" type="text" value="Business or Place Name" />
<select name="biz_department">
<option value="">Business Sector</option>
<?php
$query = $user->database->query("SELECT * FROM tbl_sectors");
while($row=$user->database->fetchArray($query))
{
$id = $row['sectorID'];
$dept = $row['sectorName'];
echo "<option value='$id'>$dept</option>";
}?>
</select>
<input name="biz_address1" type="text" value="Street Name" />
<select name="job_location">
<option value="">Location</option>
<?php
$query = $user->database->query("SELECT * FROM tbl_places");
while($row=$user->database->fetchArray($query))
{
$id = $row['placeID'];
$dept = $row['placeName'];
echo "<option value='$id'>$dept</option>";
}?>
</select>
<input name="biz_phone" type="text" value="Contact Number" />
<input name="businessSubmit" type="submit" value="Submit" />
</form>
</div>
each of the form's action is set to include/mform.php which contains my class. within the class one of the first things it does is check to see which form was submitted and the idea is then to check the data that has been submitted and do whats necessary with it
my problem is that once my class knows which form was submitted what would be the best way to check the submitted data? should i create varibles within the function to get all the post data and take it from there or should i pass those in the actual function as parameters? , or does it matter?
here is my current class file which is a little bare atm
class Mform
{
private $values = array(); //Holds submitted form field values
private $errors = array(); //Holds submitted form error messages
private $num_errors; //The number of errors in submitted form
public function __construct()
{
if(isset($_POST['businessSubmit']))
{
$this->chkBusiness();
}
if(isset($_POST['jobSubmit']))
{
$this->chkJob();
}
if(isset($_POST['accommodationSubmit']))
{
$this->chkAccommodation();
}
if(isset($_POST['tradeSubmit']))
{
$this->chkTrade();
}
if(isset($_POST['eventSubmit']))
{
$this->chkEvent();
}
}
public function chkBusiness()
{
$field = "business";
}
public function chkJob()
{
return "job";
}
public function chkAccommodation()
{
return "accommodation";
}
public function chkTrade()
{
return "trade";
}
public function chkEvent()
{
return "event";
}
/**
* setValue - Records the value typed into the given
* form field by the user.
*/
public function setValue($field, $value)
{
$this->values[$field] = $value;
}
/**
* setError - Records new form error given the form
* field name and the error message attached to it.
*/
public function setError($field, $errmsg)
{
$this->errors[$field] = $errmsg;
$this->num_errors = count($this->errors);
}
/**
* value - Returns the value attached to the given
* field, if none exists, the empty string is returned.
*/
public function value($field)
{
if(array_key_exists($field,$this->values))
{
return htmlspecialchars(stripslashes($this->values[$field]));
}
else
{
return "";
}
}
/**
* error - Returns the error message attached to the
* given field, if none exists, the empty string is returned.
*/
public function error($field)
{
if(array_key_exists($field,$this->errors))
{
return "<font size=\"2\" color=\"#ff0000\">".$this->errors[$field]."</font>";
}
else
{
return "";
}
}
/* getErrorArray - Returns the array of error messages */
public function getErrorArray()
{
return $this->errors;
}
}
/* Initialize mform */
$mform = new Mform();
most of the individual functions just have return "word" as placeholder so i dont forget to do that function at a later date.
this is what i was thinking of doing for each of the individual form functions
public function chkBusiness()
{
$field = "business";
$name = $_POST['biz_name'];// all need to be sanitized!!
$dept = $_POST['biz_dept'];
$address = $_POST['biz_address'];
$location = $_POST['biz_location'];
$phone = $_POST['biz_phone'];
//start checking the input
if(!$name || strlen($name = trim($name)) == 0)
{
$this->mform->setError($field, "* Name not entered");
}
...
...
}
any help would be appreciated
Luke
I generate a class for every table in my database; life is too short to actually write that functionality for every database table!
Each field has it's own object containing it's value, type, maxlength etc. and the fields are also added to an array so I can do really cool things with them.
Each of the table classes extend a much bigger class that allows me to insert, update, delete and display as tables and forms... I can override any functions that are non-standard although that is very rare.
The performance overhead is about 0.001ms for iterating through about 25000 good sized records.
As an example, my code to produce a datatable of document records looks like this:
//Create object
$objDocument = new cls__CMS_Document();
//Set the fields you want to display in the datatable
$objDocument->objID->Active(true);
$objDocument->objDocument_Name->Active(true);
$objDocument->objAuthorID->Active(true);
$objDocument->objVersion->Active(true);
$objDocument->objDate_Created->Active(true);
$objDocument->objDate_Last_Edited->Active(true);
//Include a hyperlink from the ID field
$objDocument->objID->HyperLink('/drilldown.php');
$objDocument->objID->Post(true);
//Pass a field through a formatting function
$objDocument->objAuthorID->OutputFunction('getAuthorFromID');
$result .= $objDocument->displayTable($sqlConditions);
unset ($objDocument);
The best bit: every step of the way, the auto-complete works:) So you type $objDocument-> and all the methods and properties pop up including all the field objects so you never misspell them.
If I get enough interest (votes), I'll make the whole thing available on the net.
That should be food for thought though when making your own.
I am trying to create function that takes two arguments one for the user input and the other a message for error. I initially have an associative array with the two input fields and the corresponding error.
When the function is submitted without any entry I get two similar output; I thought I would get 'test1' and 'test2'. I am passing different arguments each time but I get the same result. The code is below
$valid = TRUE;
//$errors='';
$errors=array('desc_error'=>'please enter valid description',
'title_error'=>'provide valid title','no_error'=>'',);
function sanitizeText($input,$error){
//$input;
if($input!='')
{
$input= filter_var($input, FILTER_SANITIZE_STRING);
if($input==''){
global $errors;
$errors[$error];
$valid=FALSE;
return $errors[$error];
}
else{
$input;
echo 'test 1';
return $input;
}
}
else if($input=='')
{
if($input==$_POST['desc'])
{
echo 'the description field is required<br/>';
$valid=FALSE;
}
else{
//
}
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText($_POST['title'],'title_error');
$desc=sanitizeText($_POST['desc'],'desc_error');
}
?>
<form method="post" action="">
<p>Book Title:<input type="text" name="title" maxlength="100" value=""/></p>
<p>Desc:<input type="text" name="desc" maxlength="100" value=""/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
I think you are trying to validate form using php you can also user javascript to validate but to do it using php please refer following links.
http://myphpform.com/required-optional-fields.php
http://coredogs.com/lesson/form-and-php-validation-one-page
http://www.phpf1.com/tutorial/php-form.html?page=3
and
http://www.montanaprogrammer.com/php-web-programming/php-form-validation/
Your code does not make sense logic wise. Firstly, you check if $input is an empty string, or is not, and then within that first check.. you again make the same exact check. Since ifs are evaluated in order, and input is not ever going to be an empty string, the first if will always execute.
Then, your first 'else'; it will only execute if the $input variable is an empty string.. I can sort of see what you're attempting to do, but it won't work as it is right now. In order for it to work, it would have to look something like the below:
function sanitizeText($input,$error) {
global $errors;
global $valid;
$input_val = filter_var($_POST[$input], FILTER_SANITIZE_STRING);
if ($input_val != '') {
$valid = TRUE;
return $input;
}
else if ($input_val == '') {
$valid = FALSE;
echo $errors[$error].'<br />';
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText('title','title_error');
$desc=sanitizeText('desc','desc_error');
}
If the input value is not an empty string, it will return the input value. If it is, it will not return anything and will instead echo the appropriate error.
I am a new programmer and am attempting to do some validation for a basic registration form. I have built a basic registration form that sends the user back to the same page when submitted. I have also created a user class and have created some basic validation functions. However, the functions have the error messages built into them. I obviously put the functions on the top of the registration form so when there is an error the errors are posted on the registration form. However, I have no control on how the error messages look and would like to know if there is a lot better way to somehow echo the error messages from outside the class so I can use some type of css or something else for better control of how they look. I hope that makes sense. Also when there is an error the user is sent back to an empty registration form. I was trying to figure out how to keep the valid information in the text boxes and just make them redo the invalid information. Here is a basic example of a validation I have done. I know its basic but I am very new to programming
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
echo "<p> Please enter a value for the password </p>";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
echo "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
Don't echo them right away, instead store them for later use. You mentioned this is inside a class, so you can use a class property to hold error messages.
class YourClass
{
public $error;
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
// Set the error message
$this->error = "Please enter a value for the password";
$valid = FALSE;
}
// etc...
}
}
Later, when you need to, you can output it in the HTML:
if (!empty($yourclass->error)) {
echo "<p class='errmsg'>{$yourclass->error}</p>\n";
}
You then just need a CSS class errmsg and you can style it how you like:
.errmsg {
color: #FF0000;
font-size: 36px;
}
Now if you have that working, you can expand it further to make the $error class property into an array and push multiple messages onto it:
// In the class, initialize it as an array
$this->error = array();
// Use the [] notation to append messages to the array.
$this->error[] = "Another error message..."
$this->error[] = "And yet another error message..."
In your presentation code, use a loop to output the messages:
// Output a big stack of error messages...
foreach ($yourclass->error as $err) {
echo "<p class='errmsg'>$err</p>\n";
}
What I normally do with classes and their errors is have a variable specifically for the errors.
So something like:
class User
{
private $_ValidationErrors = array();
function validate_password($password)
{
$this->_ValidationErrors = array();
$valid = TRUE;
if ($password == '')
{
$this->_ValidationErrors[] = "Please enter a value for the password";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
$this->_ValidationErrors[] = "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
function ValidationErrors ()
{
if (count($this->_ValidationErrors) == 0)
return FALSE;
return $this->_ValidationErrors;
}
}
Then to use:
$user = new User();
if (!$user->validate_password('somepass'))
echo implode('<BR>',$user->ValidationErrors ());
EDIT: To display errors by the user something like:
<?php
if (isset($_POST["submit"]))
{
$user = new User();
$passwordErrors = (!$user->validate_password($_POST["pass1"]))?$user->ValidationErrors():array();
}
?>
<form action="<?php echo $_SERVER["php_self"]; ?>" method="post">
<input type="text" name="pass1" value="<?php echo htmlspecialchars($_POST["pass1"]); ?>" /><BR/>
<?php
echo ((isset($passwordErrors) && count($passwordErrors) == 0)?"":implode("<BR/>", $passwordErrors));
?>
<input type="submit" name="submit" value="Register" />
</form>
I'm finishing up a small contact form and had a question about providing default values for $_POST. The reason I'm asking about default values is because within my form I have fields like this:
<input type="text" name="fullname" value="<?php echo $_POST['fullname']; ?>" />
Clearly I would like to retain the submitted value if I do not permit the data to clear. This raises errors when the page is first loaded, since there is no value for $_POST['fullname'].
To my question: is there anything I should be concerend about providing default values to the $_POST array like I'm doing in the next code-sample:
$_POST += array(
'fullname' = '',
);
If $_POST['fullname'] already exists, it will be retained - if it doesn't, it will be created within the array. This way, upon loading the form, blank values will be presented in the input fields.
Don't worry, all
I sanitize my data
Thank you for the help
Even if you are doing so, put that data in your container, do not modify superglobals. Create class that'll contain your data - then you'll have the interface do sanitize, manipulate and get it te proper way. Import data from $_POST and then validate, if all necessary values are in.
As for code:
<?php
class PostData
{
private $data;
public function __construct(array $data)
{
$this->data = is_array($data)
? $data
: array();
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function get($key, $default, $escaping)
{
if(isset($this->data[$key]))
{
switch($escaping)
{
case 'htmlspecialchars':
{
return htmlspecialchars($this->data[$key]);
break;
}
case 'mysql_real_escape_string':
{
return mysql_real_escape_string($this->data[$key]);
break;
}
// and so on, your invention goes here
default:
{
return $this->data[$key];
}
}
}
else
{
return $default;
}
}
}
$postData = new PostData($_POST);
Create function:
function displayValue($field) {
if(isset($_POST[$field])) {
echo 'value="' . htmlentities($_POST[$field]) . '"';
}
}
And then use like:
<input type="text" name="fullname" <?php displayValue('fullname'); ?> />
You can also do it like this:
<?php echo empty($_POST['fullname']) ? null : $_POST['fullname']; ?>