Clearing whitespace for user input data when posting to table - php

I am trying to clear whitespace and add a '#' character at the beginning when the user inputs a name to post to the database.
I already have a working script to allow users to input data and modify it, but I want to include a script where the whitespace is cleared and a '#' is added before the name.
E.g. If user inputs 'John Whatsmyname' - it will be posted as - #JohnWhatsmyname in the table
I thought it would just be as simple as adding something like this;
$name = ($_POST['name']);
$name = '#'.str_replace(' ', '', $name);
$name = preg_replace('/\s+/', '', $name);
Currently I have the following HTML;
<input type="text" value="<?php echo $user_data['name']; ?>" placeholder="username" name="name"/>
<input type="text" value="<?php echo $user_data['email']; ?>" placeholder="Email" name="email"/>
Full PHP script:
<?php
if (empty($_POST) === false) {
$required_fields = array('name', 'email');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Name & email are required';
break 1;
}
}
$name = ($_POST['name']);
$name = '#'.str_replace(' ', '', $name);
$name = preg_replace('/\s+/', '', $name);
<?php
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
echo 'Your details have been updated!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$update_data = array(
'info' => $_POST['info'],
'website' => $_POST['website'],
'location' => $_POST['location'],
$name => $_POST['name'],
'email' => $_POST['email'],
);
update_user($session_user_id, $update_data);
header('Location: profile.php?success');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
}
?>
I think when I am applying the changes I am doing nothing with then therefore the script continues and updates the table with the original data - I have echoed the $name variable and I get the error undefined variable.
The script needs to change the name by putting a '#' at the beginning and removes all whitespace not just the beginning and end before posting to the table. Trying to avoid error messages and have a script to fix the problem.
Thanks (Y)

You are not seeing it work because you do all the work to process $name, and then your $update_data array goes and pulls a fresh copy from the global $_POST array. Instead, you should change it to this:
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
if (empty($name))
{
die('No name provided');
}
// Format name
$name = '#'.str_replace(' ', '', $name);
$update_data = array(
'info' => $_POST['info'],
'website' => $_POST['website'],
'location' => $_POST['location'],
'name' => $name,
'email' => $_POST['email'],
);

Related

How to check if value exist in json file using php?

<?php
if(isset($_POST['submit']))
{
$file = 'entries.json';
$json_file = file_get_contents($file);
$parsed_json = json_decode($json_file, true);
$email = $_POST['email'];
$flag = false;
foreach ($parsed_json as $key => $value)
{
if ($value['email'] == $email)
{
$flag = true;
break;
}
}
if ($flag)
{
$arr = array(
"centre" => $_POST['centre'],
"name" => $_POST['name'],
"email" => $_POST['email'],
"phone" => $_POST['phone'],
"city" => $_POST['city'],
"course" => $_POST['course']
);
$json_string = json_encode($arr);
$success = file_put_contents($file, $json_string);
if($success == true)
{
echo "<p class='text-success'>Thank you for showing interest. Please contact your counsellor for Unique Registration Number (URN)<p>";
}
}
else
{
echo "<p class='text-danger'>Email already exist.<p>";
}
}
?>
In the above code I am trying to validate with email id already exist when we post form data in json format. Here, Json format working perfectly but it always show thank you message. If email exist or not.
When I click on submit then all data post and convert in json successfully and I am fetching this data in other website but I want to show here that email id already exist. So, How can I do this? Please help me.
Thank You

Problem with uploading multiple photos into database through pivot table

