Form doesn't working properly - php

If all inputs are filled, everything works just fine. But if I check just checkbox, the form let me register, no matter I didn't fill all the inputs.
Also if add var_dump to the bottom of the page ( when just checkbox is checked) it says "boolean false " Please help...
<?php
$page_title = 'Registracija'; // Definiše title i h1
$folder = 'registration-db';
if (!file_exists($folder)) {
mkdir($folder, 0777, true);`enter code here`
}
$fajl = $folder . '/registrovani_korisnici.txt';
// Citanje podataka
if (file_exists($fajl)) {
$podaci = file_get_contents($fajl);
$registracija = explode("\n", rtrim($podaci)); //Vracanje података iz baze
}
$errors = false;
//Obrada forme i provera podataka
if (!empty($_POST)) { //ako nije prazna promenljiva
//Provera da li su podaci unešeni
if (empty($_POST['user_name'])) { //radi
$errors[] = 'Niste upisali ime i prezime!<br>';
}
if (empty($_POST['user_email'])) { //radi
$errors[] = 'Niste uneli E-mail!<br>';
}
if (filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL) === false) {// Izbacio !empty($_POST['user_email']) &&
$errors[] = 'Nije validna email adresa!<br>';
}
if (empty($_POST['user_password'])) { //radi
$errors[] = 'Niste uneli lozinku!<br>';
}
if (strlen($_POST[]) <= 5) { //radi
$errors[] = 'Lozinka mora da ima više od 5 karaktera!<br>';
}
if (empty($_POST['user_password2'])) { //radi
$errors[] = 'Niste potvrdili lozinku!<br>';
}
if ($_POST['user_password'] !== $_POST['user_password2']) {
$errors[] = 'Lozinka mora da bude ista u oba pokušaja!';
}
if (empty($_POST['day']) || empty($_POST['month']) || empty($_POST['year'])) { //radi
$errors[] = 'Niste uneli ispravan datum!<br>';
}
if (empty($_POST['check'])) { //radi
$errors[] = 'Niste prihvatili uslove korišćenja!<br>';
}
/*if (date('Y') - $_POST['year'] < 15) {
$errors[] = 'Nemate dovoljno godina, da biste se registrovali!<br>';
}*/ //Problem kada se ne definiše vrednost $_POST['year']!!!!!
else {
// Data forwarding
extract($_POST);
// Name
// Skidanje tagova - Zbog bezbednosti!!!
$user_name = strip_tags($user_name);
//Pretvaranje u mala slova
$user_name = strtolower($user_name);
//Pretvaranje prvih slova u velika (Ime Prezime)
$user_name = ucwords($user_name);
// Čišćenje Email-a
$user_email = strip_tags($user_email);
//Čišćenje Lozinke
$user_password = strip_tags($user_password);
//Čišćenje Lozinke2
$user_password2 = strip_tags($user_password2);
/*html_entity_decode();
htmlentities();*/
$podaci .= $user_name . '#!$!#' . $user_email . '#!$!#' . $user_password . '#!$!#' . $user_password2 . '#!$!#' . $day . '.' . $month . '.' . $year . '#!$!#' . PHP_EOL;
//Zapisivanje u fajl
file_put_contents($fajl, $podaci);
header('Location: registracija.php?sent=1');
}
}
?>
<?php include 'inc/header.php'; //include header?>
<!-- Prikazivanje greške-->
<?php if ($errors !== false) : ?>
<p>GREŠKA: </p>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
<?php endif; ?>
<?php if (isset($_GET['sent']) && $_GET['sent'] == 1): ?>
<h2>Uspešno ste registrovani! Hvala.</h2>
<?php else : ?>
<!-- Form -->
<form action="" method="post">
<p>
<input type="text" name="user_name" placeholder="Ime i prezime">
</p>
<p>
<input type="email" name="user_email" placeholder="E-mail">
</p>
<p>
<input type="password" name="user_password" placeholder="Lozinka">
</p>
<p>
<input type="password" name="user_password2" placeholder="Ponovite lozinku">
</p>
<h2>Datum rodjenja</h2>
<select name="day">
<option selected disabled>Dan</option>
<?php for ($i = 1; $i <= 31; $i++) : ?>
<option> <?php echo $i; ?> </option>
<?php endfor; ?>
</select>
<select name="month">
<option selected disabled>Mesec</option>
<?php for ($i = 1; $i <= 12; $i++) : ?>
<option> <?php echo $i; ?> </option>
<?php endfor; ?>
</select>
<select name="year">
<option selected disabled>Godina</option>
<?php
$start = date("Y");
$end = date("Y") - 100;
?>
<?php for ($i = $start; $i >= $end; $i--) : ?>
<option> <?php echo $i; ?> </option>
<?php endfor; ?>
</select>
<br>
<br>
<input type="checkbox" name="check"> Prihvatam uslove korišćenja
<p>
<button>Registrujte se</button>
</p>
</form>
<?php endif; ?>
<!-- Form END -->
<?php include 'inc/footer.php'; //include footer?>

