PHP | Input control statements do not do the job - php

I don't understand why I have implemented control instructions in my form that don't work, every time they record in the database all the behaviors that I don't want.
/*ERRORI*/
$nome_obbligatorio = "";
$errore_nome = "";
$cognome_obbligatorio = "";
$errore_cognome = "";
$password_obbligatoria = "";
$due_psw_non_coincidono = "";
$password_err_min_8_caratteri = "";
$password_err_min_8_max_20_caratteri = "";
$errore_password = "";
$citta_obbligatorio = "";
$errore_citta = "";
$cap_obbligatorio = "";
$errore_cap = "";
$errore_cap_caratteri_speciali = "";
$telefono_obbligatorio = "";
$errore_telefono = "";
$iban_obbligatorio = "";
$iban_err_min_27_caratteri = "";
/*FINE ERRORI*/
if(isset($_POST['submit'])) {
/*CAMPI FORM*/
$nome = $connessione->real_escape_string($_POST['nome']);
$cognome = $connessione->real_escape_string($_POST['cognome']);
$password = $connessione->real_escape_string($_POST['password']);
$citta = $connessione->real_escape_string($_POST['citta']);
$cap = $connessione->real_escape_string($_POST['cap']);
$telefono = $connessione->real_escape_string($_POST['telefono']);
$iban = $connessione->real_escape_string($_POST['iban']);
$email = $connessione->real_escape_string($_POST['email']);
$confermaPassword = $connessione->real_escape_string($_POST['confermaPassword']);
$indirizzo = $connessione->real_escape_string($_POST['indirizzo']);
$indirizzo_txt = $connessione->real_escape_string($_POST['indirizzo_txt']);
$civico = $connessione->real_escape_string($_POST['civico']);
$codice_fiscale = $connessione->real_escape_string($_POST['codice_fiscale']);
$categoria_richiesta = $connessione->real_escape_string($_POST['categoria_richiesta']);
/*FINE CAMPI FORM*/
/*----------------------------------------------------*/
if (empty($_POST["nome"])) {
$nome_obbligatorio = "Nome è un campo obbligatorio";
} else {
if (!preg_match("~[0-9]+~", $nome)) {
$errore_nome = "Il nome non può contenere numeri";
}
}
if (empty($_POST["cognome"])) {
$cognome_obbligatorio = "Cognome è un campo obbligatorio";
} else {
if (!preg_match("~[0-9]+~", $cognome)) {
$errore_cognome = "Il cognome non può contenere numeri";
}
}
if (empty($_POST["password"])) {
$password_obbligatoria = "Password è un campo obbligatorio";
} else {
if( strlen($password ) < 8 )
{
$password_err_min_8_caratteri .= "La Password deve contenere almeno 8 caratteri";
}
if( strlen($password ) > 20 )
{
$password_err_min_8_max_20_caratteri .= "La Password può essere composta da 8 fino a 20 caratteri";
}
if( !preg_match("A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}z", $password ) )
{
$errore_password .= "La Password deve contenere almeno una lettera maiuscola una minuscola e un numero";
}
}
if (empty($_POST["citta"])) {
$citta_obbligatorio = "Città è un campo obbligatorio";
} else {
if (!preg_match("#\W+#", $citta)) {
$errore_citta = "Città non può contenere caratteri speciali";
}
}
if (empty($_POST["cap"])) {
$citta_obbligatorio = "CAP è un campo obbligatorio";
} else {
if(!preg_match("#[a-z]+#", $cap ))
{
$errore_cap .= "Il CAP non può contenere lettere";
}
if( !preg_match("#\W+#", $cap ) )
{
$errore_cap_caratteri_speciali .= "Il CAP non può contenere caratteri speciali";
}
}
if (empty($_POST["telefono"])) {
$telefono_obbligatorio = "Telefono è un campo obbligatorio";
} else {
if( !preg_match("#[a-z]+#", $telefono ) )
{
$errore_telefono .= "Il telefono non può contenere lettere";
}
}
if (empty($_POST["iban"])) {
$iban_obbligatorio = "IBAN è un campo obbligatorio";
} else {
if( strlen($password ) < 27 )
{
$iban_err_min_27_caratteri .= "L' IBAN deve contenere almeno 27 caratteri";
}
}
if ($password != $confermaPassword)
$due_psw_non_coincidono = "Le due password non coincidono!";
$CONTROLLA = mysqli_query($connessione,"SELECT email FROM collaboratori WHERE email='$email'");
$SE_IL_RISULTATO_IMMESSO=mysqli_num_rows($CONTROLLA);
if($SE_IL_RISULTATO_IMMESSO==0)
{
$hash = password_hash($password, PASSWORD_BCRYPT);
$connessione->query("INSERT INTO collaboratori
(
nome,
cognome,
email,
password,
citta,
indirizzo,
indirizzo_txt,
civico,
cap,
telefono,
codice_fiscale,
iban,
categoria_richiesta
)
VALUES
(
'$nome',
'$cognome',
'$email',
'$hash',
'$citta',
'$indirizzo',
'$indirizzo_txt',
'$civico',
'$cap',
'$telefono',
'$codice_fiscale',
'$iban'
)");
header("location: index.php?col_reg=Y");
}
else
{
$indirizzo_email_gia_registrato = 'Indirizzo email, già registrato' ;
}
}
for example the field 'nome' and 'cognome', the controls seem non-existent
I can't understand why they fail every time,thanks in advance for your support.

The problem is that you set your error variables, but do not check them before you send the query. You have to write some if() statement before sending the SQL query checking if there were any errors before. One way to do this is to use an array and fill it with error messages:
$errors = array();
if (/*name is invalid */) {
$errors[] = 'Your name is invalid.';
}
if (/*city is invalid */) {
$errors[] = 'Your city is invalid.';
}
if (/*email already used */) {
$errors[] = 'The email address is already being used.';
}
//...
// check if there were any validation errors above.
if (count($errors) > 0) {
// deal with error messages like showing them with 'echo' and `foreach`
} else {
// all fine, send the query.
}

Related

Bind more than one domain via ldap and php

Currently I have a project that authenticates via ldap to modify contact attribute, but only in a single domain, I'm trying to add an implementation so I can identify which domain the user wants to authenticate after informing on a form, example:
domain\user.
Here's how my code treats only one domain.
index.php
<?php
set_time_limit(30);
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
/*
* Function Find user: Procura o usuario no LDAP
*/
$ldap_server = "iphost";
$ldap_binddn = "CN=LDAP Change Info,CN=Users,DC=DOMAIN,DC=com,DC=br";
$ldap_bindpw = "passwordhere";
$ldap_search_dn = "DC=domain,DC=com,DC=br";
function erro($mensagem, $goto_page = "") {
if ($mensagem == "") {
$_SESSION['last_error'] = "";
return;
}else{
$_SESSION['last_error'] = $mensagem;
}
if ($goto_page == "") {
$goto_page = "error.php";
}
include("_include/$goto_page");
die();
}
function modify_user_attribute($userdn, $attributes) {
global $ldap_server;
global $ldap_binddn;
global $ldap_bindpw;
global $ldap_search_dn;
/*
*
* Conexão no servidor LDAP.
*/
#TODO: Fazer conectar em outro servidor caso o primeiro de erro.
$ldap = ldap_connect($ldap_server) or die("LDAP Server connect error.");
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
$ret = false;
if ($ldap) {
$ldapbind = ldap_bind($ldap, $ldap_binddn, $ldap_bindpw);
if ($ldapbind) {
$ret = ldap_modify($ldap, $userdn, $attributes);
ldap_close($ldap);
}
}
return $ret;
}
function check_value($value, $name) {
if ($value == null) {
erro("Atributo $name não pode ser nulo", "modify.php");
}
if ($value == "") {
erro("Atributo $name não pode ser vazio", "modify.php");
}
if (strlen($value) > 20) {
erro("Atributo $name não pode conter mais do que 20 caracteres.", "modify.php");
}
}
function find_and_auth_user($login, $senha) {
global $ldap_server;
global $ldap_binddn;
global $ldap_bindpw;
global $ldap_search_dn;
$ldap_user_to_find = "";
$ldap_user_pass = "";
$ldap_user_dn = "";
/*
*
* Conexão no servidor LDAP.
*/
#TODO: Fazer conectar em outro servidor caso o primeiro de erro.
$ldap = ldap_connect($ldap_server) or die("LDAP Server connect error.");
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
if (!$ldap) {
//Redirecionar o usuário para uma tela de erro de sistema.
}
# Find
$ldapbind = ldap_bind($ldap, $ldap_binddn, $ldap_bindpw);
if ($ldapbind) {
$ldap_search_filter = "(sAMAccountName=$login)";
$result = ldap_search($ldap, $ldap_search_dn, $ldap_search_filter) or erro("Erro de sistema");
$data = ldap_get_entries($ldap, $result);
if ($data["count"] == 1) {
$ldap_user_dn = $data[0]["dn"];
# print "Encontrado usuário: " . $ldap_user_dn . "\n";
$ldapbind2 = ldap_bind($ldap, $ldap_user_dn, $senha);
if ($ldapbind2) {
$result = ldap_search($ldap, $ldap_user_dn, $ldap_search_filter) or erro("Erro de sistema");
$data = ldap_get_entries($ldap, $result);
/*
* Salva na sessão os dados encontrados.
*/
$_SESSION['dn'] = $ldap_user_dn;
$_SESSION['telephonenumber'] = $data[0]["telephonenumber"][0];
$_SESSION['ipphone'] = $data[0]["ipphone"][0];
$_SESSION['last_error'] = "";
return true;
}else{
#Redireciona o usuário para página de erro de login e senha.
erro("Usuário ou senha incorreta.", "login.php");
}
}else{
erro("Usuário ou senha incorreta.", "login.php");
}
}
ldap_close($ldap);
}
#
#
# SINGLE PAGE APP
#
#
#
if (session_id() == "") {
session_start();
//GET = Formulario de LOGIN
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$_SESSION['last_error'] = "";
include("_include/login.php");
return;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//POST do formulario de LOGIN
if (isset($_POST['username']) && isset($_POST['password'])) {
if (find_and_auth_user($_POST['username'], $_POST['password'])){
include("_include/modify.php");
}
return;
}
//POST do formulario de CHANGE
if (isset($_GET['change']) && $_GET['change'] == "true") {
$values["telephonenumber"][0] = $_POST['telephonenumber'];
$values["ipphone"][0] = $_POST['ipphone'];
check_value($values["telephonenumber"][0], "Telefone");
check_value($values["ipphone"][0], "Ramal");
if ($_SESSION['dn'] == null) {
erro("Erro de sistema. DN nula.", "login.php");
}
if ($_SESSION['dn'] == "") {
erro("Erro de sistema. DN nula.", "login.php");
}
if (modify_user_attribute($_SESSION['dn'], $values)) {
include("_include/success.php");
return;
}else{
erro("Erro alterando atributos.", "modify.php");
}
}
}
}else{
include("_include/modify.php");
return;
}
?>
Here's how I'm thinking of using it to authenticate to more than one domain:
teste.php
<?php
$username = $_POST['username'];
$arr = explode("\\", $login);
echo "Dominio = " .strtoupper($arr[0]) ."\n";
echo "Login = $arr[1]\n";
$conf = array();
$conf["DOMAIN1"]["LDAP_SERVER"] = "iphost";
$conf["DOMAIN1"]["BIND_DN"] = "CN=LDAP Change Info,CN=Users,DC=domain1,DC=com,DC=br";
$conf["DOMAIN1"]["BIND_PWD"] = "passwordhere";
$conf["DOMAIN1"]["SEARCH_DN"] = "DC=domain1,DC=com,DC=br";
$conf["DOMAIN2"]["LDAP_SERVER"] = "iphost";
$conf["DOMAIN2"]["BIND_DN"] = "CN=LDAP Change Info,CN=Users,DC=domain2,DC=com,DC=br";
$conf["DOMAIN2"]["BIND_PWD"] = "passwordhere";
$conf["DOMAIN2"]["SEARCH_DN"] = "DC=domain2,DC=com,DC=br";
$conf["DOMAIN3"]["LDAP_SERVER"] = "iphost";
$conf["DOMAIN3"]["BIND_DN"] = "CN=LDAP Change Info,CN=Users,DC=domain3,DC=com,DC=br";
$conf["DOMAIN3"]["BIND_PWD"] = "passwordhere";
$conf["DOMAIN3"]["SEARCH_DN"] = "DC=domain3,DC=com,DC=br";
#var_dump($conf);
$dominio = strtoupper($arr[0]);
if ( empty($conf[$dominio]["LDAP_SERVER"])) {
die("Domain $dominio not found\n");
}
//echo "auth domain " .$conf[$dominio]["LDAP_SERVER"] ."\n";
I would like to know how it would be possible to join the raciocio line to be able to log in to other domains.
I want to openly publish this code, it can help a lot of people.