I am working on a cms for properties/ads in oop php for learning purposes. I am trying to upload multiple photos that are connected through pivot table with specific property but I am having trouble inserting those photos. I need when I insert property with two or more photos that those photos have diiferent ids in pivot table but the same id for property. I succeeded with one photo at the time, but with multiple I get errors:
Warning: explode() expects parameter 2 to be string, array given in
C:\xampp\htdocs\App\Models\Ad.php on line 177 when I var dump $tmp
variable I get null and
Warning: end() expects parameter 1 to be array, null given in
C:\xampp\htdocs\App\Models\Ad.php on line 179 when I var dump
$file_ext variable I get empty string
I am using three tables to do that. photos (name, extension, created_at, updated_at), property_photo (property_id, photo_id), properties (title, description, type_of_property, use_of_the_property, quadrature, location...). Here is my code:
Ad Model:
public function createAd($data, $pht)
{
if (isset($data['photoExtension'])) {
$this->photoExtension = preg_replace('~(?<=a)\w~', "", $data['photoExtension']);
}
$this->photoExtension = strtolower(strrchr( $pht, '.' ));
$this->db->query("INSERT INTO properties (title, description, type_of_property, use_of_the_property, quadrature, location, price, sales_clerk_info, booked, type_of_market, type_of_payment, status) VALUES (:title, :description, :type_of_property, :use_of_the_property, :quadrature, :location, :price, :sales_clerk_info, :booked, :type_of_market, :type_of_payment, :status) ");
$this->db->bind(':title', $data['title']);
$this->db->bind(':description', $data['description']);
$this->db->bind(':type_of_property', $data['type_of_property']);
$this->db->bind(':use_of_the_property', $data['use_of_the_property']);
$this->db->bind(':quadrature', $data['quadrature']);
$this->db->bind(':location', $data['location']);
$this->db->bind(':price', $data['price']);
$this->db->bind(':sales_clerk_info', $data['sales_clerk_info']);
$this->db->bind(':booked', $data['booked']);
$this->db->bind(':type_of_market', $data['type_of_market']);
$this->db->bind(':type_of_payment', $data['type_of_payment']);
$this->db->bind(':status','1');
$this->db->execute();
$property_last_id = $this->db->lastId();
$this->db->query('INSERT INTO photos (name, extension) VALUES (:name, :extension)');
$this->db->bind(':name', $pht);
$this->db->bind(':extension', $this->photoExtension, PDO::PARAM_STR );
$this->db->execute();
$photo_last_id = $this->db->lastId();
$this->db->query('INSERT INTO property_photo (property_id, photo_id) VALUES (:property_id, :photo_id)');
$this->db->bind(':property_id', $property_last_id);
$this->db->bind(':photo_id', $photo_last_id);
$this->db->execute();
return true;
}
public function photoValidate($file)
{
if (!empty($file['name'])) {
$file_name = $file['name'];
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_error = $file['error'];
$random = sha1(microtime());
$tmp = explode('.', $file_name);
$new_photo_name = $random . '.' . $tmp[1];
$file_ext = strtolower(end($tmp));
//var_dump($tmp); null
//var_dump($file_ext); empty string
$photo_validate = '';
$extensions = ["jpeg", "jpg", "png"];
if (in_array($file_ext, $extensions) === false) {
return 'extension not allowed, please choose a JPEG or PNG file.';
} else {
if ($file_size > 2097152 || $file_error === 1) {
return 'File size must be less than 2 MB';
} else {
$value = true;
return $data = [$value, $file_tmp, $new_photo_name];
}
}
} else {
return false;
}
}
Ads Controller:
public function createAction()
{
$userinfo = $this->Auth->Auth(array('admin', 'moderator'));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$data = [
'title' => trim($_POST['title']),
'description' => trim($_POST['description']),
'type_of_property' => trim($_POST['type_of_property']),
'use_of_the_property' => trim($_POST['use_of_the_property']),
'quadrature' => trim($_POST['quadrature']),
'location' => trim($_POST['location']),
'price' => trim($_POST['price']),
'sales_clerk_info' => trim($_POST['sales_clerk_info']),
'booked' => trim($_POST['booked']),
'type_of_market' => trim($_POST['type_of_market']),
'type_of_payment' => trim($_POST['type_of_payment']),
'title_err' => '',
'description_err' => '',
'type_of_property_err' => '',
'use_of_the_property_err' => '',
'quadrature_err' => '',
'location_err' => '',
'price_err' => '',
'sales_clerk_info_err' => '',
'booked_err' => '',
'type_of_market_err' => '',
'type_of_payment_err' => ''
];
if (empty($data['title'])) {
$data['title_err'] = 'Please enter your title!!!';
}
if (empty($data['description'])) {
$data['description_err'] = 'Please enter your description!!!';
}
if (empty($data['type_of_property'])) {
$data['type_of_property_err'] = 'Please select your type!!!';
}
if (empty($data['use_of_the_property'])) {
$data['use_of_the_property_err'] = 'Please enter use of the property!!!';
}
if (empty($data['quadrature'])) {
$data['quadrature_err'] = 'Please enter your quadrature!!!';
}
if (empty($data['location'])) {
$data['location_err'] = 'Please enter your location!!!';
}
if (empty($data['price'])) {
$data['price_err'] = 'Please enter your price!!!';
}
if (empty($data['sales_clerk_info'])) {
$data['sales_clerk_info_err'] = 'Please enter your info!!!';
}
if (empty($data['booked'])) {
$data['booked_err'] = 'Please select!!!';
}
if (empty($data['type_of_market'])) {
$data['type_of_market_err'] = 'Please select your type of market!!!';
}
if (empty($data['type_of_payment'])) {
$data['type_of_payment_err'] = 'Please select your type of payment!!!';
}
$photo_validate = $this->AdModel->photoValidate($_FILES['photo']);
if (empty($data['title_err']) && empty($data['description_err']) && empty($data['type_of_property_err']) && empty($data['use_of_the_property_err']) && empty($data['quadrature_err']) && empty($data['location_err']) && empty($data['price_err']) && empty($data['sales_clerk_info_err']) && empty($data['booked_err']) && empty($data['type_of_market_err']) && empty($data['type_of_payment_err']) && $photo_validate[0] === true) {
move_uploaded_file($photo_validate[1],"public/photos/".$photo_validate[2]);
if ($this->AdModel->createAd($data, $photo_validate[2])) {
redirect('ads/index');
} else {
if ($photo_validate === false) {
$photo_validate='Please select image';
} else {
if ($photo_validate[0] === true) {
$photo_validate='';
}
}
$data=[
'photo_validate'=>$photo_validate
];
die('Something went wrong!');
}
} else {
$this->view->render('ads/create', $data, $userinfo);
}
} else {
$data = [
'photo_validate'=>'',
'title' => '',
'description' => '',
'type_of_property' => '',
'use_of_the_property' => '',
'quadrature' => '',
'location' => '',
'price' => '',
'sales_clerk_info' => '',
'booked' => '',
'type_of_market_id' => '',
'type_of_payment' => '',
'title_err' => '',
'description_err' => '',
'type_of_property_err' => '',
'use_of_the_property_err' => '',
'quadrature_err' => '',
'location_err' => '',
'price_err' => '',
'sales_clerk_info_err' => '',
'booked_err' => '',
'type_of_market_err' => '',
'type_of_payment_err' => ''
];
$this->view->render('ads/create', $data, $userinfo);
}
}
create.php
<form action="/ads/create" method="POST" enctype="multipart/form-data">
<div class="form-group row">
<div class="col-sm-12">
<h5>Upload property image</h6>
<input type="file" name="photo[]" multiple class="form-control form-control-lg"/>
</div>
/div>
<div class="form-group">
<button type="submit" name="submit" class="form-control btn btn-primary">Submit</button>
</div>
</form>
Any help would be greatly appreciated.
Take a look at array format of $_FILES for multiple files inserting. This answer and this php documentation page will be useful for you.
You expected string in photoValidate() $file['name'] but there was an array, so you got an error.
The best and the simplest way is to use something like symfony http-foundation component.
Controller:
public function createAction()
{
$request = Request::createFromGlobals();
//...
$photo_validate = $this->AdModel->photoValidate($request->files->get('photo'));
//...
}
Also, this kind of validation is pretty messy. You can also use symfony validator component.

