Form Validator for empty fields - html

Im having issues with form validation in an empty field. I've included code if there is an error in the php and really thought that would do the trick, but it still submits the form, regardless and redirects to a thank you page.
The form is on: http://www.softwaretestingconference.com/try/register.html
Here is the php:
<?php
$firstnameErr = $lastnameErr = $positionErr = $companynameErr = $address1Err = $postcodeErr = $countryErr = $emailErr = $numberErr = $elecErr = $howManyErr;
$favFruit = array();
$myemail = 'tina.harris#31media.co.uk';//<-----Put Your email address here.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "Please provide your first name";
}
else {
$firstname = $_POST["firstname"];
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Please provide your first name";
}
else {
$lastname = $_POST["lastname"];
}
if (empty($_POST["position"])) {
$positionErr = "Please state your job position";
}
else {
$position = $_POST["position"];
}
if (empty($_POST["companyname"])) {
$companynameErr = "Please state your company's name";
}
else {
$companyname = $_POST["companyname"];
}
if (empty($_POST["address1"])) {
$address1Err = "Please provide an address for your invoice";
}
else {
$address1 = $_POST["address1"];
}
if (empty($_POST['address2'])) {
}
else {
$address2 = $_POST['address2'];
}
if (empty($_POST["postcode"])) {
$postcodeErr = "Please provide a postocde for your invoice";
}
else {
$postcode1 = $_POST["postcode"];
}
if (empty($_POST["country"])) {
$countryErr = "Please provide your country for your invoice";
}
else {
$country = $_POST["country"];
}
if (empty($_POST["email"])) {
$emailErr = "Please provide your email address";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["number"])) {
$numberErr = "Please provide your phone number";
}
else {
$number = $_POST["number"];
}
if (empty($_POST["elec"])) {
$elecErr = "Please provide an electronic signature";
}
else {
$elec = $_POST["elec"];
}
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "NSTC booking: $name";
$email_body = "You have received a new booking from NSTC. ".
" Here are the details: \n Places1: $places1 \n Places2: $places2 \n Places3: $places3 \n Title: $title \n First name: $firstname \n Last name: $lastname \n Position: $position \n Company name: $companyname \n Address1: $address1 \n Address2: $address2 \n Email: $email \n Number: \n $number \n Elec: $elec \n ";
if(isset($_POST['formDoor'])){
if (is_array($_POST['formDoor'])) {
foreach($_POST['formDoor'] as $value){
$email_body .= $value;
}
} else {
$value = $_POST['formDoor'];
$email_body .= $value;
}
}
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: register-thanks.html');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact form handler</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>