First of all, you might want to turn you if statements into a if - else if - else chain. In your situation, if last if statement returns false, your former validations become void.
if (empty($_POST['day'])) {
//Validation
}
else if (empty($_POST['year'])) {
//Validation
}
else if (empty($_POST['check'])) {
//Validation
}
// Other validations
else {
}
Also, you should add a value to your checkbox like this:
<input type="checkbox" name="check" value="1" />
This way, if it's checked, it will post a value.
In your current situation, even if checkbox is checked, you don't send any value and your last if statement evaluates to false.
EDIT:
To display all missing fields at once, you just change your else statement into another if-else statements like this:
if (empty($_POST['user_name'])) {
$errors[] = 'Niste upisali ime i prezime!<br>';
}
if (empty($_POST['check'])) {
$errors[] = 'Niste prihvatili uslove korišćenja!<br>';
}
//Other validations
if($errors) {
//Show errors
}
else{
// Data forwarding
// Same as your former else statement
}

It's a small logical error. Your else block is only associated with your last if block. As a result, else will be entered if the last if block is not executed.
If $_POST['check'] is not empty that is if the condition inside the lastif block` returns false then the else will be entered and registration gets completed.
What could you do to get around this?
Use a flag. Declare a variable as $c=1;. We will change the value of this variable to 0 if any if block is entered.
$c=1;
if (empty($_POST['user_name'])) { //radi
$errors[] = 'Niste upisali ime i prezime!<br>';
$c=0;
}
if (empty($_POST['user_email'])) { //radi
$errors[] = 'Niste uneli E-mail!<br>';
$c=0;
}
if (filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL) === false) {// Izbacio !empty($_POST['user_email']) &&
$errors[] = 'Nije validna email adresa!<br>';
$c=0;
}
if (empty($_POST['user_password'])) { //radi
$errors[] = 'Niste uneli lozinku!<br>';
$c=0;
}
if (strlen($_POST[]) <= 5) { //radi
$errors[] = 'Lozinka mora da ima više od 5 karaktera!<br>';
$c=0;
}
if (empty($_POST['user_password2'])) { //radi
$errors[] = 'Niste potvrdili lozinku!<br>';
$c=0;
}
$if ($_POST['user_password'] !== $_POST['user_password2']) {
$errors[] = 'Lozinka mora da bude ista u oba pokušaja!';
$c=0;
}
$if (empty($_POST['day']) || empty($_POST['month']) || empty($_POST['year'])) { //radi
$errors[] = 'Niste uneli ispravan datum!<br>';
$c=0;
}
$if (empty($_POST['check'])) { //radi
$errors[] = 'Niste prihvatili uslove korišćenja!<br>';
$c=0;
}
elseif ($c==1)
{
//CODE
}
else if block will only be entered if $c==1 is true.
You could also use if-elseif-else ladder.
OR:
You can use the required attribute in each input tag to force the users to fill that particular field before submitting.
eg:
<input type="email" name="user_email" Placeholder="Email" required>
Add the required attribute in each input tag to stop the form from getting submitted if a field is not entered.
For example, in the above case, the form wouldn't get submitted if email-id is not entered.

Related

php login form display errors from array

I'm having some trouble displaying my errors on this login form.
The login works but I can't figure out how to display those errors.
I just need to display them between the login field and the footer. I suppose the problem should be the last part of the foreach that should go true the error array.
<!DOCTYPE html>
<html lang="en">
<body>
<?php
include ('includes/header.php');
?>
<div class="nav">
<?php
include ('includes/menu.php');
$error= logInData();
?>
</div>
<section role="main">
<div class="logIn">
<h3>Intranet Login</h3>
</div>
<form action="" method="post">
<fieldset>
<legend>Student Log in</legend>
<div>
<label for="username">Enter username: </label>
<input type='text' id="userN" name="userN" value = "<?php if (isset($error['usern'])){echo $error['usern'];} ?>">
</div>
<div>
<label for="password">Enter password: </label>
<input type='password' id="pass" name="pass" value = "">
</div>
<div>
<p class="red"><?php if (isset($error['both'])) {
echo $error['both'];
} ?></p>
</div>
<div>
<input type="submit" name="submit" value="Log-In">
</div>
</fieldset>
</form>
</section>
<?php
function logInData (){
$error = array();
$validated = array();
$clean = array();
$pass = false;
if (isset($_POST['submit']) && $pass == true) {
$inputPass = ($_POST['pass']);
$trimPass = trim($inputPass);
$inputUsern = ($_POST['userN']);
$trimUsern = trim($inputUsern);
if(!empty($trimPass)){
if (!ctype_alpha($trimPass)) {
$error['passw'] = 'No special characters allowed on password';
$pass = false;
}else{
if(empty($trimPass)){
$error['passw'] = 'password field empty';
$pass = false;
}else{
$clean['passw'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
if(!empty($trimUsern)){
if (!ctype_alpha($trimUsern)) {
$error['userN'] = 'No special characters allowed on username';
$pass = false;
}else{
if(empty($trimPass)){
$error['userN'] = 'username field empty';
$pass = false;
}else{
$clean['userN'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
$dir = '/home/sbau01/public_www/php/fma/data';
if (is_dir($dir)){
$handleDir = opendir('/home/sbau01/public_www/php/fma/data');
$path = "/home/sbau01/public_www/php/fma/data/data.txt";
if(is_file($path)){
$handle = fopen($path, 'r');
while(!feof($handle)){
$dataRow = fgets($handle);
if(!empty($dataRow)){
$separate = explode(' ',$dataRow);
$storedUsern = trim($separate[3]);
$storedPassword = trim($separate[4]);;
if (($clean['userN'] == $storedUsern) && ($clean['passw'] && $storedPassword)){
$match = true;
header('location: intranet.php');
}else{
$error['match']='<span >Username/Password is incorrect!!</span>';
$pass = false;
}
}
}fclose($handle);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}closedir($HandleDir);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}
}else {
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
}
}
?>
<footer>
<?php include ('includes/footer.php');?>
</footer>
</body>
</html>
Its a simple brackets error:
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
The part above is in the else condition of if (isset($_POST['submit']) && $pass == true) {
Thats why this will never execute. Simply remove the bracket above this part and add it after the foreach.
Saving Passwords in text files is NOT a great idea!
In line 101 you have probably an little mistake:
You just check if there are the variables, you dont check if they are equal ($clean['passw'] && $storedPassword)){
A couple of issues identified.
Do you have display errors turned on? https://stackoverflow.com/a/21429652/1246494
You are calling $error= logInData(); at the top, but have your function logInData() { ... } created down below.
I think what you want to do it put the whole function in an include file at the top like:
include ('includes/header.php');
include ('includes/logInFunction.php');
You then want to call logInData(); down in the body.
Another issue is your function puts data in an array and echos data. If you are going to have $error= logInData(); at the top of your page try moving this out of your function and into your body where you want to output the errors.
if(count($error) > 0)
{
foreach($error as $key => $value)
{
echo "ERROR: $value<br />\n";
}
}

multiple message using SESSION

I am working on a small project where I need to validate (server side) a form. With the following code it works well to show the messages "There is A problem" or "There is NO problem". I want now to show the messages like "The name is missing " when the name is missing or "The first name is not valid" when it is not. If many errors occurred, it would show multiple message. Every message must be shown in the same page as the form. I do not know if my explanations are clear.
<?php
echo $_SESSION["errorMsg"];
session_unset("errorMsg");
?>
<form method="post" action="test1.php">
<table class="contactInformation">
<tbody>
<tr>
<td>
<label for="">Nom</label>
</td>
<td>
<input type="text" name="lastName"/>
</td>
</tr>
<tr>
<td>
<label for="">Prénom</label>
</td>
<td>
<input type="text" name="firstName"/>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Envoyer la commande">
</form>
<?php
if (!empty($_POST["lastName"])) {
$lastName = trim($_POST["lastName"]);
if (strlen($lastName) < 2 || 50 < strlen($lastName)) {
$errors = "The name is not valid";
}
}
else {
$errors = "The name is missing";
}
if (!empty($_POST["firstName"])) {
$firstName = trim($_POST["firstName"]);
if (strlen($firstName) < 2 || 50 < strlen($firstName)) {
$errors = "The firstname is not valid";
}
}
else {
$errors = "the firstname is missing";
}
if ($errors != "") {
$_SESSION["errorMsg"] = "There is A problem";
header("Location: test2.php");
exit();
}
else {
$_SESSION["errorMsg"] = "There is NO problem";
header("Location: test2.php");
exit();
}
?>
If you are displaying all errors at one place only, then solution can be:
<?php
$errors = '';
if (!empty($_POST["lastName"])) {
$lastName = trim($_POST["lastName"]);
if (strlen($lastName) < 2 || 50 < strlen($lastName)) {
$errors .= "-The name is not valid. <br/>";
}
}
else {
$errors .= "-The name is missing. <br/>";
}
if (!empty($_POST["firstName"])) {
$firstName = trim($_POST["firstName"]);
if (strlen($firstName) < 2 || 50 < strlen($firstName)) {
$errors .= "-The firstname is not valid. <br/>";
}
}
else {
$errors .= "-the firstname is missing. <br/>";
}
if ($errors != "") {
$_SESSION["errorMsg"] = "There is A problem : <br/>".$errors;
header("Location: test2.php");
exit();
}
else {
$_SESSION["errorMsg"] = "There is NO problem";
header("Location: test2.php");
exit();
}
?>
Otherwise, you can be take errors in array:
<?php
$errors = array();
if (!empty($_POST["lastName"])) {
$lastName = trim($_POST["lastName"]);
if (strlen($lastName) < 2 || 50 < strlen($lastName)) {
$errors['lastname'] = "The name is not valid";
}
}
else {
$errors['lastname'] = "The name is missing";
}
if (!empty($_POST["firstName"])) {
$firstName = trim($_POST["firstName"]);
if (strlen($firstName) < 2 || 50 < strlen($firstName)) {
$errors['firstname'] = "The firstname is not valid";
}
}
else {
$errors['firstname'] = "the firstname is missing";
}
if ($errors != "") {
$_SESSION["errorMsg"]["status"] = "There is A problem";
$_SESSION["errorMsg"]["details"] = $errors;
header("Location: test2.php");
exit();
}
else {
$_SESSION["errorMsg"]["status"] = "There is NO problem";
header("Location: test2.php");
exit();
}
?>

Not able select values which contains space between value name

I am new to PHP and I have problem to select values which have space between for eg TRANSGENDER FtM, if I use TRANSGENDER-MtF then am able to save it. And same with name input, here is the code:
<?php
include_once 'core/init.php';
$general->logged_out_protect();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css" >
<title>Settings</title>
</head>
<body>
<div class="nav-bar" style="box-shadow:0 0 5px 0 rgba(0, 0, 0, 0.4);" >
<?php include 'includes/menu.php'; ?>
</div><!-- NAV BAR DIV closes here -->
<div id="main-wrap" style=" box-shadow:0 0 5px 0 rgba(0, 0, 0, 0.4);">
<div id="container">
<?php
if (isset($_GET['success']) && empty($_GET['success'])) {
echo '<h3>Your details have been updated!</h3>';
} else{
if(empty($_POST) === false) {
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
if (ctype_alpha($_POST['first_name']) === false) {
$errors[] = 'Please enter your First Name with only letters!';
}
}
if (isset($_POST['last_name']) && !empty ($_POST['last_name'])){
if (ctype_alpha($_POST['last_name']) === false) {
$errors[] = 'Please enter your Last Name with only letters!';
}
}
if (isset($_POST['gender']) && !empty($_POST['gender'])) {
$allowed_gender = array('undisclosed', 'Male', 'Female');
if (in_array($_POST['gender'], $allowed_gender) === false) {
$errors[] = 'Please choose a Gender from the list';
}
}
if (isset($_POST['trans']) && empty($_POST['trans'])) {
$allowed_trans = array(
"--Undisclosed--",
"Transperson",
"Transgender",
"Transsexual MtF",
"Transsexual FtM",
"Transvestite MtF",
"Transvestite FtM",
"Intergender",
"Intersexual");
if (in_array($_POST['trans'], $allowed_trans) === false) {
$errors[] = 'Please choose a Trans from the list if Any';
}
}
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
if(empty($errors) === true) {
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name']) && $_POST['use_default'] != 'on') {
$newpath = $general->file_newpath($path, $name);
move_uploaded_file($tmp_name, $newpath);
}else if(isset($_POST['use_default']) && $_POST['use_default'] === 'on'){
$newpath = 'avatars/default_avatar.png';
}
$first_name = htmlentities(trim($_POST['first_name']));
$last_name = htmlentities(trim($_POST['last_name']));
$gender = htmlentities(trim($_POST['gender']));
$bio = htmlentities(trim($_POST['bio']));
$trans = htmlentities(trim($_POST['trans']));
$image_location = htmlentities(trim($newpath));
$users->update_user($first_name, $last_name, $gender, $bio, $image_location, $user_id, $trans);
header('Location: settings.php?success');
exit();
} else if (empty($errors) === false) {
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}
}
?>
<h2>Settings.</h2> <p><b>Note: Information you post here is made viewable to others.</b></p>
<hr />
<form action="" method="post" enctype="multipart/form-data">
<div id="profile_picture">
<h3>Change Profile Picture</h3>
<ul>
<?php
if(!empty ($user['image_location'])) {
$image = $user['image_location'];
echo "<img src='$image'>";
}
?>
<li>
<input type="file" name="myfile" />
</li>
<?php if($image != 'avatars/default_avatar.png'){ ?>
<li>
<input type="checkbox" name="use_default" id="use_default" /> <label for="use_default">Use default picture</label>
</li>
<?php
}
?>
</ul>
</div>
<div id="personal_info">
<h3 >Change Profile Information </h3>
<ul>
<li>
<h4>First name:</h4>
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) ){echo htmlentities(strip_tags($_POST['first_name']));} else { echo $user['first_name']; }?>">
</li>
<li>
<h4>Last name: </h4>
<input type="text" name="last_name" value="<?php if (isset($_POST['last_name']) ){echo htmlentities(strip_tags($_POST['last_name']));} else { echo $user['last_name']; }?>">
</li>
<li>
<h4>Gender:</h4>
<?php
$gender = $user['gender'];
$options = array("undisclosed", "Male", "Female");
echo '<select name="gender">';
foreach($options as $option){
if($gender == $option){
$sel = 'selected="selected"';
}else{
$sel='';
}
echo '<option '. $sel .'>' . $option . '</option>';
}
?>
</select>
</li><br>
<li>
<h4>Trans:</h4>
<?php
$trans = $user['trans'];
$options = array("--Undisclosed--",
"Transperson",
"Transgender",
"Transsexual MtF",
"Transsexual FtM",
"Transvestite MtF",
"Transvestite FtM",
"Intergender",
"Intersexual");
echo '<select name="trans">';
foreach($options as $option){
if($trans == $option){
$sel = 'selected="selected"';
}else{
$sel="";
}
echo '<option '. $sel .'>' . $option . '</option>';
}
?>
</select>
</li><br>
<li>
<h4>Bio:</h4>
<textarea name="bio"><?php if (isset($_POST['bio']) ){echo htmlentities(strip_tags($_POST['bio']));} else { echo $user['bio']; }?></textarea>
</li>
</ul>
</div>
<div class="clear"></div>
<hr />
<span>Update Changes:</span>
<input type="submit" value="Update">
</form>
</div><!-- Container DIV closes here -->
</div><!-- Main Wrap DIV closes here -->
</body>
</html>
<?php
}
In relation to your screenshot, the problem is that your validation on "First name" is working correctly! I would first suggest that in order to make this change, you should change the form to read "First name(s):" to make it clear that any number of first names are allowed in this field. Ideally you should do this with the field name too.
Your code is thus:
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
if (ctype_alpha($_POST['first_name']) === false) {
$errors[] = 'Please enter your First Name with only letters!';
}
}
The function your code uses is ctype_alpha, which does not permit spaces. You could change this to:
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
// Remove spaces from intermediate variable, to permit them
$firstNames = str_replace(' ', '', $_POST['first_name']);
if (ctype_alpha($firstNames) === false) {
$errors[] = 'Please enter your first name(s) with only letters!';
}
}

Strange validation error for form

The error i got was:
Notice: Undefined index: visible in C:\xampp\htdocs\introducingphp\includes\validation_function.php on line 22
It should not happen since i already instantiated all the variables including visible
Validation_function.php
<?php
$errors = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
// * presence
// use trim() so empty spaces don't count
// use === to avoid false positives
// empty() would consider "0" to be empty
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
// * string length
// max length
function has_max_length($value, $max) {
return strlen($value) <= $max;
}
function validate_max_lengths($fields_with_max_lengths) {
global $errors;
// Expects an assoc. array
foreach($fields_with_max_lengths as $field => $max) {
$value = trim($_POST[$field]);
if (!has_max_length($value, $max)) {
$errors[$field] = fieldname_as_text($field) . " is too long";
}
}
}
// * inclusion in a set
function has_inclusion_in($value, $set) {
return in_array($value, $set);
}
?>
new_page.php (the page that has the one-page submit form that does validation)
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
// Can't add a new page unless there is a subject as a parent
if (!$current_subject) {
// subject ID was missing or invalid or
//subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("menu_name", "position", "visible",
"content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 60);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// perform Create
//add the subject_id
$subject_id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//escape content
$content = mysql_prep($_POST["content"]);
// 2. Perform database query
$query .= "INSERT INTO pages (";
$query .= " subject_id, menu_name, position, visible,
content";
$query .= ") VALUES (";
$query .= " {$subject_id}, '{$menu_name}', {$position},
{$visible}, '{$content}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Page Created.";
redirect_to("manage_content.php?subject=" .
urlencode($current_subject["id"]));
}else {
// Failure
$_SESSION["message"] = "Page creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<?php echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Page</h2>
<form action="new_page.php?subject=<?php echo
urlencode($current_subject["id"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$page_set =
find_all_pages_for_subject($current_subject["id"], false);
$page_count = mysqli_num_rows($page_set);
for($count=1; $count <= ($page_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible
<input type="radio" name="visible" value="0" /> NO
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"></textarea>
</p>
<input type="submit" name="submit" value="Create Page" />
</form>
<br />
<a href="manage_content.php?subject=<?php echo
urlencode($current_subject["id"]); ?>">Cancel</a>
</div>
</div>
<?php include("includes/footer.php"); ?>
You probably have a typo on the input HTML field. You can use:
if (isset($_POST[$field])) {
on validate_presences() function to be sure that the value exists.
When you try to do trim($_POST[$field]); you assume, the field exists in the $_POST array - for visible it does not in this case. You could move the trim to has_presence()
function has_presence($value) {
return isset($value) && trim($value) !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Now when you will only have the trim if the variable exists.
Okay, marking the radio check button makes it work now. Thanks for all your inputs guys. It has helped me a great deal.

ISSUE With Utf8 and inserting to mysql

I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
config file
$host = "localhost"; // your mysql server address
$user = ""; // your mysql username
$pass = ""; // your mysql password
$tablename = ""; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>
change the collate and character set to utf8 for the table
alter table <some_table> convert to character set utf8 collate utf8_unicode_ci;

Categories