PHP Warning: ibase_query(): supplied resource is not a valid Firebird/InterBase link resource

When I submit the form of register new user or new client, this message error appears.
I'm using PHP 7.1.5 with IIS Server in a Windows 10 OS. The same code was working correctly and stop work from nothing.
Somebody can help me?
Here is the code:
enter code here
<?php
if (!isset($_SESSION)) {
session_start();
}
// Verifica se não há a variável da sessão que identifica o usuário
if (!isset($_SESSION['UsuarioID'])) {
// Destrói a sessão por segurança
session_destroy();
// Redireciona o visitante de volta pro login
header("Location: login.php"); exit;
}
if(isset($_POST['submit'])) {
$nome = $_POST['txt_nome'];
$email = $_POST['txt_email'];
$password = $_POST['txt_password'];
$cpassword = $_POST['txt_cpassword'];
$nivel = $_POST['txt_nivel'];
$pass=strcmp($password,$cpassword);
if($pass == 0){
$senha = md5($password);
}else{
echo 'As Senhas Não Conferem. Verifique!';
}
if ($nivel == '1 - Diretoria') {
$nivel = 1;
}else if ($nivel == '2 - Gerência'){
$nivel = 2;
}else if ($nivel == '3 - Usuários'){
$nivel = 3;
}
$cad_usur = "INSERT INTO C_USUR
(C_USUR_USUR,C_USUR_STUS,C_USUR_NOME,C_USUR_LGIN,C_USUR_PSWD,C_USUR_NIVL)
VALUES ((SELECT S_CONT_CONT FROM
SP_PROX_NRMO('0001','C_USUR')),'1','$nome','$email','$senha','$nivel')";
$insert_usur = ibase_query($cad_usur);
if($cad_usur == true){
echo 'Cadastro Realizado Com Sucesso';
}else{
echo 'Não foi possível cadastrar o usuário. Verifique!';
}
}
?>