PHP function errors not showing

I wasn't entirely sure how to search for this question, so if it has been asked before please send me in the right direction.
I have a validation function with an array. Inside my array I have set up errors to be displayed if one of the form fields doesn't validate. If the user fills a field out wrong, they should get an error of which field was wrong and the form should be still present. However, they get a blank page with only the generic error (the one I echo when I called the function) and not the field-specific error. Can someone please tell me where I went wrong?
$output_form = 1; //control if form displays - yes
$error_text = '';
//declare form elements (empty first load)
$fname = '';
$valid_fname = 0;
$fname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$fname_error_message = 'First name must be 2-15 alphabetic characters only.<br>';
$lname = '';
$valid_lname = 0;
$lname_regex = '/^([A-Z]|[a-z]){2,15}$/';
$lname_error_message = 'Last name must be 2-15 alphabetic characters only.<br>';
$phone = '';
$valid_phone = 0;
$phone_regex = '/^\(\d{3}\)\d{3}-\d{4}$/';
$phone_error_message = 'Phone number must be in (xxx)xxx-xxxx format.<br>';
$city = '';
$valid_city = 0;
$city_regex = '/^([A-Z]|[a-z]){2,15}$/';
$city_error_message = 'City must be 2-15 alphabetic characters only.<br>';
$state = '';
$valid_state = 0;
$state_regex = '/^([A-Z]|[a-z]){2}$/';
$state_error_message = 'State must be 2 alphabetic characters only.<br>';
//data posted
if (isset($_POST['submit'])) {
if ($debug) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}//end debug
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$phone = trim($_POST['phone']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$phone_replace = preg_replace('/[\(\)\-\s]/', '', $phone);
function validate_form($fields, &$errors = []) {
$errors = [];
foreach ($fields as $name => $field) {
if (!preg_match ($field['regex'], $field['value'])) {
$errors[$name] = $field['error'];
$output_form = 1;
}
}
return empty($errors); //returns true/false
}
$fields = [
'fname' => ['regex' => $fname_regex, 'value' => $fname, 'error' => $fname_error_message],
'lname' => ['regex' => $lname_regex, 'value' => $lname, 'error' => $lname_error_message],
'phone' => ['regex' => $phone_regex, 'value' => $phone, 'error' => $fname_error_message],
'city' => ['regex' => $city_regex, 'value' => $city, 'error' => $city_error_message],
'state' => ['regex' => $state_regex, 'value' => $state, 'error' => $state_error_message],
];
$errors = [];
if (!validate_form($fields, $errors)) {
echo "<p>One of your fields is invalid. Please check and re-submit.</p>";
$output_form = 1;
return (false);
}
else {
$output_form = 0;
}
foreach($errors as $error) echo "<p>$error</p>";
Actually outputting stuff usually helps ;)

