I am having the following registration script,where I the first name,email etc are inserted in the database via simple html form.
<?php
include("connect.php");
$error = "";
$response[]=array();
if(isset($_POST['submit'])){
$firstName = $_POST['fname'];
$lastName = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$temp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
//echo $firstName."<br/>".$lastName."<br/>".$email."<br/>".$password."<br/>".$passwordConfirm."<br/>".$image."<br/>".$imageSize."<br/>";
if(strlen($firstName)<3){
$error = "First name is too short";
}else if(strlen($lastName)<3){
$error = "Last name is too short";
}else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = "Please enter valid email address";
}else if(strlen($password)<8){
$error = "Password must be greater than 8 characters";
}else if($password !== $passwordConfirm){
$error = "Password does not match";
}else if($image == ""){
$error = "Please upload your image";
}else{
$insertQuery = "INSERT INTO users(firstName,lastName,email,password,image) VALUES('$firstName','$lastName','$email','$password','$image')";
$result = mysqli_query($con,$insertQuery);
if($result){
//upload image in images forlder
$sql = "SELECT * FROM users";
$selectQuery = mysqli_query($con,$sql);
if($selectQuery){
while($row = mysqli_fetch_assoc($selectQuery)){
$response[] = $row;
}
}
if(move_uploaded_file($temp_image,"images/$image")){
$error = "You are successfully regirestered";
}else{
$error = "Image is not uploaded";
}
}
}
}
?>
<?php
echo $error."<br/>";
echo json_encode($response);
?>
All I am doing is validating the form,inserting data and finally selecting all data from the database so they can be represented as a JSON format.
The JSON I am getting is this.
[[],{"id":"37","firstName":"Theo","lastName":"Tziomakas","email":"theo899#gmail.com","password":"testingpass","image":"56a5e6dc-d102-4f9a-bd5b-e6a217e5ad97.png"}]
how can I take the empty array
[]
out of the JSON response ie.
[{"id":"37","firstName":"Theo","lastName":"Tziomakas","email":"theo899#gmail.com","password":"testingpass","image":"56a5e6dc-d102-4f9a-bd5b-e6a217e5ad97.png"}]
Also how can I generate a JSON like this?
{"status":"success","message":"Successfully registered"}
To remove the erroneous [] at the beginning of the JSON structure change this line
$response[]=array();
To
$response = array();
To generate a JSON structure like this
{"status":"success","message":"Successfully registered"}
I would do this
$j = new stdClass();
$j->status = 'success';
$j->message = 'Successfully registered';
$string = json_encode($j);
Related
I've created an mail server with dovecot postfix and mysql.
The user should be able to create a new mail adress via a php webpage which will insert the data into the mysql database.
It also does insert it into the DB, but the connection to the mail server wont work with that credentials.
When I insert the same things myself sirectly into the DB it works, can you please give that code a look and tell me what might be wrong?
I think it has something todo with the password hash generation with doveadm.
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else {
// check email exist or not
$query = "SELECT username FROM accounts WHERE username='$name'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$nameError = "Benutzeraccount existiert schon.";
}
}
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT resetmail FROM accounts WHERE resetmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Kontakt E-Mail Adresse bereits in Verwendung.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = shell_exec('/usr/bin/doveadm pw -s SHA512-CRYPT -p '. $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO accounts(username,domain,at,complete,resetmail,password,quota,enabled,sendonly) VALUES('$name','chillihorse.de','#','test','$email','$password','2048','1','0')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
I have made a Log in and Sign up system and on my localhost it worked properly but when i hosted it and created account it says Incorrect credentials. I will send a code if it is needed. And i have crated a MySql db.
Site link: http://metallicafanpage.esy.es
I am using Hostinger
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: home.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
Here is Register.php
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT userEmail FROM users WHERE userEmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = hash('sha256', $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
This Is Because Of Your Php Mysql version Your Hosting Server Is Just Using An Old Php Or Mysql Version
I am creating a registration form for a project, nothing secure or advanced, i am still fairly new to php etc.
I insert the data needed to into a login table and a customer tbl, the data inserts fine. But i cant get the code to check that its worked and fire off a an email and display a message to the user.
I have tried using a value retrieved from the database which would only be there is the user registered successfuly.
if($userID != null)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
I have also tried this
if($query)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
Thanks,
Edit - Here is all the code,
<?php
include ("inc/mysql.php");
error_reporting(0);
$msg = "";
$col = 'green';
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$name = $email = $chkemail = $password = $chkpassword =$address = $towncity = $postcode = "";
//Required field validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$msg = "Name is required";
$col = 'red';
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$msg = "Email is required";
$col = 'red';
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["chkemail"])) {
$msg = "Please confirm your email address";
$col = 'red';
} else {
$chkemail = test_input($_POST["chkemail"]);
}
if (empty($_POST["password"])){
$msg = "Please enter a password";
$col = 'red';
}
if (empty($_POST["chkpassword"])){
$msg = "Please confirm your password ";
$col = 'red';
} else{
$chkpassword = test_input($_POST["chkpassword"]);
if(($_POST["password"]) != $chkpassword) {
$msg = "Please check your password is correct";
$col = 'red';
} else{
$password = test_input($_POST["password"]);
}
}
if (empty($_POST["address"])) {
$msg = "Please enter the first line of your address";
$col = 'red';
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["towncity"])) {
$msg = "Please enter the first line of your Town or City";
$col = 'red';
} else {
$towncity= test_input($_POST["towncity"]);
}
if (empty($_POST["postcode"])) {
$msg = "Please enter your postcode";
$col = 'red';
} else {
$postcode = test_input($_POST["postcode"]);
$customerVeri = "N";
if($customerVeri == "N"){
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password.substr($email,0,3));
$chkpassword = md5($password.substr($email,0,3));
$verifyLink = md5(substr($name,0,3).substr($email,0,3));
$sql="SELECT customerEmail FROM customer_tbl WHERE customerEmail='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg1 = "Sorry...This email already exists, please enter another or login...";
$col1 = "red";
}
else
{
$query = mysqli_query($db, "INSERT INTO login_tbl (customerEmail, customerPassword)VALUES ('$email', '$password')");
$sql="SELECT userID FROM login_tbl WHERE customerEmail='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$userID = $row['userID'];
$query2 = mysqli_query($db, "INSERT INTO customer_tbl (customerName, userID, customerEmail, customerPassword, customerAddress, customerTowncity, customerPostcode, customerVerified, customerVerifiedlink)VALUES ('$name', '$userID', '$email', '$password','$address','$towncity','$postcode','$customerVeri','$verifyLink')");
echo("Error description: " . mysqli_error($db));
}
}
}
}
if($userID != null)
{
$msg1 = "Thank You! you are now registered, please check your email for a verification link to verify your new account! ";
$col1 = "green";
//require_once "Mail.php";
require_once "inc/email.php";
}
echo '<div style="color:'.$col.'">';
echo $msg;
echo '</div>';
echo '<div style="color:'.$col1.'">';
echo $msg1;
echo '</div>';
?>
Seems there was no issue, but instead an issue with the email.php that stopped the rest of the statement being executed. Now to pick that to bits. Sometimes a few hours away from the screen is all it needs!
Thanks all that answered..
You shouldn't check every statement for the success
The modern programming doesn't work this way. Any statement can report an error in case one occurs. While if there was no error, then everything went all right.
So, just get rid of all conditions and send your email.
I have a form which needs to be validated using php before inserting form values into a database.
it worked just fine if the fields are empty, however when I included a code to ensure only letters and white spaces are allowed in the first and last name fields it broke the validation process i.e. when I typed in any combinations of letters in the fields it displayed an error message saying "only letters and white spaces are required".
Secondly, when all fields are empty, the form displays the appropriate error message and does no submit the form to the database. However, when I type in a message in the textarea field with other fields empty, the form submits the data to the database as well as displays error messages for the other empty fields.
Any help to resolve these issues would be much appreciated.
Here is the code:
<?php
$fnameErr = $lnameErr = $emailErr = $amountErr = $phoneErr = $genderErr = $messageErr = $categoryErr = $countryErr = "";
$fname = $lname = $email = $amount = $phone = $gender = $message = $category = $country = "";
$ipaddress ="";
$defaultMessage = "Please type your message here.";
$formErrors = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//for first name
$name= $_POST["fname"];
if (empty($_POST["fname"])){
$fnameErr = "Please, enter your first name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name)){
$fnameErr = "Only letters and white spaces are allowed in the first name field";
$formErrors = true;
}else{
$fname = $_POST["fname"];
$formErrors = false;
}
//Last Name match
// for last name
$name2= $_POST["lname"];
if (empty($_POST["lname"])){
$lnameErr = "Please, enter your last name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name2)){
$lnameErr = "Only letters and white spaces are allowed in the Last name field";
$formErrors = true;
}else{
$lname = $_POST["lname"];
$formErrors = false;
}
// for email format
$emailf =($_POST["email"]);
if (empty($_POST["email"])) {
$emailErr = "Please, enter your email";
$formErrors = true;
}elseif (!filter_var($emailf, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$formErrors = true;
}else {
$email = $_POST["email"];
$formErrors = false;
}
//for phone
if (empty($_POST["phone"])){
$phoneErr = "Please, enter your phone number";
$formErrors = true;
}else{
$phone = $_POST["phone"];
$formErrors = false;
}
// for amount
if (!isset($_POST["amount"])) {
$amountErr = "You must select an amount";
$formErrors = true;
}
else {
$amount = $_POST["amount"];
$formErrors = false;
}
// for gender
if (!isset($_POST["gender"])) {
$genderErr = "You must select your gender";
$formErrors = true;
}
else {
$gender = $_POST["gender"];
$formErrors = false;
}
// for country
if (empty($_POST["country"]) || $_POST["country"] == "Country") {
$countryErr = "Please, select your country";
$formErrors = true;
}
else {
$country = $_POST["country"];
$formErrors = false;
}
// for category
if (empty($_POST["category"]) || $_POST["category"] == "Category") {
$categoryErr = "Please, select a category";
$formErrors = true;
} else {
$category = $_POST["category"];
$formErrors = false;
}
// for message
if (empty($_POST["message"]) || $_POST["message"] == $defaultMessage){
$messageErr = "Please type your prayer request";
$formErrors = true;
}else{
$message = $_POST["message"];
$formErrors = false;
}
if (empty($formErrors) ) {
//connect to database
require_once("../../includes/connect_to_db.php");
// set time zone to uk
$timezone = date_default_timezone_set("Europe/london");
//setting values
$Timestamp = date('Y-m-d h:i:s');
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$gender = isset($_POST["gender"]) ? $_POST["gender"] : '';
$message = $_POST["message"];
$country = $_POST["country"];
$category = $_POST["category"];
//echo $gender . "value";
//var_dump(billingDate);
// var_dump($customer);
//Escape all string
$firstname = mysqli_real_escape_string($connection, $fname);
$lastname = mysqli_real_escape_string($connection, $lname);
$emailNew = mysqli_real_escape_string($connection, $email);
$phoneNew = mysqli_real_escape_string($connection, $phone);
$genderNew = mysqli_real_escape_string($connection, $gender);
$messageNew = mysqli_real_escape_string($connection, $message);
$countryNew = mysqli_real_escape_string($connection, $country);
$categoryNew = mysqli_real_escape_string($connection, $category);
//querying the database
$query = "INSERT into counselling ( ";
$query .= "Timestamp, FirstName, LastName, ";
$query .= "Email, PhoneNumber, Category, Country, Gender, Message";
$query .= ")";
$query .= "VALUES ('{$Timestamp}', '{$firstname}', '{$lastname}', ";
$query .= "'{$emailNew}', '{$phoneNew}', '{$categoryNew}', '{$countryNew}', '{$genderNew}', '{$messageNew}' ";
$query .= ")";
echo $query;
$result = mysqli_query($connection, $query) ;
//check for query error
if($result){
//query success redirect_to ("somepage.php");
//redirect_to("confirmation.php");
echo "Success";
} else {
die("Database query failed");
}
} // end of if
} // End of form submission conditional.
?>
Your need to refactor your code with proper logic.
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$errors = array();
if(trim($fname) == ''){
$errors['fname'] = "First name is required";
}
if(trim($lname) == ''){
$errors['lname'] = "Last name is required";
}
if(count( $errors) > 0){
//form invalid
}
else{
//form is valid
}
I have a form which when submitted, checks this query ->
if(isset($_POST['update']) && !empty($_POST['name']) && !empty($_POST['reg_name']))
I want to echo a message "Please fill up all the required fields." if the required fields are not filled up.
In short, it should highlight the field name which is not filled up.
The Full Code:
include ('database/abcd.php');
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['update']))
{
$error = array();
if(empty($_POST['name']))
$error[] = 'Please fill name field';
if(empty($_POST['reg_name']))
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1)
{
$name = $_POST['name'];
$reg_name = $_POST['reg_name'];
$established = $_POST['established'];
$industry = $_POST['industry'];
$about = $_POST['about'];
$website = $_POST['website'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$facebook = $_POST['facebook'];
$wiki = $_POST['wiki'];
$twitter = $_POST['twitter'];
$google = $_POST['google'];
$member_username = $_SESSION['username'];
$process="INSERT INTO notifications (member_username, process, icon, class) VALUES ('$_POST[member_username]','$_POST[process]','$_POST[icon]','$_POST[class]')";
if (!mysqli_query($con,$process))
{
die('Error: ' . mysqli_error($con));
}
$sql = "UPDATE `company_meta` SET `name` = '$name', reg_name = '$reg_name', wiki = '$wiki', established = '$established', industry = '$industry', about = '$about', website = '$website', mail = '$mail', phone = '$phone', address = '$address', city = '$city', facebook = '$facebook', twitter = '$twitter', google = '$google' WHERE `member_username` = '$member_username'";
if ($con->query($sql))
{
header('Location: edit.php');
}
}
else
{
$errors = implode(',' $error);
echo $errors;
}
$con->close();
}
I think what you are pass in name or reg_name is check first .may be name or reg_name can content white space so that it not showing message otherwise above code is working correctly..
if(isset($_POST['update'])) // This first check whether it is an update call
{
$error = array(); // Here we initialize an array so that we can put the messages in it.
if(empty($_POST['name'])) // If the name field is empty, push a message in $error array.
$error[] = 'Please fill name field';
if(empty($_POST['reg_name'])) // Same as above field
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1) // Now this checks if the $error array has no value. If it has value it means that either or both of the above fields are empty and the else block will be executed.
{
// Submit your form
}
else
{
$errors = implode(',' $error);
echo $errors;
}
}
else
{
// Update not triggered.
}