Most efficient way of validating a form in an array? - php

I have a form being validated in the following manner:
//Clear all variables
$formCheck = '';
$rep = '';
$name = '';
$department = '';
$location = '';
$email = '';
$phone = '';
$type = '';
$drink = '';
$notes = '';
$lastVisited = '';
$nextVisit = '';
$clean_formCheck = '';
$clean_rep = '';
$clean_name = '';
$clean_department = '';
$clean_location = '';
$clean_email = '';
$clean_phone = '';
$clean_type = '';
$clean_drink = '';
$clean_notes = '';
$clean_lastVisited = '';
$clean_nextVisit = '';
function validateRep($rep){
...some code...
}
$formCheck = $_POST["formCheck"];
$rep = $_POST["rep"];
$name = $_POST["name"];
$department = $_POST["department"];
$location = $_POST["location"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$type = $_POST["type"];
$drink = $_POST["drink"];
$notes = $_POST["notes"];
$lastVisited = $_POST["lastVisited"];
$nextVisit = $_POST["nextVisit"];
if (validateRep($rep)){
$clean_rep = $rep;
}else{
echo "Invalid Rep";
exit();
}
//.....and so on......
I was wondering if it would be more efficient / cleaner to validate using an an array instead of individual variable? If so, how would I go about that, and how would I write the different validation functions all in one (eg. right now I have a separate function to validate each field), would it be possible with a loop through the array? i was experimenting and so far this is what I have:
$unclean['formCheck'] = $_POST["formCheck"];
$unclean['rep'] = $_POST["rep"];
$unclean['name'] = $_POST["name"];
$unclean['department'] = $_POST["department"];
$unclean['location'] = $_POST["location"];
$unclean['email'] = $_POST["email"];
$unclean['phone'] = $_POST["phone"];
$unclean['type'] = $_POST["type"];
$unclean['drink'] = $_POST["drink"];
$unclean['notes'] = $_POST["notes"];
$unclean['lastVisited'] = $_POST["lastVisited"];
$unclean['nextVisit'] = $_POST["nextVisit"];
$clean = array(
'rep', 'name', 'department', 'location', 'email', 'phone', 'type', 'drink', 'lastVisited', 'nextVisit',
);
but I'm not sure how to proceed from here.

I would use something along these lines... Just coded this very quickly, basically you create validation functions that match the post fields and return true or false if the validation passed. e.g. validate_department, validate_type, validate_drink, etc. Will work if your post data doesn't have any strange characters in (which so far it doesn't)
$post_fields = array('rep',
'name',
'department',
'location',
'email',
'phone',
'type',
'drink',
'lastVisited',
'nextVisit'
);
$validate = new Validate();
foreach ($post_fields as $post_var)
{
if (isset($_POST[$post_var]))
{
$validate->validate_data($post_var, $_POST[$post_var]);
}
}
if ($validate->all_fields_valid() === true)
{
echo 'congrats, all validation passed!';
}
else
{
echo 'oh no! error in validation process. please see below errors: <p>' .
$validate->get_error_msg() . '</p>';
}
And the validate class... Use $errorMsg to see the error messages should you run into any issues
class Validate
{
var $valid = 0,
$error = 0,
$errorMsg = '';
function validate_data($var, $data)
{
if (method_exists($this, 'validate_'.$var))
{
if (call_user_func(array($this, 'validate_'.$var), $data) === true)
{
$this->valid++;
}
else
{
$this->throwError('validation for: "'.$var.'" was not considered valid');
}
}
else
{
$this->throwError('validation function for: "'.$var.'" does not exist');
}
}
function throwError($msg = '')
{
if ($msg) $this->errorMsg .= $msg . '<br/>';
$this->error++;
}
function all_fields_valid()
{
if (!$this->error) return true;
return false;
}
/***********************************************
*************************************************
Custom validation functions go below here
Function format: validate_<postFieldName>
Returns: true or false if the data passed is valid or not
*************************************************
*************************************************/
function validate_type($type)
{
if (is_numeric($type)) return true;
return false;
}
function validate_lastVisited($data)
{
}
//etc...............
}

use filter_input.
$rep = filter_input(INPUT_POST, "rep", FILTER_SANITIZE_STRING);
$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);
$department = filter_input(INPUT_POST, "department", FILTER_SANITIZE_STRING);
$location = filter_input(INPUT_POST, "location", FILTER_SANITIZE_STRING);
if (filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
}
Like that.

Related

Woocommerce checkout redirection not working as expected after few attempts