Your problem is in the following line (My assumption):
if( empty($errors))
You are not setting anything in the $errors variable.
I would do as follows (I will give you one example, you then have to apply it to each one of your if statements.)
at the beginning of your script, define an empty array:
$errors = array();
and then (this is what you will have to replicate in all your "if" statements:
if (empty($_POST["email"])) {
$errors['mailError'] = "Please provide your email address";
}
else {
$email = $_POST["email"];
}
and at the end of your script:
if (count($errors) === 0) {
//passed, no errors.
} else {
//there are errors. handle them.
}

Related

MYSQL Error, what did i do wrong?

If I remove the or die("MySQL ERROR: ".mysqli_error()); from the code below, it gives me no error. But it also doesn't write to the database.
What am I doing wrong?
ob_start();
session_start();
require ('openid.php');
function logoutbutton() {
echo "<form action=\"steamauth/logout.php\" method=\"post\"><input value=\"Logout\" type=\"submit\" /></form>"; //logout button
}
function steamlogin() {
try {
require("steamauth/settings.php");
$openid = new LightOpenID($steamauth['domainname']);
$button['small'] = "small";
$button['large_no'] = "large_noborder";
$button['large'] = "large_border";
$button = $button[$steamauth['buttonstyle']];
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'http://steamcommunity.com/openid';
header('Location: ' . $openid->authUrl());
}
//echo "<form action=\"?login\" method=\"post\"> <input type=\"image\" src=\"http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_".$button.".png\"></form>";
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
if($openid->validate()) {
$id = $openid->identity;
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
$_SESSION['steamid'] = $matches[1];
include_once("set.php");
$query = mysqli_query("SELECT * FROM users WHERE steamid='".$_SESSION['steamid']."'");
if (mysqli_num_rows($query) == 0) {
mysqli_query("INSERT INTO users (steamid) VALUES ('".$_SESSION['steamid']."')") or die("MySQL ERROR: ".mysqli_error());
}
if (isset($steamauth['loginpage'])) {
header('Location: '.$steamauth['loginpage']);
}
} else {
echo "User is not logged in.\n";
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
}
Here's a screen-shot of my database structure:

Getting json_encode(): type is unsupported, encoded as null

I am working on web services where am using json_encode() to send my response .
It is working fine for every ther web service but I am getting json_encode(): type is unsupported, encoded as null for the following code only.
public function getjobdetailsAction()
{
$this->_helper->layout ()->disableLayout ();
$this->_helper->viewRenderer->setNoRender ( true );
$handle = fopen ( 'php://input', 'r' );
$jsonInput = fgets ( $handle );
$params = Zend_Json::decode ( $jsonInput );
if($params['user_id'] != "" && $params["job_id"] != "")
{
$job_id = $params["job_id"];
$jobObj=Extended\job::getRowObject( $job_id );
//check if job obj exist only then send job array to view.
if($jobObj)
{
$job_detail_r = array();
$job_detail_r['job_id'] = $job_id;
$job_detail_r['job_created_by'] = $jobObj->getIlookUser()->getId();
$job_detail_r['job_title'] = $jobObj->getJob_title();
$job_detail_r['url_fields'] = $jobObj->getUrl_fields();
$job_detail_r['job_reference'] = $jobObj->getJob_reference();
$job_detail_r['company_name'] = $jobObj->getCompany()->getName();
$job_detail_r['responsibilities'] = $jobObj->getResponsibilities();
$job_detail_r['industry_name'] = $jobObj->getIndustryRef()->getTitle();
$job_detail_r['skills_expertise'] = $jobObj->getSkills_n_expertise();
$job_detail_r['country'] = $jobObj->getCountryRef()->getName();
if( $jobObj->getState() )
{
$job_detail_r['state'] = $jobObj->getState()->getName();
}
else
{
$job_detail_r['state'] = "";
}
if($jobObj->getCity())
{
$job_detail_r['city'] = $jobObj->getCity()->getName();
}
else
{
$job_detail_r['city'] = "";
}
//$job_detail_r['job_function'] = $jobObj->getJobFunction()->getDescription();
$job_detail_r['job_description'] = $jobObj->getJob_description();
$job_detail_r['company_description'] = $jobObj->getCompany_desc();
if($jobObj->getSalaryRange())
{
$job_detail_r['salaryRange'] = $jobObj->getSalaryRange()->getCountryRef()->getCurrency_symbol()." ".$jobObj->getSalaryRange()->getMin_salary()." - ".$jobObj->getSalaryRange()->getMax_salary();
}
else
{
$job_detail_r['salaryRange'] = "";
}
$job_detail_r['jobType'] = $jobObj->getJobType()->getName();
//$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getMin_experience()." - ".$jobObj->getExperieneceLevel()->getMax_experience()." Years";
if($jobObj->getExperieneceLevel())
{
$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getDescription();
}
else
{
$job_detail_r['experienceLevel'] = "";
}
$job_detail_r['job_creator_image'] = Helper_common::getUserProfessionalPhoto( $jobObj->getIlookUser()->getId() );
$job_detail_r['time_of_post'] =$jobObj->getCreated_at()->format("Y-m-d H:i:s");
$job_detail_r['job_posted_by'] = $jobObj->getJob_posted_by();
$job_detail_r['apply_from'] = $jobObj->getApply_from();
if($jobObj->getJob_image() != "")
{
$job_detail_r['company_image'] = IMAGE_PATH."/jobs/".$jobObj->getJob_image();
}
else
{
$job_detail_r['company_image'] = IMAGE_PATH.'/no_image.png';
}
$job_detail_r['is_saved'] = Extended\saved_jobs::isJobSavedByMe($job_id,$params['user_id']);
$code = 200;
$msg = "Job details retrieved successfully";
$result = array("jobdetails"=>$job_detail_r);
}
else
{
$code = 301;
$msg = "Error in retrieving details";
}
}
else
{
$code = 301;
$msg = "Missing parameters";
}
echo Helper_common::successFailureMsgs($code,$msg,$result);
exit();
public static function successFailureMsgs( $code, $message, $result = array())
{
if($code == 200)
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"OK","Message"=>$message,"result"=>$result));
}
else
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"Error","Message"=>$message));
}
return Zend_Json::encode($result1);
}
In response I am getting correct response but the above error as well .
Please assist.
Thanks in advance.
For json_encode(), and therefore Zend_Json(), all types are accepted except resource.
So you have debbuger your table to see where the resource is located.
You can try something like this:
foreach ($job_detail_r as $k => $v){
if (is_resource($v))
echo $k . ' => ressource type = ' . get_resource_type($v);
}

