Not able select values which contains space between value name - php

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!';
}
}

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";
}
}

Form doesn't working properly

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.

Checking if the input name and telephone number valid with php

I have tried this code to add validation when the input is name and number. But, there is something wrong with this code. The validation for nama and telepon are always wrong. I use the form and validation in one page.Can you help me solve this problem
<?php
error_reporting(E_ALL);
class ValidateInfo
{
public $errors;
public $message;
public $data;
public $wrong;
public $wrongmessage;
public function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
{
$trimmed = trim($payload[$type]);
if(!empty($validate)) {
// Strip out all but numbers
if(in_array('digits',$validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {
// not an integer!
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Telephon number must be in number';
} else {
$this->wrong[$type] = 0;
}
}
// Strip out letters
elseif(in_array('letters',$validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === true) {
// not an integer!
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Name must be in alphabet';
} else {
$this->wrong[$type] = 0;
}
}
// Re-assign data type to consolidate
$this->data[$type] = (!isset($this->data[$type]))? $trimmed:$this->data[$type];
// Check if data is an email
if(in_array('email',$validate)) {
if(filter_var($this->data[$type], FILTER_VALIDATE_EMAIL) === false){
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Tulis email seperti: yourname#email.com';
} else {
$this->wrong[$type] = 0;
}
}
// Strip out html tags
if(in_array('strip',$validate)) {
$this->data[$type] = strip_tags($this->data[$type]);
}
}
if(!isset($this->data[$type]))
$this->data[$type] = $trimmed;
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
}
}
// Creat instance of info processor
$info = new ValidateInfo();
// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {
// Checks empty fields
$info->Check($_POST,'nama','Write your name',array('letters'));
$info->Check($_POST,'telepon','Write the phone number',array('digits'));
$info->Check($_POST,'email','Write the email',array('email'));
$info->Check($_POST,'judul','Write the title');
$info->Check($_POST,'konten','Write the content');
if(array_sum($info->errors) == 0 && array_sum($info->wrong) == 0) {
// path and name of the file
$filetxt = 'dataInJson.json';
// Assign stored data
$data = $info->data;
// path and name of the file
$filetxt = 'dataInJson.json';
// to store all form data
$arr_data = array();
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
// appends the array with new form data
$arr_data[] = $data;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "dataInJson.json"
// outputs error message if data cannot be saved
if(file_put_contents('dataInJson.json', $jsondata)) {
$info->errors['success'] = true; ?>
<script type="text/javascript">alert("Data has been submitted");</script>
<?php }
else {
$info->message['general']['put_file'] = 'Tidak dapat menyimpan data di "dataInJson.json"';
}
}
}
else
$info->message['general']['submit'] = 'Form fields not submited'; ?>
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="center">
<h1>Data Buku</h1>
<?php if(isset($info->errors['success'])) { ?>
<h2>Thank you!</h2>
<?php } else { ?>
<p><span class="error">* required field.</span></p>
<?php } ?>
<hr>
<form action="" method="post">
<?php if(isset($info->message['general'])) {
foreach($info->message['general'] as $_error) { ?>
<span class="error">* <?php echo $_error; ?></span><br>
<?php
}
} ?>
<h2>Informasi Pengarang</h2>
<div class="roadie">
<label for="nama">Nama:</label>
<input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value=" <?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
<?php
if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?>
<span class="error">* <?php echo $info->message['nama']; ?></span><?php
}
if(isset($info->wrong['nama']) && $info->wrong['nama'] == 1) { ?>
<span class="error">* <?php echo $info->wrongmessage['nama']; ?></span><br><?php
}?>
</div>
<div class="roadie">
<label for="telepon">Nomor Telepon:</label>
<input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
<?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?><span class="error">* <?php echo $info->message['telepon']; ?></span><?php }
if(isset($info->wrong['telepon']) && $info->wrong['telepon'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['telepon']; ?></span><br><?php } ?>
</div>
<div class="roadie">
<label for="email">e-Mail:</label>
<input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
<?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?><span class="error">* <?php echo $info->message['email']; ?></span><br><?php }
if(isset($info->wrong['email']) && $info->wrong['email'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['email']; ?></span><br><?php }
?>
</div>
<div class="roadie">
<h2>Tulisan</h2>
<label for="judul">Judul:</label>
<input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
<?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?><span class="error">* <?php echo $info->message['judul']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="konten">Konten:</label>
<textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) { echo strip_tags($info->data['konten']); } ?></textarea>
<?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?><span class="error">* <?php echo $info->message['konten']; ?></span><br><?php } ?>
</div>
<input type="submit" id="submit" name = submit value="Create" />
<input type="reset" id="reset" value="Reset" />
</form>
I debugged your code, and the problem is:
When your program checks your nama field, it has option array('letters') for $validate.
elseif (in_array('letters', $validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {
So when you want to check letters, why do you use FILTER_VALIDATE_INT ?
The other problem is here:
if(!isset($this->data[$type])) {
$this->data[$type] = $trimmed;
}
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
This block is at the end of your Check. So, when first run, you try to check an empty thing, and then when method finishes, the nama will be added to the $this->data. This is why your second Check call does not found the telpone. So move this block to the top of your method, and validate, is this exists. Validate formats only after this check.

PDO Cannot use object of type ads as array (form error)

I'm newbie with PDO and I'm trying to make an ads site. On a page with insert data from a form I receive this issue: "Fatal Error. Cannot use object of type ads as array". Before ask here I searched about this issue and I didn't find anything (maybe because I'm newbie???). Please don't vote me negative.
This is the PHP file with functions:
class ads{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function insert_ads($categorie, $subcategorie, $userid, $site, $nume, $oras, $judet, $telefon, $email, $titlu_anunt, $text_anunt, $pret_anunt ){
$time = time();
$categorie = 'masini';
$subcategorie = 'dacia';
$email_code = $email_code = uniqid('code_',true);
$query = $this->db->prepare("INSERT INTO `ads` (`categorie`, `subcategorie`, `userid`, `site`, `nume`, `oras`, `judet`, `telefon`, `email`, `email_code`, `titlu_anunt`, `text_anunt`, `pret_anunt`, `data_adaugare`, `vizualizari`, `confirmed`, `platit`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
$query->bindValue(1, $categorie);
$query->bindValue(2, $subcategorie);
$query->bindValue(3, 0);
$query->bindValue(4, $site);
$query->bindValue(5, $nume);
$query->bindValue(6, $oras);
$query->bindValue(7, $judet);
$query->bindValue(8, $telefon);
$query->bindValue(9, $email);
$query->bindValue(10, $email_code);
$query->bindValue(11, $titlu_anunt);
$query->bindValue(12, $text_anunt);
$query->bindValue(13, $pret_anunt);
$query->bindValue(14, $time);
$query->bindValue(15, 1);
$query->bindValue(16, 0);
$query->bindValue(17, 0);
try{
$id_last = ("SELECT LAST_INSERT_ID()");
$result = $this->db->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
#code to deal with the picture uploads
#target folder
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
$images ="INSERT INTO ads_images(ads_id,image_name)
VALUES($last_id,:image_name)";
$images_insert = $this->db->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
));
}}
$query->execute();
mail($email, 'Please activate your account', "Hello " . $nume. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.djmixtv.com/test/activate_ads.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
This is the PHP code:
if (isset($_GET['success']) && empty($_GET['success'])) {
echo '<h3>Your details have been updated!</h3>';
} else{
if(empty($_POST) === false) {
if (isset($_POST['nume']) && !empty ($_POST['nume'])){ // We only allow names with alphabets
if (ctype_alpha($_POST['nume']) === false) {
$errors[] = 'Please enter your Name only with letters!';
}
}
if (isset($_POST['oras']) && !empty ($_POST['oras'])){
if (ctype_alpha($_POST['oras']) === false) {
$errors[] = 'Please enter your city with only letters!';
}
}
if (isset($_POST['judet']) && !empty ($_POST['judet'])){
if (ctype_alpha($_POST['judet']) === false) {
$errors[] = 'Please enter your contry with only letters!';
}
}
if (isset($_POST['telefon']) && !empty ($_POST['telefon'])){
if (ctype_digit($_POST['telefon']) === false) {
$errors[] = 'Please enter your phone with only numbers!';
}
}
if (isset($_POST['telefon']) && !empty ($_POST['telefon'])){
if (ctype_digit($_POST['telefon']) === false) {
$errors[] = 'Please enter your phone with only numbers!';
}
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if (isset($_POST['titlu_anunt']) && !empty ($_POST['titlu_anunt'])){
if (ctype_alnum($_POST['titlu_anunt']) === false) {
$errors[] = 'Please enter your phone with only numbers!';
}
}
$site = htmlentities(trim($_POST['site']));
$nume = htmlentities(trim($_POST['nume']));
$oras = htmlentities(trim($_POST['oras']));
$judet = htmlentities(trim($_POST['judet']));
$telefon = htmlentities(trim($_POST['telefon']));
$email = htmlentities(trim($_POST['email']));
$titlu_anunt = htmlentities(trim($_POST['titlu_anunt']));
$text_anunt = htmlentities(trim($_POST['text_anunt']));
$pret_anunt = htmlentities(trim($_POST['pret_anunt']));
$ads->insert_ads($categorie, $subcategorie, $site, $nume, $oras, $judet, $telefon, $email, $titlu_anunt, $text_anunt, $pret_anunt);
header('Location: settings.php?success');
exit();
}
This is the form:
<form action="" method="post" enctype="multipart/form-data">
<div id="personal_info">
<h3 >Change Profile Information </h3>
<ul>
<li>
<h4>Site:</h4>
<input type="text" name="site" value="<?php if (isset($_POST['site']) ){echo htmlentities(strip_tags($_POST['site']));} else { echo $ads['site']; }?>">
</li>
<li>
<h4>Nume: </h4>
<input type="text" name="nume" value="<?php if (isset($_POST['nume']) ){echo htmlentities(strip_tags($_POST['nume']));} else { echo $ads['nume']; }?>">
</li>
<li>
<h4>Nume: </h4>
<input type="text" name="nume" value="<?php if (isset($_POST['nume']) ){echo htmlentities(strip_tags($_POST['nume']));} else { echo $ads['nume']; }?>">
</li>
<li>
<h4>Oras: </h4>
<input type="text" name="oras" value="<?php if (isset($_POST['oras']) ){echo htmlentities(strip_tags($_POST['oras']));} else { echo $ads['oras']; }?>">
</li>
<li>
<h4>Judet: </h4>
<input type="text" name="judet" value="<?php if (isset($_POST['judet']) ){echo htmlentities(strip_tags($_POST['judet']));} else { echo $ads['judet']; }?>">
</li>
<li>
<h4>Telefon: </h4>
<input type="text" name="telefon" value="<?php if (isset($_POST['telefon']) ){echo htmlentities(strip_tags($_POST['telefon']));} else { echo $ads['telefon']; }?>">
</li>
<li>
<h4>Email: </h4>
<input type="text" name="email" value="<?php if (isset($_POST['email']) ){echo htmlentities(strip_tags($_POST['email']));} else { echo $ads['email']; }?>">
</li>
<li>
<h4>Titlu Anunt: </h4>
<input type="text" name="titlu_anunt" value="<?php if (isset($_POST['titlu_anunt']) ){echo htmlentities(strip_tags($_POST['titlu_anunt']));} else { echo $ads['titlu_anunt']; }?>">
</li>
<li>
<h4>Text anunt:</h4>
<textarea name="text_anunt"><?php if (isset($_POST['text_anunt']) ){echo htmlentities(strip_tags($_POST['text_anunt']));} else { echo $user['text_anunt']; }?></textarea>
</li>
<li>
<h4>Pret: </h4>
<input type="text" name="pret_anunt" value="<?php if (isset($_POST['pret_anunt']) ){echo htmlentities(strip_tags($_POST['pret_anunt']));} else { echo $ads['pret_anunt']; }?>">
</li>
<li>
<h4>Image</h4>
<input type="file" name="image_name[]" multiple /><br />
</ul>
</div>
<div class="clear"></div>
<hr />
<span>Update Changes:</span>
<input type="submit" value="Update">
</form>
This is not related to PDO.
You cannot use an ads instance as an array. For example
$ads = new ads();
$ads['something'] = 1; //Fatal Error comes here
It is in your form everywhere.
<input type="text" name="site" value="<?php if (isset($_POST['site']) ){
echo htmlentities(strip_tags($_POST['site']));} else { echo $ads['site']; }
?>">
In PHP if you want to use a property, you have to define it.
class ads {
public myProperty;
public function setAValueForMyProperty(){
$this->myProperty = 1;
}
}
$ads = new ads();
$ads->setAValueForMyProperty();
echo $ads->myProperty;
If you want to use a class instance as an array, you have two options. You can export its content into an array:
class ads {
protected myProperty = 1;
public function toArray(){
return array(
'myProperty' => $this->myProperty;
);
}
}
$ads = new ads();
$arr = $ads->toArray();
echo $arr['myProperty'];
Or you can implement the ArrayAccess interface:
class ads implements ArrayAccess {
protected myProperty = 1;
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
public function offsetExists($offset) {
return isset($this->$offset);
}
public function offsetUnset($offset) {
unset($this->$offset);
}
public function offsetGet($offset) {
return $this->$offset;
}
}
$ads = new ads();
echo $ads['myProperty'];
I think you should read more about how classes work in php.
http://www.php.net/manual/en/language.oop5.php

do i need to add any code to PHP after using SSL

i'm using a simple contact form on my website using PHP, and i'm about to install SSL on my website, codewise do i need to make any changes to the PHP code, i'm totaly new to SSL and this is my first SSL installation .
<?php
$errors = array();
$missing = array();
if (isset($_POST['send'])) {
$to = 'john#example.com';
$subject = 'Feedback from contact form';
$expected = array('name', 'email', 'comments');
$required = array('name', 'email', 'comments');
$headers = "From: webmaster#example.com\r\n";
$headers .= "Content-type: text/plain; charset=utf-8";
require './includes/mail_process.php';
if ($mailSent) {
header('Location: thanks.php');
exit;
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Contact Us</title>
<link href="./styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Contact Us</h1>
<?php if ($_POST && $suspect) { ?>
<p class="warning">Sorry your mail could not be be sent.</p>
<?php } elseif ($errors || $missing) { ?>
<p class="warning">Please fix the item(s) indicated.</p>
<?php }?>
<form name="contact" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
<label for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span>
<?php } ?>
</label>
<input type="text" name="name" id="name"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email address</span>
<?php } elseif (isset($errors['email'])) { ?>
<span class="warning">Invalid email address</span>
<?php } ?>
</label>
<input type="text" name="email" id="email"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span class="warning">You forgot to add your comments</span>
<?php } ?>
</label>
<textarea name="comments" id="comments"><?php
if ($errors || $missing) {
echo htmlentities($comments, ENT_COMPAT, 'utf-8');
}
?></textarea>
</p>
<p>
<input type="submit" name="send" id="send" value="Send Comments">
</p>
</form>
<pre>
</body>
</html>
the mail_process.php goes like this
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
$$key = '';
} elseif(in_array($key, $expected)) {
$$key = $temp;
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-to: $validemail";
} else {
$errors['email'] = true;
}
}
if (!$suspect && !$missing && !$errors) {
$message = '';
foreach ($expected as $item) {
if (isset($$item) && !empty($$item)) {
$val = $$item;
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item) . ": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers, $authenticate);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
Since you don't have any absolute URL references you won't have a problem. I'd recommend you put this in your header (or at the top of all your PHP files) to force them to use https, that way if you did need absolute URLs in your website, you can have them all HTTPS as everyone would be forced there anyway.
if($_SERVER['HTTPS'] != 'on' || !stristr($_SERVER['HTTP_HOST'], 'www.')) {
$redirect= "https://www.".str_replace('www.','',$_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI'];
header("Location:$redirect");
}
You would have to change absolute URL's to "https://....". If you are not using absolute URL's there is nothing to change if your form and processing script are both on https.

Categories