I am developing a WooCommerce payment gateway plugin with WordPress version 5.4.2 and WooCommerce version 3.8.0.
Plugin working fine for few 3-4 trials, but after this I am not able to get redirected to the checkout page. It keeps redirecting to the cart or basket page.
I have also checked the logs, but nothing found there.
I not professional in WordPress.
The plugin has live demo
You can see code below
// Submit payment and handle response
public function process_payment($order_id) {
global $woocommerce;
global $current_user;
//get user details
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$first_name = $current_user->shipping_first_name;
$last_name = $current_user->shipping_last_name;
$phone_number = $current_user->billing_phone;
$country = $current_user->shipping_country;
$state = $current_user->shipping_state;
$city = $current_user->shipping_city;
$postcode = $current_user->shipping_postcode;
$address_1 = $current_user->shipping_address_1;
$address_2 = $current_user->shipping_address_2;
$udf1 = $first_name." ".$last_name;
$udf2 = $user_email;
$udf3 = $phone_number;
$udf4 = $country." ".$state." ".shipping_city." ".$address_1." ".$address_2." ".$postcode;
$user_email = $_POST['billing_email'];
$first_name = $_POST['billing_first_name'];
$last_name = $_POST['billing_last_name'];
$phone_number = $_POST['billing_phone'];
$country = $_POST['billing_country'];
$state = $_POST['billing_state'];
$city = $_POST['billing_city'];
$postcode = $_POST['billing_postcode'];
$address_1 = $_POST['billing_address_1'];
$address_2 = $_POST['billing_address_2'];
$udf1 = $first_name." ".$last_name;
$udf2 = $user_email;
$udf3 = $phone_number;
$udf4 = $country." ".$state." ".shipping_city." ".$address_1." ".$address_2." ".$postcode;
$order = new WC_Order( $order_id );
$atom_login_id = $this->login_id;
$atom_password = $this->password;
$atom_prod_id = $this->atom_product_id;
$amount = $order->get_total();
$currency = "INR";
$custacc = "1234567890";
$txnid = $order_id;
$clientcode = urlencode(base64_encode(007));
$datenow = date("d/m/Y h:m:s");
$encodedDate = str_replace(" ", "%20", $datenow);
if(!function_exists('wc_get_checkout_url')){
require_once '/includes/wc-core-functions.php';
}
$ru = wc_get_checkout_url();
$data["login"] = $atom_login_id;
$data["pass"] = $atom_password;
$data["prodid"] = $atom_prod_id;
$data['txnid']=$txnid;
$data['amt'] = $amount;
$data['reqHashCode'] = $this->req_hash_code;
$data['requestEncypritonKey'] = $this->req_enc_key;
$data['salt'] = $this->req_salt_key;
$signature = $this->getChecksum($data);
$param = "login=".$atom_login_id."&pass=".$atom_password."&ttype=NBFundTransfer"."&prodid=".$atom_prod_id."&amt=".$amount."&txncurr=".$currency."&txnscamt=0"."&clientcode=".$clientcode."&txnid=".$txnid."&date=".$encodedDate ."&custacc=".$custacc."&udf1=".$udf1."&udf2=".$udf2."&udf3=".$udf3."&udf4=".$udf4."&ru=".$ru;
$param = $param."&signature=".$signature;
$atomenc = new AtomAES();
$encData = $atomenc->encrypt($param, $data['requestEncypritonKey'], $data['salt']);
global $wpdb, $woocommerce;
return array('result' => 'success', 'redirect' => $this->url."?" ."login=".$atom_login_id."&encdata=".strtoupper($encData));
exit;
}
// checking response from payment gateway and show messages on checkout page
function check_atom_response(){
global $woocommerce;
global $wpdb, $woocommerce;
$atomenc = new AtomAES();
$decrypted = $atomenc->decrypt($_POST['encdata'], $this->res_enc_key, $this->res_salt_key);
$array_response = explode('&', $decrypted); //change & to | for production
$equalSplit = array();
foreach ($array_response as $ar) {
$equalSub = explode('=', $ar);
if(!empty($equalSub[1]) && !empty($equalSub[0])){
$temp = array(
$equalSub[0] => $equalSub[1],
);
$equalSplit += $temp;
}
}
if(isset($equalSplit['f_code']) && $this->validateResponse($equalSplit)){
$order = new WC_Order($equalSplit['mer_txn']);
$order_id = $equalSplit['mer_txn'];
$VERIFIED = $equalSplit['f_code'];
if($VERIFIED == 'Ok'){
$VERIFIED = 'complete';
}else{
$VERIFIED = 'pending';
}
$bank_name = $equalSplit['bank_name'];
$bank_txn = $equalSplit['bank_txn'];
$discriminator = $equalSplit['discriminator'];
if($equalSplit['f_code']=='Ok'){
$order->update_status('completed');
$this -> msg['message'] = "Thank you for shopping with us. Your account has been charged <b>Rs".$equalSplit['amt']."</b> for order id <b>".$order_id."</b> and your transaction is successful. Bank Transaction ID is : <b>".$equalSplit['bank_txn']."</b>.";
$this->msg['class'] = 'woocommerce-message';
$this->msg['order'] = $order;
} else if($equalSplit['f_code'] == 'F') {
$return_url = $this->get_return_url($order);
$order->update_status('failed');
$this->msg['class'] = 'woocommerce-error';
$this->msg['message'] = "<b style='color:red;font-size:20px'>The transaction has been failed or declined.</b>";
$this->msg['order'] = $order;
} else {
$order->update_status('cancelled');
$this->msg['class'] = 'woocommerce-error';
$this->msg['message'] = "<b style='color:red;font-size:20px'>The transaction has been cancelled or declined.</b>";
$this->msg['order'] = $order;
}
add_action('the_content', array(&$this, 'showMessage'));
add_filter('cron_schedules', 'new_intervals');
function new_intervals($interval) {
$interval['minutes_30'] = array('interval' => 30*60, 'display' => 'Once 30 minutes');
return $interval;
}
function InitiateMyCron() {
wp_schedule_event(time(), 'minutes_30', 'update_ransaction_status');
}
}
}

