I am in need of a little bit of help here, it is the only part missing on my website.
I have a newsletter script and on the first page I am using a multilanguage function that I got from codecanyon (PHPMLC) that works perfectly.
This is the index.php with the form ( I have stripped the unnecessary html).
<?php
require_once( "../PHPMLC/class/PHPMLC.php" );
$ml = new PHPMLC();
$ml_languages = $ml->getLanguages();
$ml_selected_language_code = $ml->getCurrentLanguageCode();
$ml_strings = $ml->getTranslatedStringsForCurrentLanguage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $ml_strings['prereg_m_title']; ?></title>
<link href="/css/style.css" rel="stylesheet">
</head>
<body class="Site">
<form class="form-horizontal" id="newsletter" action="send.php" method="post" accept-charset="utf-8"
enctype="multipart/form-data">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-6">
<input type="email" name="signup-email" class="form-control" id="signup-email" value=""
pattern="[A-Z-a-z-0-9-_#.]+" autocomplete="off" required />
<input type="hidden" name="signup-gender" id="signup-gender" value="female" />
</div>
</div>
<div class="form-group">
<label for="inputPassword3"
class="col-sm-2 control-label"><?php echo $ml_strings['prereg_country_label']; ?></label>
<div class="col-sm-6">
<select class="form-control" name="signup-country" required />
<option value="" disabled selected><?php echo $ml_strings['prereg_please_select']; ?></option>
<option value="Albania">Albania</option>
<option value="Andorra">Andorra</option>
<option value="Austria">Austria</option>
<option value="Belarus">Belarus</option>
<option value="Belgium">Belgium</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-info"><?php echo $ml_strings['prereg_submit_button']; ?></button>
</div>
</div>
</form>
</body>
</html>
The form send the inputs to a file "send.php" which has the following code :
<?php
require 'inc/Database.class.php';
class Newsletter {
private static $email;
private static $gender;
private static $country;
private static $ip;
private static $datetime = null;
private static $valid = true;
public function __construct() {
die( 'Init function is not allowed' );
}
public static function register( $email ) {
if ( ! empty( $_POST ) ) {
self::$email = $_POST['signup-email'];
self::$gender = $_POST['signup-gender'];
self::$country = $_POST['signup-country'];
//Test if it is a shared client
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
self::$ip = $_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
self::$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
self::$ip = $_SERVER['REMOTE_ADDR'];
}
self::$datetime = date( 'Y-m-d H:i:s' );
if ( empty( self::$email ) ) {
$status = "error";
$message = "The email address field must not be blank";
self::$valid = false;
} else if ( ! filter_var( self::$email, FILTER_VALIDATE_EMAIL ) ) {
$status = "error";
$message = "You must fill the field with a valid email address";
self::$valid = false;
}
if ( self::$valid ) {
$pdo = Database::connect();
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$existingSignup = $pdo->prepare( "SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'" );
$existingSignup->execute();
$data_exists = ( $existingSignup->fetchColumn() > 0 ) ? true : false;
if ( ! $data_exists ) {
$sql = "INSERT INTO signups (signup_email_address, signup_category, signup_country, signup_ip, signup_date) VALUES (:email, :gender, :country, :ip, :datetime)";
$q = $pdo->prepare( $sql );
$q->execute(
array( ':email' => self::$email,
':gender' => self::$gender,
':country' => self::$country,
':ip' => self::$ip,
':datetime' => self::$datetime
) );
if ( $q ) {
$status = "success";
$message = "Your registration was successful";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already registered";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode( $data );
Database::disconnect();
}
}
}
if ( ! empty( $_POST ) ) {
$email = $_POST['signup-email'];
$gender = $_POST['signup-gender'];
$country = $_POST['signup-country'];
Newsletter::register( $email );
}
?>
My problem is, I cannot translate the error/alert messages in send.php. I mean I cannot use the key $ml_strings['reg_successful']; instead of "Your registration was successful". It's driving me crazy because I am an amateur.
Many thanks in advance for your help.
The execution of send.php is completely separated from the execution of index.php, so you need to initialize the $ml_strings variable in both files. In other words, add the following line to the Newsletter class in send.php:
$ml_strings = $ml->getTranslatedStringsForCurrentLanguage();
Related
Please kindly see my PHP code as below:
It is 2 files. My questions are how could I store the user input information and store it to admin pages. how could I make the confirmation message to users if they input correctly? how could I create the admin page with fetching data and displaying it? how could I make the password gating for the admin page? Please kindly help with my assignment. Thank you
File name: content.php
<h2>PHP Assignment 1 </h2>
<p><span class="error">* required field </span></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
First Name:
<input type="text" name="FirstName" value="<?php echo $FirstName;?>"/>
<span class="error">* <?php echo $FirstNameErr;?></span>
<br><br>
Last Name:
<input type="text"name="LastName" value="<?php echo $LastName;?>"/>
<span class="error">* <?php echo $LastNameErr;?></span>
<br><br>
Email Address:
<input type="text" name="EmailAddress" value="<?php echo $EmailAddress;?>"/>
<span class="error">* <?php echo $EmailAddressErr;?></span>
<br><br>
<input name="submit" type="submit" value="Submit"/><br><br>
</form>
File name: process.php
<!DOCTYPE HTML>
<html>
<head>
<style>.error {color: #FF0000;} </style>
</head>
<body>
<?php
$FirstNameErr = $LastNameErr = $EmailAdressErr ="";
$FirstName = $LastName = $EmailAddress = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["FirstName"])) {
$FirstNameErr = "First Name is required";
} else {
$FirstName = test_input($_POST["FirstName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $FirstName)){
$FirstNameErr = "Only letters and white space allowed";
}
else echo $FirstName;
}
if (empty($_POST["LastName"])) {
$LastNameErr = "Last Name is required";
} else {
$LastName = test_input($_POST["LastName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $LastName)){
$LastNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["EmailAddress"])){
$EmailAddressErr = "Email Address is required";
} else {
$EmailAddress = test_input($_POST["EmailAddress"]);
if (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)) {
$EmailAddressErr = "Invalid email format";
}
}
}
function test_input($data){
$data= trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
enter code here
<!DOCTYPE HTML>
<html>
<head>
<style>.error {color: #FF0000;} </style>
</head>
<body>
<?php
$FirstNameErr = $LastNameErr = $EmailAdressErr ="";
$FirstName = $LastName = $EmailAddress = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["FirstName"])) {
$FirstNameErr = "First Name is required";
} else {
$FirstName = test_input($_POST["FirstName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $FirstName)){
$FirstNameErr = "Only letters and white space allowed";
}
else echo $FirstName;
}
if (empty($_POST["LastName"])) {
$LastNameErr = "Last Name is required";
} else {
$LastName = test_input($_POST["LastName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $LastName)){
$LastNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["EmailAddress"])){
$EmailAddressErr = "Email Address is required";
} else {
$EmailAddress = test_input($_POST["EmailAddress"]);
if (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)) {
$EmailAddressErr = "Invalid email format";
}
}
}
function test_input($data){
$data= trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is by no means the right way to do it in the real world, but it does give you a very good starting point include the fundementals which you can work from. It mostly covers all requirements, however, there are some key areas that need improving: admin authentication and error handling for database errors etc.
Here's a video of it the below in action: https://www.youtube.com/watch?v=EmaEYzIkpnY
There are 4 files that powers this example:
database.php which includes the database connection helper. Databse connection details will need updating to match your enviroment.
forms.php is a file containing variables and helper functions for form validation.
index.php which is your "frontend" form for users details.
admin.php which is where you'd login to view all recorded submissions.
In summary:
Errors are simply stored in an array and then presented with the helper functions has_error() and get_error().
Data storage is handled with PDO research this along with prepared statements.
Gated admin area is hardcoded variable value checking and should not be used. You should instead have a users table which stores the password as a hashed value, your authentication process would then check against these values and set session values.
Bootstrap is used for the basic UI.
database.php
<?php
/**
* Open a new database connection.
*
* #return PDO
*/
function db_connect() {
$host = 'localhost';
$user = 'root';
$pass = 'mysql';
$name = 'my_table';
try {
return new PDO("mysql:host=$host;dbname=$name;charset=UTF8", $user, $pass);
} catch (PDOException $e) {
die('Database connectuon failed: ' . $e->getMessage());
}
}
forms.php
<?php
/**
* #var array $payload
*/
$payload = [];
/**
* #var string[] $error_bag
*/
$error_bag = [];
/**
* #var bool $success
*/
$success = false;
/**
* Set the global payload array.
*
* #param array $data
*/
function set_payload(array $data) {
global $payload;
$payload = $data;
}
/**
* Add an error to the global error bag.
*
* #param string $name
* #param string $error
*/
function add_error(string $name, string $error) {
global $error_bag;
$error_bag[$name] = $error;
}
/**
* Check if input has errors.
*
* #param string $name
* #return bool
*/
function has_error(string $name) {
global $error_bag;
return array_key_exists($name, $error_bag);
}
/**
* Get the error for input.
*
* #param string $name
* #return null|string
*/
function get_error(string $name) {
global $error_bag;
return has_error($name) ? $error_bag[$name] : null;
}
/**
* Get input from request.
*
* #param string $name
* #param mixed $default
* #return mixed|null
*/
function input(string $name, $default = null) {
global $payload;
return array_key_exists($name, $payload) ? $_POST[$name] : $default;
}
index.php
<?php
require_once 'database.php';
require_once 'forms.php';
if (!empty($_POST)) {
set_payload($_POST);
$first_name = input('first_name');
$last_name = input('last_name');
$email_address = input('email_address');
if (empty(trim($first_name))) {
add_error('first_name', 'Please provide a first name.');
}
if (empty(trim($last_name))) {
add_error('last_name', 'Please provide a last name.');
}
if (empty(trim($email_address)) || !filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
add_error('email_address', 'Please provide a valid email address.');
}
// If empty, assume all fields are valid.
if (empty($error_bag)) {
// Empty payload on success, prevents form values from being filled.
set_payload([]);
$database = db_connect();
$database->exec("CREATE TABLE IF NOT EXISTS submissions (
`id` INT NOT NULL AUTO_INCREMENT,
`first_name` longtext NOT NULL,
`last_name` longtext NOT NULL,
`email_address` longtext NOT NULL,
primary key (`id`)
) CHARACTER SET UTF8 COLLATE utf8_general_ci;");
$query = $database->prepare('INSERT INTO `submissions` (`first_name`, `last_name`, `email_address`) VALUES (:first_name, :last_name, :email_address)');
$query->execute([
':first_name' => $first_name,
':last_name' => $last_name,
':email_address' => $email_address
]);
if ($database->lastInsertId()) {
// Set success flag.
$success = true;
} else {
add_error('database', 'Failed to process submission, please try again later.');
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Submission</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container my-5">
<h1>PHP Assignment 1 </h1>
<?php if ($success): ?>
<div class="alert alert-success">
<strong>Success!</strong> Your submission has been recieved.
</div>
<?php endif ?>
<?php if (has_error('database')): ?>
<div class="alert alert-danger">
<strong>Uh oh!</strong> <?= htmlspecialchars(get_error('database')); ?>
</div>
<?php endif ?>
<form action="index.php" method="post">
<div class="mb-3">
<label for="first-name">First name:</label>
<input
type="text"
id="first-name"
name="first_name"
class="form-control <?= has_error('first_name') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('first_name')); ?>">
<?php if (has_error('first_name')): ?>
<div class="invalid-feedback"><?= get_error('first_name'); ?></div>
<?php endif ?>
</div>
<div class="mb-3">
<label for="last-name">Last name:</label>
<input
type="text"
id="last-name"
name="last_name"
class="form-control <?= has_error('last_name') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('last_name')); ?>">
<?php if (has_error('last_name')): ?>
<div class="invalid-feedback"><?= get_error('last_name'); ?></div>
<?php endif ?>
</div>
<div class="mb-3">
<label for="email-address">Email address:</label>
<input
type="email"
id="email-address"
name="email_address"
class="form-control <?= has_error('email_address') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('email_address')); ?>">
<?php if (has_error('email_address')): ?>
<div class="invalid-feedback"><?= get_error('email_address'); ?></div>
<?php endif ?>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
admin.php
<?php
require_once 'database.php';
require_once 'forms.php';
/**
* #var bool $authed
*/
$authed = false;
if (!empty($_POST)) {
set_payload($_POST);
$username = input('username');
$password = input('password');
if (empty(trim($username))) {
add_error('username', 'Please enter your username.');
}
if (empty(trim($password))) {
add_error('password', 'Please enter your password.');
}
if (empty($error_bag) && ($username !== 'test' || $password !== 'password1')) {
add_error('username', 'The details provided were incorrect.');
}
// If empty, assume all fields are valid.
if (empty($error_bag)) {
// Empty payload on success, prevents form values from being filled.
set_payload([]);
// Set success flag.
$authed = true;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin area</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body class="bg-light">
<div class="container my-5">
<?php if ($authed): ?>
<h1>Submission results</h1>
<?php
$database = db_connect();
$results = $database->query('SELECT * FROM `submissions`')->fetchAll();
?>
<table class="table table-striped table-bordered bg-white">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email address</th>
</tr>
</thead>
<tbody>
<?php if ($results): ?>
<?php foreach($results as $result): ?>
<tr>
<td><?= htmlspecialchars($result['id']); ?></td>
<td><?= htmlspecialchars($result['first_name']); ?></td>
<td><?= htmlspecialchars($result['last_name']); ?></td>
<td><?= htmlspecialchars($result['email_address']); ?></td>
</tr>
<?php endforeach ?>
<?php else:?>
<tr>
<td colspan="4">No results</td>
</tr>
<?php endif ?>
</tbody>
</table>
<?php else: ?>
<div class="row justify-content-center">
<div class="col-lg-4">
<div class="card">
<div class="card-body">
<form action="admin.php" method="post">
<div class="mb-3">
<label for="first-name">Username:</label>
<input
type="text"
id="username"
name="username"
class="form-control <?= has_error('username') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('username')); ?>">
<?php if (has_error('username')): ?>
<div class="invalid-feedback"><?= get_error('username'); ?></div>
<?php endif ?>
</div>
<div class="mb-3">
<label for="last-name">Password:</label>
<input
type="password"
id="password"
name="password"
class="form-control <?= has_error('password') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('password')); ?>">
<?php if (has_error('password')): ?>
<div class="invalid-feedback"><?= get_error('password'); ?></div>
<?php endif ?>
</div>
<button type="submit" class="btn btn-primary btn-block">Login</button>
</form>
</div>
</div>
</div>
</div>
<?php endif ?>
</div>
</body>
</html>
All I am trying to do is escape html injection into my input text boxes. Am I not using htmlentities correctly?
Code:
<?php
require_once "pdo.php";
// Demand a GET parameter
if ( ! isset($_GET['name']) || strlen($_GET['name']) < 1 ) {
die('Name parameter missing');
} else {
$username = $_GET['name'];
}
// If the user requested logout go back to index.php
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
$year = isset($_POST['year']) ? $_POST['year'] : '';
$mileage = isset($_POST['mileage']) ? $_POST['mileage'] : '';
$make = isset($_POST['make']) ? $_POST['make'] : '';
$failure = false;
$success = false;
if ( isset($_POST['make']) && isset($_POST['year'])
&& isset($_POST['mileage'])) {
//$year = $_POST['year'];
//$mileage = $_POST['mileage'];
//$make = $_POST['make'];
if ( strlen($make) < 1){
$failure = "Make is Required";
} else {
if (is_numeric($year) and is_numeric($mileage) ){
error_log("year is a number ".$_POST['year']);
error_log("Mileage is a number ".$_POST['mileage']);
$sql = "INSERT INTO autos (make, year, mileage)
VALUES (:make, :year, :mileage)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':make' => $make,
':year' => $year,
':mileage' => $mileage));
$success = "Record Inserted";
} else {
$failure = "Mileage and Year must be numeric";
error_log("year or mileage is not a number year=".$_POST['year']);
error_log("Mileage or year is not a number mileage=".$_POST['mileage']);
}
}
}
if ( isset($_POST['delete']) && isset($_POST['auto_id']) ) {
$sql = "DELETE FROM autos WHERE auto_id = :zip";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':zip' => $_POST['auto_id']));
}
$stmt = $pdo->query("SELECT make, year, mileage, auto_id FROM autos");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Douglas Osborne's Automobile Tracker</title>
</head>
<body>
<table border="0">
<?php
foreach ( $rows as $row ) {
echo "<tr><td>";
echo($row['year']);
echo(" /");
echo("</td><td>");
echo($row['make']);
echo("</td><td>");
echo($row['mileage']);
echo(" miles");
echo("</td><td>");
echo('<form method="post"><input type="hidden" ');
echo('name="auto_id" value="'.$row['auto_id'].'">'."\n");
echo('<input type="submit" value="Del" name="delete">');
echo("\n</form>\n");
echo("</td></tr>\n");
}
?>
<body>
<div class="container">
<h1>
<?php
if ( isset($_REQUEST['name']) ) {
echo "<p>Tracking Autos for ";
echo htmlentities($_REQUEST['name']);
echo "</p>\n";
}
?>
</h1>
<p>
<?php
// Note triple not equals and think how badly double
// not equals would work here...
if ( $failure !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
if ( $success !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: green;">'.htmlentities($success)."</p>\n");
}
?>
</p>
<form method="post">
<p>Make:
<input type="text" name="make" size="60" value="<?= htmlentities($make) ?>"/>
</p>
<p>Year:
<input type="text" name="year" value="<?= htmlentities($year) ?>"/>
</p>
<p>Mileage:
<input type="text" name="mileage" value="<?= htmlentities($mileage) ?>"/>
</p>
<input type="submit" value="Add">
<input type="submit" name="logout" value="Logout">
</form>
<h2>Automobiles</h2>
<ul>
<p>
</ul>
</div>
</html>
Output wont escape see screenshot:
Adding htmlspecialchars to (make) gave me the result I was looking for. Thanks for anyone's attempt to help me.
I have read thru almost all docs on this but cant seem to find a tailored solution to my problem. The registration and login form is with php5, mysqli, jquery and bootstrap, but it's not submitting to the database.
For register.php
<?php require_once 'config.php'; ?>
<?php
if(!empty($_POST)){
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data)$success = USER_REGISTRATION_SUCCESS;
} catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Registration Form</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<?php require_once 'templates/ads.php';?>
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Smart</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="Name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="Signing Up....">Sign Up</button>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign In
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
and for the register.js
$(document).ready(function(){
$("#register-form").validate({
submitHandler : function(form) {
//$('#submit_btn').attr('disabled','disabled');
$('#submit_btn').attr('disabled','true');
$('#submit_btn').button('loading');
form.submit();
},
rules : {
name : {
required : true
},
email : {
required : true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password : {
required : true
},
confirm_password : {
required : true,
equalTo: "#password"
}
},
messages : {
name : {
required : "Please enter name"
},
email : {
required : "Please enter email",
remote : "Email already exists"
},
password : {
required : "Please enter password"
},
confirm_password : {
required : "Please enter confirm password",
equalTo: "Password and confirm password doesn't match"
}
},
errorPlacement : function(error, element) {
$(element).closest('div').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div').removeClass('has-error').addClass('has-success');
$(element).closest('div').find('.help-block').html('');
}
});
});
and this is for the user.php
<?php
/**
* This User will have functions that hadles user registeration,
* login and forget password functionality
*/
class Cl_User
{
/**
* #var will going contain database connection
*/
protected $_con;
/**
* it will initalize DBclass
*/
public function __construct()
{
$db = new Cl_DBclass();
$this->_con = $db->con;
}
/**
* this will handles user registration process
* #param array $data
* #return boolean true or false based success
*/
public function registration( array $data )
{
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$name = mysqli_real_escape_string( $this->_con, $trimmed_data['name'] );
$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
$cpassword = mysqli_real_escape_string( $this->_con, $trimmed_data['confirm_password'] );
// Check for an email address:
if (filter_var( $trimmed_data['email'], FILTER_VALIDATE_EMAIL)) {
$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email']);
} else {
throw new Exception( "Please enter a valid email address!" );
}
if((!$name) || (!$email) || (!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "INSERT INTO users (user_id, name, email, password, created) VALUES (NULL, '$name', '$email', '$password', CURRENT_TIMESTAMP)";
if(mysqli_query($this->_con, $query)){
mysqli_close($this->_con);
return true;
};
} else{
throw new Exception( USER_REGISTRATION_FAIL );
}
}
/**
* This method will handle user login process
* #param array $data
* #return boolean true or false based on success or failure
*/
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT user_id, name, email, created FROM users where email = '$email' and password = '$password' ";
$result = mysqli_query($this->_con, $query);
$data = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
mysqli_close($this->_con);
if( $count == 1){
$_SESSION = $data;
$_SESSION['logged_in'] = true;
return true;
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
/**
* This will shows account information and handles password change
* #param array $data
* #throws Exception
* #return boolean
*/
public function account( array $data )
{
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
$cpassword = $trimmed_data['confirm_password'];
$user_id = mysqli_real_escape_string( $this->_con, $trimmed_data['user_id'] );
if((!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "UPDATE users SET password = '$password' WHERE user_id = '$user_id'";
if(mysqli_query($this->_con, $query)){
mysqli_close($this->_con);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This handle sign out process
*/
public function logout()
{
session_unset();
session_destroy();
header('Location: index.php');
}
/**
* This reset the current password and send new password to mail
* #param array $data
* #throws Exception
* #return boolean
*/
public function forgetPassword( array $data )
{
if( !empty( $data ) ){
// escape variables for security
$email = mysqli_real_escape_string( $this->_con, trim( $data['email'] ) );
if((!$email) ) {
throw new Exception( FIELDS_MISSING );
}
$password = $this->randomPassword();
$password1 = md5( $password );
$query = "UPDATE users SET password = '$password1' WHERE email = '$email'";
if(mysqli_query($this->_con, $query)){
mysqli_close($this->_con);
$to = $email;
$subject = "New Password Request";
$txt = "Your New Password ".$password;
$headers = "From: admin#smarttutorials.net" . "\r\n" .
"CC: admin#smarttutorials.net";
mail($to,$subject,$txt,$headers);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This will generate random password
* #return string
*/
private function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
}
I maked image upload for my form, but this going with adding time to error
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null' in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php:58 Stack trace: #0 /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php(58): PDOStatement->execute(Array) #1 {main} thrown in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php on line 58
<?php
require 'conf/db.php';
if ( !empty($_POST)) {
// keep track validation errors
$nimiError = null;
$emailError = null;
$mobiilError = null;
$suguError = null;
// keep track post values
$nimi = $_POST['nimi'];
$email = $_POST['email'];
$mobiil = $_POST['mobiil'];
$sugu = $_POST['sugu'];
// validate input
$valid = true;
if (empty($nimi)) {
$nimiError = 'Palun sisesta nimi';
$valid = false;
}
if (empty($email)) {
$emailError = 'Palun sisesta e-mail';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Palun sisesta korrektne e-mail';
$valid = false;
}
if (empty($mobiil)) {
$mobiilError = 'Palun sisesta mobiili number';
$valid = false;
}
if (empty($sugu)) {
$suguError = 'Palun vali sugu';
$valid = false;
}
//Pilt
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
$image = $full_path;
}
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu,image) values(?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($nimi,$email,$mobiil,$sugu,$image));
Database::disconnect();
header("Location: index.php");
}
}
?>
<!DOCTYPE html>
<html lang="et">
<head>
<meta charset="utf-8">
<title>Klientide andmed by Siim Aarmaa IS-13</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<div class="row">
<h3>Lisa uus klient</h3>
</div>
<form class="form-horizontal" action="lisa.php" method="post">
<div class="form-group <?php echo !empty($nimiError)?'error':'';?>">
<label class="col-sm-2 control-label">Nimi</label>
<div class="controls">
<input name="nimi" type="text" placeholder="Nimi" value="<?php echo !empty($nimi)?$nimi:'';?>">
<?php if (!empty($nimiError)): ?>
<span class="help-block"><?php echo $nimiError;?></span>
<?php endif; ?>
</div>
</div>
<div class="form-group <?php echo !empty($emailError)?'error':'';?>">
<label class="col-sm-2 control-label">E-mail</label>
<div class="controls">
<input name="email" type="text" placeholder="E-mail" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-block"><?php echo $emailError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-group <?php echo !empty($mobiilError)?'error':'';?>">
<label class="col-sm-2 control-label">Mobiili number</label>
<div class="controls">
<input name="mobiil" type="text" placeholder="Mobiili number" value="<?php echo !empty($mobiil)?$mobiil:'';?>">
<?php if (!empty($mobiilError)): ?>
<span class="help-block"><?php echo $mobiilError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-group <?php echo !empty($suguError)?'error':'';?>">
<label class="col-sm-2 control-label">Sugu</label>
<div class="controls">
<input name="sugu" type="radio" value="<?php echo !empty($mees)?$mees:'Mees';?>">Mees
<input name="sugu" type="radio" value="<?php echo !empty($naine)?$naine:'Naine';?>">Naine
<?php if (!empty($suguError)): ?>
<span class="help-block"><?php echo $suguError;?></span>
<?php endif;?>
</div><br>
<div class="form-group <?php echo !empty($mobiilError)?'error':'';?>">
<label class="col-sm-2 control-label">Pilt</label>
<div class="controls">
<input type="file" name="image" required="required" value=""/>
<?php if (!empty($mobiilError)): ?>
<span class="help-block"><?php echo $mobiilError;?></span>
<?php endif;?>
</div>
</div>
<br>
<div class="form-group">
<button type="submit" class="btn btn-success">Lisa klient</button>
<a class="btn btn-default" href="index.php">Tagasi</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Looks like something went wrong with the fileupload. You have no else branches for the is_uploaded_file() and move_uploaded_file() checks.
<?php
require 'conf/db.php';
$errors = array();
if ( !isset($_POST['nimi'],$_POST['email'],$_POST['mobiil'],$_POST['sugu']) ) {
$errors['parameter'] = 'missing POST parameter';
}
else {
// keep track post values
$nimi = $_POST['nimi'];
$email = $_POST['email'];
$mobiil = $_POST['mobiil'];
$sugu = $_POST['sugu'];
// validate input
if (empty($nimi)) {
$errors['nimi'] = 'Palun sisesta nimi';
}
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$errors['email'] = 'Palun sisesta korrektne e-mail';
}
if (empty($mobiil)) {
$errors['mobiil'] = 'Palun sisesta mobiili number';
}
if (empty($sugu)) {
$errors['suguError'] = 'Palun vali sugu';
}
if ( empty($errors) ) {
//Pilt
if( !is_uploaded_file($_FILES['image']['tmp_name']) ) {
$errors['upload'] = 'no file uploaded';
}
else {
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if( !move_uploaded_file($_FILES['image']['tmp_name'], $full_path) ) {
$errors['upload'] = 'cannot move file';
}
else {
$image = $full_path;
}
}
}
}
// insert data
if ( empty($errors) ) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu,image) values(?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute( array($nimi,$email,$mobiil,$sugu,$image) );
Database::disconnect();
header("Location: index.php");
die;
}
else {
echo '<pre>', join("\r\n", $errors), '</pre>';
}
The problem is because of the Undefined index: image, which means your file didn't get uploaded. And that's because you didn't set the enctype="multipart/form-data" in your <form> element. It should be,
<form class="form-horizontal" action="lisa.php" method="post" enctype="multipart/form-data">
// your HTML code
</form>
Hi I am struggling to see why this isn't updating the database. It reloads the page directed to by the HEADER but does not update the any field. Any help would be grealty appreaciated.
Update Form
<?php
include("../script/dbconnect.php");
include("../script/addprodcat.php");
$post = get_posts($_GET['id']);
if ( isset($_POST['name'], $_POST['description'], $_POST['price'], $_POST['sale'], $_POST['picture'], $_POST['category']) ) {
$errors = array();
$name = trim($_POST['name']);
$description = trim($_POST['description']);
if ( empty($name) ) {
$errors[] = 'You need to supply a title';
} else if ( strlen($name) > 255 ) {
$errors[] = 'Title cannot be longer than 255 characters';
}
if ( empty($description) ) {
$errors[] = 'You need to supply text';
}
if ( empty($price) ) {
$errors[] = 'You need to supply text';
}
if ( empty($sale) ) {
$errors[] = 'You need to supply text';
}
if ( empty($picture) ) {
$errors[] = 'You need to supply text';
}
if (! category_exists('id', $_POST['category']) ) {
$errors[] = 'Category does not exist';
}
if ( empty($errors) ) {
edit_product($_GET['id'], $name, $description, $price, $sale, $picture, $_POST['category']);
header("Location: ../admin/edit_products.php?id={$post[0]['post_id']}");
die();
}
}
?>
<div style="width:100%; height:150px; background-color:white;"><span style="font-family:saxMonoRegular; letter-spacing:2px; display:block; font-size:4.5em; text-align:center; padding-top:15px;"> Edit <?php echo $post[0]['name']; ?> </span></div>
<div class="link" style="width:100%; background-color:#ccc;">
<form action="" method="post">
<?php
if ( isset($errors) && ! empty($errors) ) {
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
}
?>
<label for="name">Title</label>
<input type="text" name="name" value="<?php echo $post[0]['name']; ?>"><br/>
<label for="price">Price</label>
<input type="text" name="price" value="<?php echo $post[0]['price']; ?>"><br/>
<label for="sale">Sale</label>
<input type="text" name="sale" value="<?php echo $post[0]['sale']; ?>"><br/>
<label for="picture">Picture</label>
<input type="text" name="picture" value="<?php echo $post[0]['picture']; ?>"><br/>
<label for="description">Description</label>
<textarea name="description" rows="15" cols="50"><?php echo $post[0]['description']; ?></textarea><br/>
<label for="prod_id">Category</label>
<select name="prod_id">
<?php
foreach ( get_categories() as $category ) {
$selected = ( $category['name'] == $post[0]['name'] ) ? " selected" : '';
?>
<option value="<?php echo $category['id']; ?>" <?php echo $selected; ?>> <?php echo $category['name']; ?></option>
<?php
}
?>
</select><br/>
<input class="button-link" type="submit" value="Edit Post">
</form>
</div>
addprodcat.php
function edit_product($id, $prod_id, $prod_sub_id, $name, $description, $price, $sale, $picture, $category) {
$id = (int) $id;
$prod_id = (int) $prod_id;
$prod_sub_id = (int) $prod_sub_id;
$name = mysql_real_escape_string($name);
$description = mysql_real_escape_string($description);
$price = mysql_real_escape_string($price);
$sale = mysql_real_escape_string($sale);
$picture = mysql_real_escape_string($picture);
$category = (int) $category;
mysql_query("UPDATE `products` SET
`cat_id` = {$category},
`prod_id` = {$prod_id},
`prod_sub_id ` = '{$prod_sub_id}',
`name` = '{$name}',
`description` = '{$description}',
`price` = '{$price}',
`sale` = '{$sale}',
`picture` = '{$picture}'
WHERE `id` = {$id}");
echo mysql_error();
}
Your update form passes only 7 parameters to the edit_products function; this function, however, expects 9.
edit_product($_GET['id'], $name, $description, $price, $sale, $picture, $_POST['category']);
...
function edit_product($id, $prod_id, $prod_sub_id, $name, $description, $price, $sale, $picture, $category)
You need to pass $prod_id and $prod_sub_id as well.
As an extra note, it's worth commenting out any redirects when debugging code as any (non-fatal) errors/warnings that would otherwise be shown are missed.
Number of function parameters differ. The function expects 9 but you provided 7.
This is a common user error that happens in lengthy lines.
Use the coding standard like this:
function edit_product(
$id,
$prod_id,
$prod_sub_id,
$name,
$description,
$price,
$sale,
$picture,
$category
) {
/*function code */
}
Follow same standard when you 'call' the function too.