PHP/Mysql Can't update database

The problem is that I can't update the database using this code. It seems that the UPDATE query don't recognize $id variable. I try to put it in the if cycle but still don't recognize it.
Here I put the code for update the database and to retrieve data from it to show in the form fields. The script is executed but it doesn't update the database.
<?php
session_start();
require_once("../config.php");
require_once("../database.php");
//inserisci dati in tabella utenti
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$id=isset($_GET['id']) ? intval($_GET['id']) : "";
if ($_SERVER["REQUEST_METHOD"] == "POST" ) {
$error_message = "";
//primo controllo campi inseriti con funzione test_input
if(isset($_POST['nome'])) {
$nome = test_input($_POST['nome']);
} else {
$error_message = "Devi inserire il tuo nome.<br/>";
}
if(isset($_POST['cognome'])) {
$cognome = test_input($_POST['cognome']);
} else {
$error_message = "Devi inserire il tuo cognome.</br>";
}
if(isset($_POST['paese'])) {
$paese = test_input($_POST['paese']);
} else {
$error_message = "Devi inserire il paese di residenza.</br>";
}
if(isset($_POST['provincia'])) {
$provincia = test_input($_POST['provincia']);
} else {
$error_message = "<p>Devi inserire la provincia di residenza.</br>";
}
if(isset($_POST['citta'])) {
$citta = test_input($_POST['citta']);
} else {
$error_message = "Devi inserire la città di residenza.</br>";
}
if(isset($_POST['telefono'])) {
$telefono = intval(test_input($_POST['telefono']));
} else {
$error_message = "Devi inserire un recapito telefonico.</br>";
}
if(isset($_POST['indirizzo'])) {
$indirizzo = test_input($_POST['indirizzo']);
} else {
$error_message = "Devi inserire il tuo indirizzo di residenza.</br>";
}
if(isset($_POST['cap'])) {
$cap = intval(test_input($_POST['cap']));
} else {
$error_message = "Devi inserire il tuo cap.</br>";
}
if(isset($_POST['cf'])) {
$cf = test_input($_POST['cf']);
} else {
$error_message = "Devi inserire il tuo codice fiscale.</br>";
}
//if(!isset($error_message)) {
$results1 = $db->prepare("UPDATE utenti SET
nome = :nome,
cognome = :cognome,
cf = :cf,
paese = :paese,
provincia = :provincia,
citta = :citta,
indirizzo = :indirizzo,
cap = :cap,
telefono = :telefono
WHERE id = " . $id);
$results1->bindParam(':nome',$nome);
$results1->bindParam(':cognome',$cognome);
$results1->bindParam(':cf',$cf);
$results1->bindParam(':paese',$paese);
$results1->bindParam(':provincia',$provincia);
$results1->bindParam(':citta',$citta);
$results1->bindParam(':indirizzo',$indirizzo);
$results1->bindParam(':cap',$cap);
$results1->bindParam(':telefono',$telefono);
$results1->bindParam(':id',$id);
if($results1->execute()) {
header("Location:aggiorna.php?aggiorna=ok");
exit;
} else {
$error_message = "Problema nell'inserimento nel database: ";
header("Location:aggiorna.php?");
}
//}
}
$results = $db->prepare("SELECT * FROM utenti WHERE id= ?");
$results->bindParam(1,$id);
$results->execute();
$dati = $results->fetch(PDO::FETCH_ASSOC);
Change from
WHERE id = " . $id);
To
WHERE id = :id ");

How to validate my contact form?

I used this code to connect my contact form to mysql but the problem is I don't know how to validate each item like the name has to be fill or the email should be valid so it will not bother me later when I take care all of it, here is my code :can you help me :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
You should have client side validation (e.g using jquery)
and in your php you can try like this:
if(!empty($_POST['lastname']) && !empty($_POST['age']) && !empty($_POST['firstname']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('mysqli_real_escape_string($con,$_POST[firstname])','mysqli_real_escape_string($con,$_POST[lastname])','mysqli_real_escape_string($con,$_POST[age])')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
You can validate email in php like this:
filter_var($emailAddress, FILTER_VALIDATE_EMAIL)
php filter
For proper validation of a form, some aspects have to be taken into account, to help filter an excess of garbage input. My approach is this:
First of all, check the minimum lenght of the text. This way, you decrease the risk of getting meaningless input. Secondly, check the maximum lenght of the text; you don't want someone flooding your database with a ton of text just for fun. And thirdly, you should use regular expressions to check proper formats for the different fields (a postal code, a phone number, an e-mail) and very important, allow only characters that are required in that field, to avoid or minimize the risk of someone sending miserable cross-site injections thru the input.
Here an orientative example:
function validate_form() {
$errors = array();
// El nombre del usuario es necesario
if (! strlen(trim($_POST['user_name']))) {
$errors[] = 'The username is required.';
}
// El nombre del usuario no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z0-9_\- ]#', trim($_POST['user_name']))) {
$errors[] = 'The username cannot contain invalid characters.';
}
// El nombre del usuario no debe tener menos de 3 caracteres
if (strlen(trim($_POST['user_name'])) < 3) {
$errors[] = 'The username cannot have less than 3 characters long.';
}
// El nombre del usuario no debe tener más de 24 caracteres
if (strlen(trim($_POST['user_name'])) > 24) {
$errors[] = 'The username cannot have more than 24 characters long.';
}
// La contraseña es necesaria
if (! strlen(trim($_POST['password']))) {
$errors[] = 'The password is required.';
}
// La contraseña no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z0-9_\-]#', trim($_POST['password']))) {
$errors[] = 'The password cannot contain invalid characters.';
}
// La contraseña no debe tener menos de 6 caracteres
if (strlen(trim($_POST['password'])) < 6) {
$errors[] = 'The password cannot have less than 6 characters long.';
}
// La contraseña no debe tener más de 12 caracteres
if (strlen(trim($_POST['password'])) > 12) {
$errors[] = 'The password cannot have more than 12 characters long.';
}
// La contraseña debe contener letras y números
if (! preg_match('/([a-zA-Z][0-9]|[0-9][a-zA-Z])+/', trim($_POST['password']))) {
$errors[] = 'The password must contain letters and numbers.';
}
// Password y Password Check deben ser iguales
if ($_POST['password'] != $_POST['password_check']) {
$errors[] = 'Password and Password Check do not match.';
}
// El correo electrónico es necesario
if (! strlen(trim($_POST['e_mail']))) {
$errors[] = 'The e-mail is required.';
}
// El correo electrónico no debe contener caracteres problemáticos
if (preg_match('/[^a-zA-Z0-9_\-#\.]/', trim($_POST['e_mail']))) {
$errors[] = 'The e-mail cannot contain invalid characters.';
}
// El correo electrónico no debe tener más de 64 caracteres
if (strlen(trim($_POST['e_mail'])) > 64) {
$errors[] = 'The e-mail cannot have more than 64 characters long.';
}
// El correo electrónico debe tener un formato correcto
if (! preg_match('/[^#\s]{3,}#([-a-z0-9]{3,}\.)+[a-z]{2,}/', trim($_POST['e_mail']))) {
$errors[] = 'The e-mail must have a valid format.';
}
// El país seleccionado debe ser válido
if (! array_key_exists($_POST['country'], $GLOBALS['countries'])) {
$errors[] = 'Please select a valid country.';
}
// La ciudad es necesaria
if (! strlen(trim($_POST['city']))) {
$errors[] = 'The city is required.';
}
// La ciudad no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z\- ]#', trim($_POST['city']))) {
$errors[] = 'The city cannot contain invalid characters.';
}
// La ciudad no debe tener menos de 3 caracteres
if (strlen(trim($_POST['city'])) < 3) {
$errors[] = 'The city cannot have less than 3 characters long.';
}
// La ciudad no debe tener más de 64 caracteres
if (strlen(trim($_POST['city'])) > 64) {
$errors[] = 'The city cannot have more than 64 characters long.';
}
// El mes seleccionado debe ser válido
if (! array_key_exists($_POST['month'], $GLOBALS['months'])) {
$errors[] = 'Please select a valid month.';
}
// El día seleccionado debe ser válido
if (! array_key_exists($_POST['day'], $GLOBALS['days'])) {
$errors[] = 'Please select a valid day.';
}
// El año seleccionado debe ser válido
if (! array_key_exists($_POST['year'], $GLOBALS['years'])) {
$errors[] = 'Please select a valid year.';
}
// El nombre real del usuario es necesario
if (! strlen(trim($_POST['real_name']))) {
$errors[] = 'Your real name is required.';
}
// El nombre real del usuario no debe contener caracteres problemáticos
if (preg_match('#[^a-zA-Z\- ]#', trim($_POST['real_name']))) {
$errors[] = 'Your real name cannot contain invalid characters.';
}
// El nombre real del usuario debe tener menos de 3 caracteres
if (strlen(trim($_POST['real_name'])) < 3) {
$errors[] = 'Your real name cannot have less than 3 characters long.';
}
// El nombre real del usuario no debe tener más de 64 caracteres
if (strlen(trim($_POST['real_name'])) > 64) {
$errors[] = 'Your real name cannot have more than 64 characters long.';
}
// El número CAPTCHA introducido debe ser correcto
$captcha_num_1 = substr($_POST['captcha'], 0, 1);
$captcha_num_2 = substr($_POST['captcha'], 1, 1);
$captcha_num_3 = substr($_POST['captcha'], 2, 1);
$captcha_num_4 = substr($_POST['captcha'], 3, 1);
$captcha_num_5 = substr($_POST['captcha'], 4, 1);
if (($_SESSION['num1'] != crypt($captcha_num_1, $_SESSION['num1'])) ||
($_SESSION['num2'] != crypt($captcha_num_2, $_SESSION['num2'])) ||
($_SESSION['num3'] != crypt($captcha_num_3, $_SESSION['num3'])) ||
($_SESSION['num4'] != crypt($captcha_num_4, $_SESSION['num4'])) || ($_SESSION['num5'] != crypt($captcha_num_5, $_SESSION['num5']))) {
$errors[] = 'The CAPTCHA number entered is not correct.';
}
// El nombre de usuario y la dirección de e-mail deben ser únicos en la base de datos
global $db;
$sql = 'SELECT user_name, e_mail FROM users';
$q = mysqli_query($db, $sql);
if (mysqli_num_rows($q) > 0) {
while ($users = mysqli_fetch_object($q)) {
if ($users->user_name == $_POST['user_name']) {
$errors[] = 'This username already exists in the database. Please use a different one.';
}
if ($users->e_mail == $_POST['e_mail']) {
$errors[] = 'This e-mail address already exists in the database. Please use a different one.';
}
}
}
// Si hay errores, resetear el CAPTCHA
if (is_array($errors)) { reset_captcha();
}
return $errors;
}
Please find the following answer
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$c=0;
if($_POST['firstname']=="")
{
$msg='Please enter firstname';
$c++;
}
if($_POST['lastname']=="")
{
$msg1='Please enter lastname';
$c++;
}
if($_POST['age']=="")
{
$msg2='Please enter age';
$c++;
}
if($c==0)
{
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
Print $msg,$msg1,$msg2 in respective places

Unable to edit ints

I'm building an admin panel in PHP. I'm new to PHP and I can't get my edit page to work as I need it to. I can edit the name, but 2 values which represent "Active User" and "Access Level" are set to 0 and I can't change it from 0 on my edit page, only from PhpmyAdmin..
<?php
// Inserir o registo na BD
include_once ('config1.php');
// Estabelecer a ligação à BD
$connection = new mysqli('localhost', 'root', '123456', 'admin1');
//Verificar se a ligação foi estabelecida com sucesso
if (mysqli_connect_errno() ) {
echo "</h2>Erro no acesso a BD</h2>" . mysqli_connect_error();
exit();
}
// Validar se os campos do formulário foram preenchidos pelo utilizador
// Verificar se "username" foi enviado
if (isset($_POST['iusername']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$username = trim($_POST['iusername']);
}
if (isset($_POST['inome']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$nome = trim($_POST['inome']);
}
if (isset($_POST['inivel']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$apelido = trim($_POST['inivel']);
}
if (isset($_POST['iativo']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$telefone = trim($_POST['iativo']);
}
if (isset($_POST['iemail']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$email = trim($_POST['iemail']);
}
if (isset($_POST['ipass']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$pass = trim($_POST['ipass']);
}
if (isset($_POST['irpass']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$repass = trim($_POST['irpass']);
}
// Função de validação do email (chamada mais abaixo no código)
function isValidEmail($email){
return #eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z] {2,3})", $email);
// Validar se o nº de caracteres do "username" está entre 4 e 12
if (strlen($username) < 4 || strlen($username) > 12) {
$erro = true;
$msgerro .= "<p>erro: \"username\" deve conter entre 4 e 12 caracteres</p>";
}
// Validar se o nome tem entre 3 e 40 caracteres
if (strlen($nome) < 3 || strlen($nome) > 40) {
//echo (strlen($nome));
$erro = true;
$msgerro .= "<p>erro: \"nome\" deve conter entre 3 a 40 caracteres</p>";
}
// Validação das passwords
$mudapass = false;
if (strlen($password) == 0 && strlen($rpassword) == 0) {
$mudapass = false;
} else {
$mudapass = true;
}
// 2.2. Validar o tamanho da password
if (strlen($password) < 4 || strlen($password)> 16) {
$erro = true;
$msgerro .= "<p>erro: \"password\" deve conter entre 4 a 16 caracteres</p>";
}
}
// 3. Validar se as duas passwords correspondem
if ($password != $rpassword) {
$erro = true;
$msgerro .= "<p>\"passwords\" não correspondem</p>";
}
// validação de email
// Chama a nova função "isValidEmail"
if (isValidEmail($email) == false) {
$erro = true;
$msgerro .= "<p>email inválido</p>";
}
// Final das validações (avisa caso algum erro seja detectado)
if ($erro) {
echo "<p>Formulário submetido com erros</p>";
echo $msgerro;
echo "<br>";
// Desenha 2 botões "Corrigir" e "Listar"
echo "<a class='ains' href='javascript:history.go(-1)' title='Volta à página anterior'>Corrigir </a>";
echo "<br/>";
echo "<a class='ains' href='lista.php'>Listar</a>";
exit();
}
if($password != $rpassword){
echo "ERRO: PASSWORDS SAO DIFERENTES";
}
$sql= "UPDATE usuarios SET
nome = '$nome';
email = '$email';
nivel = '$nivel';
ativo = '$ativo';
WHERE
usuario = '$username'";
if ($mudapass == TRUE) {
$sql = "UPDATE usuarios SET nome = '$nome',
password = '$password',
email = '$email',
nivel = '$nivel',
ativo = '$ativo', WHERE usuario = '$username'";
}
if ($mudapass == FALSE) {
$sql = "UPDATE usuarios SET
nome = '$nome',
email = '$email',
nivel = '$nivel',
ativo = '$ativo'
WHERE
usuario = '$username'";
}
$connection->query($sql);
// Lista users depois de actualizar
header("location:lista.php");
?>
It looks like a naming problem. Two of your variables don't seem to follow the same convention as the rest of them, and unless I'm missing some extra processing before the query, then you should change these two lines:
$apelido = trim($_POST['inivel']);
// ...several lines later
$telefone = trim($_POST['iativo']);
to this:
$nivel = trim($_POST['inivel']);
// ...several lines later
$ativo = trim($_POST['iativo']);

Categories