Validation for php registration before sending out notification mail

I'm building a PHP registration system. It will send a notification email to me if there's a new user register to my website. But the problem is, if the user doesn't enter anything, it will send a email to me also. How do I overcome this issue?
This is the validation part.
/*Validation Begins*/
if(empty($_POST) === false) {
$required_fields = array('school_name', 'mailing_address', 'postcode', 'courier_address', 'courier_postcode', 'courier_postcode', 'phonenumber', 'faxnumber', 'email', 'website', 'principal_fullname', 'principal_phonenumber', 'principal_email');
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required_fields) === true){
mysql_close();
?>
<script type="text/javascript">
alert("Fields marked with an asterisk are required");
history.back();
</script>
<?php
}
}
Below is the insertion function and the mail function.
function register_school($register_data){
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
mysql_query("INSERT INTO `schools_info` ($fields) VALUES ($data)");
?>
<script type='text/javascript'>
alert("Registration Successful!"); window.location.href = '/registration-success/';
</script>
<?php
$schoolname = $_POST['school_name'];
$mailing_address = $_POST['mailing_address'];
$postcode = $_POST['postcode'];
$courier_address = $_POST['courier_address'];
$phonenumber = $_POST['courier_postcode'];
$faxnumber = $_POST['faxnumber'];
$email = $_POST['email'];
$website = $_POST['website'];
$principal_fullname = $_POST['principal_fullname'];
$principal_phonenumber = $_POST['principal_phonenumber'];
$principal_email = $_POST['principal_email'];
$to = "example#hotmail.com";
$subject = "New Registered School";
$message = "School Name: $schoolname\r\nSchool Address: $mailing_address\r\nPostcode: $postcode\r\nCourier Address: $courier_address\r\nCourier Postcode: $courier_postcode\r\nPhone Number: $phonenumber\r\nFax Number: $faxnumber\r\nEmail: $email\r\nWebsite: $website\r\nPrincipal Name: $principal_fullname\r\nPrincipal Phone Number: $principal_phonenumber\r\nPrincipal Email: $principal_email";
$from = "testing.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
Register School
if(empty($_POST) === false){
$register_data = array(
'school_name' => $_POST['school_name'],
'mailing_address' => $_POST['mailing_address'],
'postcode' => $_POST['postcode'],
'courier_address' => $_POST['courier_address'],
'courier_postcode' => $_POST['courier_postcode'],
'phonenumber' => $_POST['phonenumber'],
'faxnumber' => $_POST['faxnumber'],
'email' => $_POST['email'],
'website' => $_POST['website'],
'principal_fullname' => $_POST['principal_fullname'],
'principal_phonenumber' => $_POST['principal_phonenumber'],
'principal_email' => $_POST['principal_email'],
'CScoor' => $_POST['CScoor'],
'CS_email' => $_POST['CS_email'],
'CS_phone' => $_POST['CS_phone'],
'Engcoor' => $_POST['Engcoor'],
'Eng_email' => $_POST['Eng_email'],
'Eng_phone' => $_POST['Eng_phone'],
'Mcoor' => $_POST['Mcoor'],
'M_email' => $_POST['M_email'],
'M_phone' => $_POST['M_phone'],
'Sccoor' => $_POST['Sccoor'],
'Sc_email' => $_POST['Sc_email'],
'Sc_phone' => $_POST['Sc_phone']
);
register_school($register_data);
mysql_close();
}
Before the part:
$to = "example#hotmail.com";
$subject = "New Registered School";
$message = "School Name: $schoolname\r\nSchool Address: $mailing_address\r\nPostcode: $postcode\r\nCourier Address: $courier_address\r\nCourier Postcode: $courier_postcode\r\nPhone Number: $phonenumber\r\nFax Number: $faxnumber\r\nEmail: $email\r\nWebsite: $website\r\nPrincipal Name: $principal_fullname\r\nPrincipal Phone Number: $principal_phonenumber\r\nPrincipal Email: $principal_email";
$from = "testing.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
begins. Check every variable if it is empty or not:
// Edit: Sorry didn't see that you have an array about the values. Then you can make it something like this:
$success = true;
foreach($register_data as $data) {
if (empty($_POST[$data])) {
$success = false;
break;
}
}
if ($success == true) {
//then mail
}
if(empty($_POST) === false) {
$required_fields = array('school_name', 'mailing_address', 'postcode', 'courier_address', 'courier_postcode', 'courier_postcode', 'phonenumber', 'faxnumber', 'email', 'website', 'principal_fullname', 'principal_phonenumber', 'principal_email');
$flag = TRUE;
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required_fields) === true){
mysql_close();
$flag = FALSE;
?>
<script type="text/javascript">
alert("Fields marked with an asterisk are required");
history.back();
</script>
<?php
} // end second if
} //end foreach
if ($flag == TRUE){
$register_data = array(.....); //all $_POST value assign here
register_school($register_data);}
} //end first if