Token field json syntax error bootstrap

I have around 700 product list in my Databse table.
I am using bootstrap's tokenfield for auotcomplete, i have to use auto complete in search textbox.
I am getting syntax error :
SyntaxError: missing ] after element list
...B','Lino Perros Men's Leather Wallet - Pink','Lenovo A269i','Lenovo S660 - Tita**
in console.
<?php $t = $this->general_model->auto_complete_sug(); ?>
$( document ).ready(function() {
$('#tokenfield-2').tokenfield({
autocomplete: {
source: <?=$t?>,
delay : 100
},
limit: 1,
minLength: 1,
showAutocompleteOnFocus: true
});
});
<input type="text" class="span2" name="search" id="tokenfield-2" placeholder="Search...">
In my model: I have created this functions:
public function auto_complete_sug()
{
$data = $this->auto_complete_token_fun();
$data1 = explode(',', $data);
$data1 = array_unique($data1);
foreach ($data1 as $value1) {
$temparr[] = $value1;
}
$str = '[';
$c = count($temparr);
$counter = 0;
foreach ($temparr as $val) {
$counter++;
$str .= "'".$val."'";
if($counter < $c){
$str .= ",";
}
}
$str .= ']';
return $str;
}
public function auto_complete_token_fun()
{
// $this->db->query("SET GLOBAL group_concat_max_len = 10000000");
$q = $this->db->query("SELECT GROUP_CONCAT( sub_category_name ) AS scname
FROM `tbl_subcategory` WHERE status = 'Active' ");
if($q->num_rows() > 0)
{
$d = $q->row_array();
return $d['scname'];
}
else
{
return '';
}
}
Please help!!

PHP Unidentified Function script [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
The code I am trying to use is below, Ive double checked it and everything and it keeps saying this error: Fatal error: Call to undefined function Votifier() , I dont know what the problem is here. This is my last resort to ask here, Ive been googling for 2 hours.. Thanks in advance.
<?php
if (isset($_COOKIE['votfed']) && $_COOKIE['vofted'] == 'true') {
exit();
} else {
mysql_connect("", "", "")or die("cannot connect");
mysql_select_db("")or die("cannot select DB");
$result = mysql_query('SELECT * FROM servers WHERE id = "' . $_GET["server"] . '"');
while ($row = mysql_fetch_array($result)) {
$public_key = $row['votifier_key'];
$server_ip = $row['ip'];
$server_port = $row['votifier_port'];
$username = 'USERNAME';
}
$username = preg_replace("/[^A-Za-z0-9_]+/", '', $username);
if (Votifier($public_key, $server_ip, $server_port, $username)) {
echo 'Success!';
} else {
echo 'Error!';
}
ini_set('error_reporting', E_ALL);
function Votifier($public_key, $server_ip, $server_port, $username) {
$public_key = wordwrap($public_key, 65, "\n", true);
$public_key = <<<EOF
-----BEGIN PUBLIC KEY-----
$public_key
-----END PUBLIC KEY-----
EOF;
$address = $_SERVER['REMOTE_ADDR'];
$timestamp = time();
$string = "VOTE\MC-ServerLists.com\n$username\n$address\n$timeStamp\n";
$leftover = (256 - strlen($string)) / 2;
while ($leftover > 0) {
$string .= "\x0";
$leftover--;
}
openssl_public_encrypt($string, $crypted, $public_key);
$socket = fsockopen($server_ip, $server_port, $errno, $errstr, 3);
if ($socket) {
fwrite($socket, $crypted);
return true;
} else
return false;
}
mysql_connect("", "", "")or die("cannot connect");
mysql_select_db("")or die("cannot select DB");
mysql_query('insert into voters (server_id, ipaddress) VALUES ("' . $_GET["server"] . '", "' . $_SERVER['REMOTE_ADDR'] . '")');
}
If you formatted your code correctly, you'd see that the function is conditionally defined, and because of this, its definition must occur before you call the function:
<?php
if (isset($_COOKIE['votfed']) && $_COOKIE['vofted'] == 'true') {
// ...
} else {
// ...
$username = preg_replace("/[^A-Za-z0-9_]+/", '', $username);
if (Votifier($public_key, $server_ip, $server_port, $username)) {
echo 'Success!';
} else {
echo 'Error!';
}
function Votifier($public_key, $server_ip, $server_port, $username)
{
// ...
}
// ...
}
?>
Essentially, you are executing this code:
<?php
if( false) {
} else {
if( foo()) {
echo 'Foo!';
}
function foo() {
return true;
}
}
Which should show you that foo() is not defined until after the else executes, but you call foo() at the beginning of the else block (before it's defined).
Your function should be outside of the if statement, like this:
<?php
function Votifier($public_key, $server_ip, $server_port, $username)
{
// ...
}
if (isset($_COOKIE['votfed']) && $_COOKIE['vofted'] == 'true') {
// ...
} else {
// ...
$username = preg_replace("/[^A-Za-z0-9_]+/", '', $username);
if (Votifier($public_key, $server_ip, $server_port, $username)) {
echo 'Success!';
} else {
echo 'Error!';
}
// ...
}
Alternatively, you can place it at the beginning of the else block, but I wouldn't recommend it from a readability standpoint.

Registering user with PDO

I have a problem while processing the register
Here is the code for the function:
<?php
include $_SERVER['DOCUMENT_ROOT']. "/config/config.php";
$conn = new PDO('mysql:host=' . $ip . ';dbname=' . $database, $username, $password);
function registerUser($username, $password, $passwordagain, $email, $mcname)
{
$validusername= "/^[a-z0-9]+$/";
$validpassword= "/^[A-Za-z0-9]+$/";
$validemail= "/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
$validmcname= "/^[A-Za-z0-9]+$/";
$error = 0;
if(strlen($username)<4 || strlen($username)>24)
{
$error = 1;
}
if(strlen($password)<6 || strlen($password)>24)
{
$error = 1;
}
if(strlen($mcname)<4 || strlen($mcname)>24)
{
$error = 1;
}
if(!preg_match($validusername, $username))
{
$error = 1;
}
if(!preg_match($validpassword, $password))
{
$error = 1;
}
if(!preg_match($validemail, $email))
{
$error = 1;
}
if(!preg_match($validmcname, $mcname))
{
$error = 1;
}
if($password != $passwordagain)
{
$error = 1;
}
$userexistquery = $conn->query('SELECT * FROM users WHERE username=' . $username);
$userexist = $userexistquery->fetch();
if(count($userexist) != 0)
{
$error=1;
echo "<div class='erroralert'>Username already exists!</div>";
}
$emailexistquery = $conn->query('SELECT * FROM users WHERE email=' . $email);
$emailexist = $emailexistquery->fetch();
if($emailexist != 0)
{
$error=1;
echo "<div class='erroralert'>E-mail already exists!</div>";
}
if($error != 1)
{
$encryptedpassword = hash('sha512', $password);
$registeruser = $conn->query("INSERT INTO users(username, password, email, mcname) VALUES ('$username', '$encryptedpassword', '$email', '$mcname')");
echo "<div class='successalert'>Succesfully registred</div>";
}
else
{
echo "<div class='erroralert'>An error occured during registration.</div>";
}
}
?>
The error that gives me is:
Notice: Undefined variable: conn in C:\xampp\htdocs\functions\functions.php on line 45
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\functions\functions.php on line 45
You instantiate your variable $conn outside of the function. You have to pass it as an argument in order to use it inside.