Custom function to allow only expected data in submissions

I have a function that allows only expected data from form submissions. I was using it before and it was working fine but now when I try to use it. it throws an error: Warning: Invalid argument supplied for foreach() I've tried using is_array() function but that didn't fix the error. any idea why this happening.
Function
function allowed_post_params($allowed_params=[]) {
$allowed_array = [];
foreach ($allowed_params as $param) {
if (isset($_POST[$param])) {
$allowed_array[$param] = $_POST[$param];
} else {
$allowed_array[$param] = NULL;
}
}
return $allowed_array;
}
Use in Processing
if (is_post_request()) {
$post_params = allowed_post_params('email', 'username', 'password', 'country');
$email = $post_params['email'] ?? '';
$username = $post_params['username'] ?? '';
$password = $post_params['password'] ?? '';
$country = $post_params['country'] ?? '';
}
You are supplying 4 string arguments to the function.
$post_params = allowed_post_params('email', 'username', 'password', 'country');
It should be a single array:
$post_params = allowed_post_params(['email', 'username', 'password', 'country']);

How to insert multiple dynamic data using CodeIgniter?

I am using CodeIgniter, I am displaying the fields dynamically. Now I have to insert the data in the database. So I tried below code.
$order = $this->input->post('order[]');
$partner = $this->input->post('parner[]');
$bankname = $this->input->post('newpartner[]');
$status = $this->input->post('filestatus[]');
$user_id = $this->input->post('user_id');
$order_length = sizeof($order);
for ($j = 0; $j < $order_length; $j++) {
if (($status = 1) || ($status = 3)) {
$remark = $this->input->post('remark[]');
} else {
$remark = "";
}
if (($status = 2) || ($status = 4))) {
$reasonDate = $this->input-> post('reasonDate[]');
$remark = $this->input-> post('remark[]');
} else {
$reasonDate = "";
$remark = "";
}
if ($status = 7) {
$reasonAmt = $this->input->post('reasonAmt[]');
$reason = $this->input->post('reason[]');
} else {
$reasonAmt = "";
$reason = "";
}
$data['row'] = array(
'order' => $order[$j],
'bankname' => $bankname[$j],
'status' => $status[$j],
'lead_id' => $user_id,
'remark' => $remark[$j],
'reasonDate' => $reasonDate[$j],
'reasonAmt' => $reasonAmt[$j],
'reason' => $reason[$j]
);
$save = array(
'b_orderno' => $data['row']['order'],
'b_bankname' => $data['row']['bankname'],
'b_filestatus' => $data['row']['status'],
'p_id' => $data['row']['pid'],
'lead_id' => $data['row']['lead_id'],
'b_remark' => $data['row']['remark'],
'b_date' => $data['row']['reasonDate'],
'b_amt' => $data['row']['reasonAmt'],
'b_reason' => $data['row']['reason']
);
$afterxss = $this->security-> xss_clean($save);
if ($afterxss) {
$this - > db - > insert('tbl_bankdata', $afterxss);
$response['error'] = "true";
$response['msg'] = "added successfully";
} else {
$response['error'] = "false";
$response['msg'] = "Sometning wrong! please check the internet connection and try again";
}
}
echo json_encode($response);
I am getting the issue on the status field because depending upon the status value input field will display. Also, I used If the condition in logic for the status field. Each row has a unique status field.
You will find my HTML and script in below link.
https://jsfiddle.net/08phzue3/
This is my UI screenshot. Ignore the value that is only for testing purpose.
1)Onload this will display
2) If user select the status
3) If multiple row
Would you help me out with this?
Actually you are not comparing here:
if (($status = 1) || ($status = 3)) {
You are assigning the values to your $status variable
this should be:
if (($status == 1) || ($status == 3)) {
Side note: same for other conditions as well.
Edit:
As you mentioned you are getting array in $status so using comparison is not a correct logic here, there are multiple solution available,
You can use in_array() like:
if(in_array(1, $status) || in_array(3, $status)){
$remark = $this->input->post('remark[]');
}
else{
$remark = "";
}
Final Solutions (04-07-2019):
After changing the $save and $data arrays, issue has been resolved for OP:
$save['b_orderno'] = $order[$j];
$save['b_bankname'] = $bankname[$j];
$save['b_filestatus'] = $status[$j];
$save['p_id'] = $partner[$j];
$save['lead_id'] = $user_id;
if(!empty($remark[$j])){
$save['b_remark'] = $remark[$j];
}
if(!empty($reasonDate[$j])){
$save['b_date'] = $reasonDate[$j];
}
if(!empty($message[$j])){
$save['b_message'] = $message[$j];
}
if(!empty($reasonAmt[$j])){
$save['b_amt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$save['b_reason'] = $reason[$j];
}
$data['row']['order'] = $order[$j];
$data['row']['bankname'] = $bankname[$j];
$data['row']['status'] = $status[$j];
$data['row']['lead_id'] = $user_id;
$data['row']['remark'] = $remark[$j];
$data['row']['reasonDate'] = $reasonDate[$j];
if(!empty($reasonAmt[$j])){
$data['row']['reasonAmt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$data['row']['reason'] = $reason[$j];
}

How to format output data from PHP form in separate text file?

I've created a PHP form that outputs the form data entries into a separate text file. The problem with the output is that it's plain text with no line breaks or spaces between entries. I would like to know how I can format the output data so that it is more legible (possibly using a table or just simple line breaks).
I asked my professor for a solution and he referred me to this page. I'm sure this is what I am looking for but I have trouble forming it for my needs. What do I need to change from the code on that page in order for it to work for me? I've tried adding and subtracting code but that resulted in syntax errors.
Here's the PHP form code:
<?php
// define variables and set to empty values
$nameErr = '';
$emailErr = '';
$commentErr = '';
$likesErr = '';
$howErr = '';
$rateErr = '';
$name = '';
$email = '';
$comment = '';
$likes = '';
$how = '';
$rate = '';
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}
$data = $name.$email.$comment.$likes.$how.$rate.
'';
file_write($data, 'feedback.php')
?>
EDIT 1:
This is the section that I believe is causing the issues since there are two file_write:
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data, FILE_APPEND | LOCK_EX);
}//return an error message if the data isnt a string
}
$data = $name.PHP_EOL.$email.PHP_EOL.$comment.PHP_EOL.$likes.PHP_EOL.$how.PHP_EOL.$rate.‌PHP_EOL.
file_write($data, 'feedback.php');
For the sake of this answer, I am assuming that file_write is a function that you've included somewhere. AFAIK file_write isn't a standard PHP function for writing to a file.
Your data is written to the file as a single line with no spaces because you haven't specified any spaces or line breaks.
If you want line breaks in-between each of the fields, do the following:
$data = $name.PHP_EOL.$email.PHP_EOL.$comment.PHP_EOL.$likes.PHP_EOL.$how.PHP_EOL.$rate;
file_write($data, 'feedback.php');
It is best to use PHP_EOL for adding line breaks. It is cross-platform -- PHP will automatically choose the correct newline character(s) for whichever platform your code is running on.
Try "\n" or you can also try "\r\n"
So you can following this code:
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data.'\n\n', FILE_APPEND | LOCK_EX);
}//return an error message if the data isnt a string
}
$data = $name.'\n'.$email.'\n'.$comment.'\n'.$likes.'\n'.$how.'\n'.$rate;
first comment. Keep the FILE_APPEND flag as it will keep an on-going storage.
Second. In the future, if you want to analyze your data having it separated with newlines will be a pain to parse. I suggest exporting comma delimited with newlines only for new entries. You can then easily parse or import (as a csv) into Excel.
$data = $name.','.$email.','.$comment.','.$likes.','.$how.','.$rate.PHP_EOL;
file_write($data, 'feedback.php');
However, you may run into an issue where somebody puts a comma in your web form. How do you account for that? You could enclose each item in the row with quotes. You can do that one yourself! good luck.
You can use the PHP_EOL constant so that line endings appropriate to the server will be output, in which case your code would look like
$data = $_POST['name'] . PHP_EOL;
$data .= $_POST['email'] . PHP_EOL;
$data .= $_POST['comment'] . PHP_EOL;
$data .= $_POST['likes'] . PHP_EOL;
$data .= $_POST['how'] . PHP_EOL;
$data .= $_POST['rate'] . PHP_EOL;
OR try this one
$data = $_POST['name'] . "\r\n";
IF this not helps you try this as well
$data = sprintf("%s\n%s\n%s\n",$_POST['name'],$_POST['email'], $_POST['comment'],$_POST['how'],$_POST['rate']);
file_put_contents($file, $data, FILE_APPEND);
You may try this :
<?php
// define variables and set to empty values
$nameErr = '';
$emailErr = '';
$commentErr = '';
$likesErr = '';
$howErr = '';
$rateErr = '';
$name = '';
$email = '';
$comment = '';
$likes = '';
$how = '';
$rate = '';
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function file_write($data, $feedback){
if(is_string($data)){
return file_put_contents($feedback, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}
$data = $name.PHP_EOL;
$data .= $email.PHP_EOL;
$data .= $comment.PHP_EOL;
$data .= $likes.PHP_EOL;
$data .= $how.PHP_EOL;
$data .= $rate.PHP_EOL;
file_write($data, 'feedback.php')
?>
Hope any of this help you

No refresh register form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have created a registration form and it works my only issues is I want to be able to hide the post info in the url if you click submit and the validation fails it does this
register.php?action=signup
is there a mod rewrite for this?
so that the url remains
register.php
removing the ?action=signup
I have searched every where but have came up with nothing
php code for register page
<?php
//Error reporting #1-8F636958
error_reporting(E_ALL | E_STRICT);
//End Error reporting
//Include Common Files #1-EDC1CE42
define("RelativePath", ".");
define("PathToCurrentPage", "/");
define("FileName", "NewPage1.php");
include_once(RelativePath . "/Common.php");
include_once(RelativePath . "/Template.php");
include_once(RelativePath . "/Sorter.php");
include_once(RelativePath . "/Navigator.php");
//End Include Common Files
class clsRecordusers { //users Class #2-9BE1AF6F
//Variables #2-9E315808
// Public variables
public $ComponentType = "Record";
public $ComponentName;
public $Parent;
public $HTMLFormAction;
public $PressedButton;
public $Errors;
public $ErrorBlock;
public $FormSubmitted;
public $FormEnctype;
public $Visible;
public $IsEmpty;
public $CCSEvents = "";
public $CCSEventResult;
public $RelativePath = "";
public $InsertAllowed = false;
public $UpdateAllowed = false;
public $DeleteAllowed = false;
public $ReadAllowed = false;
public $EditMode = false;
public $ds;
public $DataSource;
public $ValidatingControls;
public $Controls;
public $Attributes;
// Class variables
//End Variables
//Class_Initialize Event #2-627C035C
function clsRecordusers($RelativePath, & $Parent)
{
global $FileName;
global $CCSLocales;
global $DefaultDateFormat;
$this->Visible = true;
$this->Parent = & $Parent;
$this->RelativePath = $RelativePath;
$this->Errors = new clsErrors();
$this->ErrorBlock = "Record users/Error";
$this->DataSource = new clsusersDataSource($this);
$this->ds = & $this->DataSource;
$this->InsertAllowed = true;
if($this->Visible)
{
$this->ComponentName = "users";
$this->Attributes = new clsAttributes($this->ComponentName . ":");
$CCSForm = explode(":", CCGetFromGet("ccsForm", ""), 2);
if(sizeof($CCSForm) == 1)
$CCSForm[1] = "";
list($FormName, $FormMethod) = $CCSForm;
$this->EditMode = ($FormMethod == "Edit");
$this->FormEnctype = "application/x-www-form-urlencoded";
$this->FormSubmitted = ($FormName == $this->ComponentName);
$Method = $this->FormSubmitted ? ccsPost : ccsGet;
$this->btn_register = new clsButton("btn_register", $Method, $this);
$this->username = new clsControl(ccsTextBox, "username", "Soldier", ccsText, "", CCGetRequestParam("username", $Method, NULL), $this);
$this->username->Required = true;
$this->user_email = new clsControl(ccsTextBox, "user_email", "User Email", ccsText, "", CCGetRequestParam("user_email", $Method, NULL), $this);
$this->user_email->Required = true;
$this->user_birthdate = new clsControl(ccsTextBox, "user_birthdate", "User Birthdate", ccsText, "", CCGetRequestParam("user_birthdate", $Method, NULL), $this);
$this->user_birthdate->Required = true;
}
}
//End Class_Initialize Event
//Initialize Method #2-052CBF13
function Initialize()
{
if(!$this->Visible)
return;
$this->DataSource->Parameters["urluid"] = CCGetFromGet("uid", NULL);
}
//End Initialize Method
//Validate Method #2-B7C6592D
function Validate()
{
global $CCSLocales;
$Validation = true;
$Where = "";
$Validation = ($this->username->Validate() && $Validation);
$Validation = ($this->user_email->Validate() && $Validation);
$Validation = ($this->user_birthdate->Validate() && $Validation);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "OnValidate", $this);
$Validation = $Validation && ($this->username->Errors->Count() == 0);
$Validation = $Validation && ($this->user_email->Errors->Count() == 0);
$Validation = $Validation && ($this->user_birthdate->Errors->Count() == 0);
return (($this->Errors->Count() == 0) && $Validation);
}
//End Validate Method
//CheckErrors Method #2-E8847328
function CheckErrors()
{
$errors = false;
$errors = ($errors || $this->username->Errors->Count());
$errors = ($errors || $this->user_email->Errors->Count());
$errors = ($errors || $this->user_birthdate->Errors->Count());
$errors = ($errors || $this->Errors->Count());
$errors = ($errors || $this->DataSource->Errors->Count());
return $errors;
}
//End CheckErrors Method
//Operation Method #2-6BA9892D
function Operation()
{
if(!$this->Visible)
return;
global $Redirect;
global $FileName;
$this->DataSource->Prepare();
if(!$this->FormSubmitted) {
$this->EditMode = $this->DataSource->AllParametersSet;
return;
}
if($this->FormSubmitted) {
$this->PressedButton = "btn_register";
if($this->btn_register->Pressed) {
$this->PressedButton = "btn_register";
}
}
$Redirect = $FileName . "?" . CCGetQueryString("QueryString", array("ccsForm"));
if($this->Validate()) {
if($this->PressedButton == "btn_register") {
if(!CCGetEvent($this->btn_register->CCSEvents, "OnClick", $this->btn_register) || !$this->InsertRow()) {
$Redirect = "";
}
}
} else {
$Redirect = "";
}
if ($Redirect)
$this->DataSource->close();
}
//End Operation Method
//InsertRow Method #2-C62BC29D
function InsertRow()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeInsert", $this);
if(!$this->InsertAllowed) return false;
$this->DataSource->username->SetValue($this->username->GetValue(true));
$this->DataSource->user_email->SetValue($this->user_email->GetValue(true));
$this->DataSource->user_birthdate->SetValue($this->user_birthdate->GetValue(true));
$this->DataSource->Insert();
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterInsert", $this);
return (!$this->CheckErrors());
}
//End InsertRow Method
//Show Method #2-AE9867B3
function Show()
{
global $CCSUseAmp;
$Tpl = CCGetTemplate($this);
global $FileName;
global $CCSLocales;
$Error = "";
if(!$this->Visible)
return;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeSelect", $this);
$RecordBlock = "Record " . $this->ComponentName;
$ParentPath = $Tpl->block_path;
$Tpl->block_path = $ParentPath . "/" . $RecordBlock;
$this->EditMode = $this->EditMode && $this->ReadAllowed;
if($this->EditMode) {
if($this->DataSource->Errors->Count()){
$this->Errors->AddErrors($this->DataSource->Errors);
$this->DataSource->Errors->clear();
}
$this->DataSource->Open();
if($this->DataSource->Errors->Count() == 0 && $this->DataSource->next_record()) {
$this->DataSource->SetValues();
if(!$this->FormSubmitted){
$this->username->SetValue($this->DataSource->username->GetValue());
$this->user_email->SetValue($this->DataSource->user_email->GetValue());
$this->user_birthdate->SetValue($this->DataSource->user_birthdate->GetValue());
}
} else {
$this->EditMode = false;
}
}
if($this->FormSubmitted || $this->CheckErrors()) {
$Error = "";
$Error = ComposeStrings($Error, $this->username->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_email->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_birthdate->Errors->ToString());
$Error = ComposeStrings($Error, $this->Errors->ToString());
$Error = ComposeStrings($Error, $this->DataSource->Errors->ToString());
$Tpl->SetVar("Error", $Error);
$Tpl->Parse("Error", false);
}
$CCSForm = $this->EditMode ? $this->ComponentName . ":" . "Edit" : $this->ComponentName;
$this->HTMLFormAction = $FileName . "?" . CCAddParam(CCGetQueryString("QueryString", ""), "ccsForm", $CCSForm);
$Tpl->SetVar("Action", !$CCSUseAmp ? $this->HTMLFormAction : str_replace("&", "&", $this->HTMLFormAction));
$Tpl->SetVar("HTMLFormName", $this->ComponentName);
$Tpl->SetVar("HTMLFormEnctype", $this->FormEnctype);
$this->btn_register->Visible = !$this->EditMode && $this->InsertAllowed;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeShow", $this);
$this->Attributes->Show();
if(!$this->Visible) {
$Tpl->block_path = $ParentPath;
return;
}
$this->btn_register->Show();
$this->username->Show();
$this->user_email->Show();
$this->user_birthdate->Show();
$Tpl->parse();
$Tpl->block_path = $ParentPath;
$this->DataSource->close();
}
//End Show Method
} //End users Class #2-FCB6E20C
class clsusersDataSource extends clsDBlocalhost { //usersDataSource Class #2-5EDEDCFF
//DataSource Variables #2-8A9D7D42
public $Parent = "";
public $CCSEvents = "";
public $CCSEventResult;
public $ErrorBlock;
public $CmdExecution;
public $InsertParameters;
public $wp;
public $AllParametersSet;
public $InsertFields = array();
// Datasource fields
public $username;
public $user_email;
public $user_birthdate;
//End DataSource Variables
//DataSourceClass_Initialize Event #2-56B8B1F7
function clsusersDataSource(& $Parent)
{
$this->Parent = & $Parent;
$this->ErrorBlock = "Record users/Error";
$this->Initialize();
$this->username = new clsField("username", ccsText, "");
$this->user_email = new clsField("user_email", ccsText, "");
$this->user_birthdate = new clsField("user_birthdate", ccsText, "");
$this->InsertFields["soldier"] = array("Name" => "soldier", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_email"] = array("Name" => "user_email", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_birthdate"] = array("Name" => "user_birthdate", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
}
//End DataSourceClass_Initialize Event
//Prepare Method #2-DC2F5FB8
function Prepare()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->wp = new clsSQLParameters($this->ErrorBlock);
$this->wp->AddParameter("1", "urluid", ccsInteger, "", "", $this->Parameters["urluid"], "", false);
$this->AllParametersSet = $this->wp->AllParamsSet();
$this->wp->Criterion[1] = $this->wp->Operation(opEqual, "uid", $this->wp->GetDBValue("1"), $this->ToSQL($this->wp->GetDBValue("1"), ccsInteger),false);
$this->Where =
$this->wp->Criterion[1];
}
//End Prepare Method
//Open Method #2-B071412E
function Open()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildSelect", $this->Parent);
$this->SQL = "SELECT * \n\n" .
"FROM users {SQL_Where} {SQL_OrderBy}";
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteSelect", $this->Parent);
$this->query(CCBuildSQL($this->SQL, $this->Where, $this->Order));
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteSelect", $this->Parent);
}
//End Open Method
//SetValues Method #2-1C83BB75
function SetValues()
{
$this->username->SetDBValue($this->f("soldier"));
$this->user_email->SetDBValue($this->f("user_email"));
$this->user_birthdate->SetDBValue($this->f("user_birthdate"));
}
//End SetValues Method
//Insert Method #2-D2F97CD9
function Insert()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->CmdExecution = true;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildInsert", $this->Parent);
$this->InsertFields["soldier"]["Value"] = $this->username->GetDBValue(true);
$this->InsertFields["user_email"]["Value"] = $this->user_email->GetDBValue(true);
$this->InsertFields["user_birthdate"]["Value"] = $this->user_birthdate->GetDBValue(true);
$this->SQL = CCBuildInsert("users", $this->InsertFields, $this);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteInsert", $this->Parent);
if($this->Errors->Count() == 0 && $this->CmdExecution) {
$this->query($this->SQL);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteInsert", $this->Parent);
}
}
//End Insert Method
} //End usersDataSource Class #2-FCB6E20C
//Initialize Page #1-2A4101A9
// Variables
$FileName = "";
$Redirect = "";
$Tpl = "";
$TemplateFileName = "";
$BlockToParse = "";
$ComponentName = "";
$Attributes = "";
// Events;
$CCSEvents = "";
$CCSEventResult = "";
$TemplateSource = "";
$FileName = FileName;
$Redirect = "";
$TemplateFileName = "NewPage1.html";
$BlockToParse = "main";
$TemplateEncoding = "UTF-8";
$ContentType = "text/html";
$PathToRoot = "./";
$PathToRootOpt = "";
$Scripts = "|";
$Charset = $Charset ? $Charset : "utf-8";
//End Initialize Page
//Before Initialize #1-E870CEBC
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeInitialize", $MainPage);
//End Before Initialize
//Initialize Objects #1-1F103AC9
$DBlocalhost = new clsDBlocalhost();
$MainPage->Connections["localhost"] = & $DBlocalhost;
$Attributes = new clsAttributes("page:");
$Attributes->SetValue("pathToRoot", $PathToRoot);
$MainPage->Attributes = & $Attributes;
// Controls
$users = new clsRecordusers("", $MainPage);
$MainPage->users = & $users;
$users->Initialize();
$ScriptIncludes = "";
$SList = explode("|", $Scripts);
foreach ($SList as $Script) {
if ($Script != "") $ScriptIncludes = $ScriptIncludes . "<script src=\"" . $PathToRoot . $Script . "\" type=\"text/javascript\"></script>\n";
}
$Attributes->SetValue("scriptIncludes", $ScriptIncludes);
$CCSEventResult = CCGetEvent($CCSEvents, "AfterInitialize", $MainPage);
if ($Charset) {
header("Content-Type: " . $ContentType . "; charset=" . $Charset);
} else {
header("Content-Type: " . $ContentType);
}
//End Initialize Objects
//Initialize HTML Template #1-28F2FDD6
$CCSEventResult = CCGetEvent($CCSEvents, "OnInitializeView", $MainPage);
$Tpl = new clsTemplate($FileEncoding, $TemplateEncoding);
if (strlen($TemplateSource)) {
$Tpl->LoadTemplateFromStr($TemplateSource, $BlockToParse, "UTF-8");
} else {
$Tpl->LoadTemplate(PathToCurrentPage . $TemplateFileName, $BlockToParse, "UTF-8");
}
$Tpl->SetVar("CCS_PathToRoot", $PathToRoot);
$Tpl->block_path = "/$BlockToParse";
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeShow", $MainPage);
$Attributes->SetValue("pathToRoot", "");
$Attributes->Show();
//End Initialize HTML Template
//Execute Components #1-0C9864E9
$users->Operation();
//End Execute Components
//Go to destination page #1-810C207B
if($Redirect)
{
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
header("Location: " . $Redirect);
unset($users);
unset($Tpl);
exit;
}
//End Go to destination page
//Show Page #1-E3A8594F
$users->Show();
$Tpl->block_path = "";
$Tpl->Parse($BlockToParse, false);
if (!isset($main_block)) $main_block = $Tpl->GetVar($BlockToParse);
$main_block = CCConvertEncoding($main_block, $FileEncoding, $TemplateEncoding);
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeOutput", $MainPage);
if ($CCSEventResult) echo $main_block;
//End Show Page
//Unload Page #1-4215F8E1
$CCSEventResult = CCGetEvent ($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
unset($users);
unset($Tpl);
//End Unload Page
?>
You can submit the information via POST. The way you are submitting the data across is from a GET HTTP request. The best thing to do is submit it over via post data. I am assuming your frontend call is using ajax for the form submission? if not and using a simple form change method to POST. If it is using ajax, I would need to know if you are using something like jquery or crafting the XHR request yourself, but if you are doing it that way I would assume you would know the difference.
<form action="action_page.php" method="POST">

Categories