How to display error message properly from check_required_fields function?

Hi i'd like some help please. i'm having a function for validating required fields of forms, in which i pass the req. fields in an array, so if is empty e.g first_name returns an error message: "The first_name is empty." . The problem is that i would like to make the name of the field in the message to look more "friendly" to the user, no camelCases or '_'. How can i achieve this?
p.s. here's my code:
$required_fields = array('first_name', 'last_name', 'email', 'profileInfo', 'message');
$errors = array_merge($errors, check_required_fields($required_fields));
Right now the output error message looks like :
"The first_name is required" or "The profileInfo is required".
The function is this:
function check_required_fields($required_fields) {
$field_errors = array();
foreach($_POST as $field=>$value){
if(empty($value) && in_array($field, $required_fields) === true){
$field_errors[] = "the " . $field . " is required.";
//break 1;
}
}
return $field_errors;
}
You could give each required field a label...
$required_fields = array(
'first_name' => 'First Name',
'last_name' => 'Last name',
'email' => 'Email Address',
'profileInfo' => 'Profile information',
'message' => 'Message'
);
$errors = array_merge($errors, check_required_fields($required_fields));
You will need to alter check_required_fields method to handle the $required_fields array correctly, like this:
function check_required_fields($required_fields)
{
$field_errors = array();
foreach ($_POST as $field => $value)
{
if (empty($value) && array_key_exists($field, $required_fields) === true)
{
$field_errors[] = "the " . $required_fields[$field] . " is required.";
//break 1;
}
}
return $field_errors;
}
Edit: I have just noticed that your loop on $_POST will only work as expected if the fields are set. Try the following:
function check_required_fields($required_fields)
{
$field_errors = array();
foreach ($required_fields as $field => $label)
{
$value = $_POST[$field];
if (empty($value))
{
$field_errors[] = "the " . $label . " is required.";
//break 1;
}
}
return $field_errors;
}

Categories