I am developing a website with User registration and login ,after completing the page configuration ,i tried to register it worked perfectly and later next day i tried to register but the page is not loading ,after filling in the data and if i click submit ,it reloads the same register page with no effect ,how to solve this problem
SQL Query Processing code:
<?php
class User
{
public $user_active = 0;
private $clean_email;
public $status = false;
private $clean_password;
private $clean_username;
private $unclean_username;
public $sql_failure = false;
public $mail_failure = false;
public $email_taken = false;
public $username_taken = false;
public $activation_token = 0;
function __construct($user, $pass, $email)
{
// Used for display only
$this->unclean_username = $user;
// Sanitize
$this->clean_email = sanitize($email);
$this->clean_password = trim($pass);
$this->clean_username = sanitize($user);
if (usernameExists($this->clean_username)) {
$this->username_taken = true;
}
else if (emailExists($this->clean_email)) {
$this->email_taken = true;
}
else {
// No problems have been found.
$this->status = true;
}
}
public function userPieAddUser()
{
global $db, $emailActivation, $websiteUrl, $db_table_prefix;
// Prevent this function being called if there were construction errors
if ($this->status) {
// Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
// Construct a unique activation token
$this->activation_token = generateactivationtoken();
// Do we need to send out an activation email?
if ($emailActivation) {
// User must activate their account first
$this->user_active = 0;
$mail = new userPieMail();
// Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE", array(
"{$websiteUrl}/",
$this->activation_token
));
// Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array(
"#ACTIVATION-MESSAGE",
"#ACTIVATION-KEY",
"#USERNAME#"
) ,
"subjectStrs" => array(
$activation_message,
$this->activation_token,
$this->unclean_username
)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if (!$mail->newTemplateMsg("new-registration.txt", $hooks)) {
$this->mail_failure = true;
}
else {
// Send the mail. Specify users email here and subject.
// SendMail can have a third parementer for message if you do not wish to build a template.
if (!$mail->sendMail($this->clean_email, "New User")) {
$this->mail_failure = true;
}
}
}
else {
// Instant account activation
$this->user_active = 1;
}
if (!$this->mail_failure) {
// Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `" . $db_table_prefix . "users` (
`username`,
`username_clean`,
`password`,
`email`,
`activationtoken`,
`last_activation_request`,
`LostpasswordRequest`,
`active`,
`group_id`,
`sign_up_date`,
`last_sign_in`
)
VALUES (
'" . $db->sql_escape($this->unclean_username) . "',
'" . $db->sql_escape($this->clean_username) . "',
'" . $secure_pass . "',
'" . $db->sql_escape($this->clean_email) . "',
'" . $this->activation_token . "',
'" . time() . "',
'0',
'" . $this->user_active . "',
'1',
'" . time() . "',
'0'
)";
return $db->sql_query($sql);
}
}
}
}
?>
Config.php file for Register Processing
<?php
if (is_dir("install/")) {
header("Location: install/");
die();
}
require_once ("settings.php");
// Dbal Support - Thanks phpBB ; )
require_once ("db/" . $dbtype . ".php");
// Construct a db instance
$db = new $sql_db();
if (is_array($db->sql_connect($db_host, $db_user, $db_pass, $db_name, $db_port, false, false))) {
die("Unable to connect to the database");
}
if (!isset($language)) $langauge = "en";
require_once ("lang/" . $langauge . ".php");
require_once ("class.user.php");
require_once ("class.mail.php");
require_once ("funcs.user.php");
require_once ("funcs.general.php");
require_once ("class.newuser.php");
session_start();
// Global User Object Var
// loggedInUser can be used globally if constructed
if (isset($_SESSION["userPieUser"]) && is_object($_SESSION["userPieUser"])) $loggedInUser = $_SESSION["userPieUser"];
else if (isset($_COOKIE["userPieUser"])) {
$db->sql_query("SELECT session_data FROM " . $db_table_prefix . "sessions WHERE session_id = '" . $_COOKIE['userPieUser'] . "'");
$dbRes = $db->sql_fetchrowset();
if (empty($dbRes)) {
$loggedInUser = NULL;
setcookie("userPieUser", "", -parseLength($remember_me_length));
}
else {
$obj = $dbRes[0];
$loggedInUser = unserialize($obj["session_data"]);
}
}
else {
$db->sql_query("DELETE FROM " . $db_table_prefix . "sessions WHERE " . time() . " >= (session_start+" . parseLength($remember_me_length) . ")");
$loggedInUser = NULL;
}
?>
Register Page PHP Code
<?php
require_once ("models/config.php");
// Prevent the user visiting the logged in page if he/she is already logged in
if (isUserLoggedIn()) {
header("Location: index.php");
die();
}
/*
Below is a very simple example of how to process a new user.
Some simple validation (ideally more is needed).
The first goal is to check for empty / null data, to reduce workload here we let the user class perform it's own internal checks, just in case they are missed.
*/
// Forms posted
if (!empty($_POST)) {
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
// Perform some validation
// Feel free to edit / change as required
if (minMaxRange(5, 25, $username)) {
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT", array(
5,
25
));
}
if (minMaxRange(8, 50, $password) && minMaxRange(8, 50, $confirm_pass)) {
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT", array(
8,
50
));
}
else if ($password != $confirm_pass) {
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if (!isValidemail($email)) {
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
// End data validation
if (count($errors) == 0) {
// Construct a user object
$user = new User($username, $password, $email);
// Checking this flag tells us whether there were any errors such as possible data duplication occured
if (!$user->status) {
if ($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE", array(
$username
));
if ($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE", array(
$email
));
}
else {
// Attempt to add the user to the database, carry out finishing tasks like emailing the user (if required)
if (!$user->userPieAddUser()) {
if ($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if ($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if (count($errors) == 0) {
if ($emailActivation) {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
}
else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
HTML Register Form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Registration |
<?php echo $websiteName; ?>
</title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>
Sign Up
</h2>
</div>
<div class="modal-body">
<div id="success">
<p>
<?php echo $message ?>
</p>
</div>
<div id="regbox">
<form name="newUser" action="
<?php echo $_SERVER['PHP_SELF'] ?>
" method="post">
<p>
<label>
Username:
</label>
<input type="text" name="username" />
</p>
<p>
<label>
Password:
</label>
<input type="password" name="password" />
</p>
<p>
<label>
Re-type Password:
</label>
<input type="password" name="passwordc" />
</p>
<p>
<label>
Email:
</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear">
</div>
<p style="margin-top:30px; text-align:center;">
<a href="login.php">
Login
</a>
/
<a href="forgot-password.php">
Forgot Password?
</a>
/
<a href="
<?php echo $websiteUrl; ?>
">
Home Page
</a>
</p>
</body>
</html>
In your html file remove the action attribute of tag form or use action = "". Donot use $_SERVER[PHP_SELF] as it is prone to extra scripts being run from your page.
Other than that, will check the code. Try using echo or print_r wherever possible to check what part is causing problem. Use try-catch for checking if the db returns errors in SQL.
Related
I am trying to add the login function to my website, but when I clicked on the login button, the page crashes and gives the following error message:
/index.php - Uncaught Error: Call to a member function prepare() on
null in
/Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php:56
Stack trace:
0 /Users/xx/Documents/INFO2300/xxproject-3/includes/init.php(82): exec_sql_query(NULL, 'SELECT * FROM u...', Array)
1 /Users/xx/Documents/INFO2300/xx-project-3/includes/init.php(199): log_in('xx333', 'xx')
2 /Users/xxDocuments/INFO2300/xx333-project-3/index.php(2): include('/Users/xx/D...')
3 {main} thrown in /Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php on line
56
Here is my code for index.php:
<?php
include("includes/init.php");
$db = open_or_init_sqlite_db('secure/gallery.sqlite', 'secure/init.sql');
$messages = array();
// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
const MAX_FILE_SIZE = 1000000;
// Users must be logged in to upload files!
if ( isset($_POST["submit_upload"]) && is_user_logged_in() ) {
// TODO: filter input for the "box_file" and "description" parameters.
// Hint: filtering input for files means checking if the upload was successful
$upload_info=$_FILES["box_file"];
$upload_desc=filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
if ($upload_info['error']==UPLOAD_ERR_OK){
$upload_name=basename($upload_info["name"]);
$upload_ext = strtolower( pathinfo($upload_name, PATHINFO_EXTENSION) );
$sql="INSERT INTO documents(user_id,file_name,file_ext,description)VALUES(:user_id,:file_name,:file_ext,:description)";
$params=array(
':user_id' => $current_user['id'],
':file_name'=> $upload_name,
':file_ext'=>$upload_ext,
':description'=>$upload_desc,
);
$result=exec_sql_query($db, $sql, $params);
if ($result){
$file_id=$db->lastInsertId("id");
$new_path="uploads/documents/$file_id.$upload_ext";
move_uploaded_file($upload_info["tmp_name"],$new_path);
}
}
// TODO: If the upload was successful, record the upload in the database
// and permanently store the uploaded file in the uploads directory.
// $box_file=filter_input(INPUT_POST, "box_file", FILTER_SANITIZE_STRING);
// $description=filter_input(INPUT_POST,"description", FILTER_SANITIZE_STRING);
}
?>
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style/all.css" media="all" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
</head>
<body>
<h1>Fine Art Photography</h1>
<div id="content-wrap">
<?php
// If the user is logged in, let them upload files and view their uploaded files.
if ( is_user_logged_in() ) {
foreach ($messages as $message) {
echo "<p><strong>" . htmlspecialchars($message) . "</strong></p>\n";
}
?>
<h2>Upload a File</h2>
<!-- TODO: Peer review this form checking to make sure it properly supports file uploads. -->
<form id="uploadFile" action="index2.php" method="post" enctype="multipart/form-data">
<ul>
<li>
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<label for="box_file">Upload File:</label>
<input id="box_file" type="file" name="box_file">
</li>
<li>
<label for="box_desc">Description:</label>
<textarea id="box_desc" name="description" cols="40" rows="5"></textarea>
</li>
<li>
<button name="submit_upload" type="submit">Upload File</button>
</li>
</ul>
</form>
<?php
} else {
?>
<p><strong>You need to sign in before you can upload image.</strong></p>
<?php
include("includes/login.php");
}
?>
<!-- <h2>Saved Files</h2> -->
<h2>Categories</h2>
<h2>Photos</h2>
<div class="img">
<?php
$records = exec_sql_query($db, "SELECT * FROM images")->fetchAll(PDO::FETCH_ASSOC);
if (count($records) > 0) {
foreach($records as $record) {
echo "<div class=\"content\">";
echo "<div class=\"block\">";
echo "<img class=\"pic\" src=\"uploads/images/". $record["id"] . "." . $record["image_ext"]. "\"/>";
echo "<a href=\"uploads/images/". $record["id"] . "." . $record["image_ext"] .
"\"class=\"link\">" . htmlspecialchars($record["image_name"]) . "</a>";
echo "<p class=\"link\">" . htmlspecialchars($record["description"]). "</p>";
echo "</div>";
echo "</div>";
}
}
?>
</div>
</body>
</html>
And here is my code for init.php:
<?php
// vvv DO NOT MODIFY/REMOVE vvv
// check current php version to ensure it meets 2300's requirements
function check_php_version()
{
if (version_compare(phpversion(), '7.0', '<')) {
define(VERSION_MESSAGE, "PHP version 7.0 or higher is required for 2300. Make sure you have installed PHP 7 on your computer and have set the correct PHP path in VS Code.");
echo VERSION_MESSAGE;
throw VERSION_MESSAGE;
}
}
check_php_version();
function config_php_errors()
{
ini_set('display_startup_errors', 1);
ini_set('display_errors', 0);
error_reporting(E_ALL);
}
config_php_errors();
// open connection to database
function open_or_init_sqlite_db($db_filename, $init_sql_filename)
{
if (!file_exists($db_filename)) {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (file_exists($init_sql_filename)) {
$db_init_sql = file_get_contents($init_sql_filename);
try {
$result = $db->exec($db_init_sql);
if ($result) {
return $db;
}
} catch (PDOException $exception) {
// If we had an error, then the DB did not initialize properly,
// so let's delete it!
unlink($db_filename);
throw $exception;
}
} else {
unlink($db_filename);
}
} else {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
return null;
}
function exec_sql_query($db, $sql, $params = array())
{
$query = $db->prepare($sql);
if ($query and $query->execute($params)) {
return $query;
}
return null;
}
// ^^^ DO NOT MODIFY/REMOVE ^^^
// You may place any of your code here.
// $db = open_or_init_sqlite_db('secure/site.sqlite', 'secure/init.sql');
define('SESSION_COOKIE_DURATION', 60*60*1);
$session_messages = array();
function log_in($username, $password) {
global $db;
global $current_user;
global $session_messages;
if ( isset($username) && isset($password) ) {
// check if username exists in the database
$sql = "SELECT * FROM users WHERE username = :username;";
$params = array(
':username' => $username
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// There shouldn't be repetitive username.
$account = $records[0];
// Check if password is correct
if ( password_verify($password, $account['password']) ) {
// Create session
$session = session_create_id();
// Store session ID in database
$sql = "INSERT INTO sessions (user_id, session) VALUES (:user_id, :session);";
$params = array(
':user_id' => $account['id'],
':session' => $session
);
$result = exec_sql_query($db, $sql, $params);
if ($result) {
// If result exists, session stored in DB
// Send this back to the user.
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
$current_user = $account;
return $current_user;
} else {
array_push($session_messages, "Log in failed. Something went wrong");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "No username or password given.");
}
$current_user = NULL;
return NULL;
}
function find_user($user_id) {
global $db;
$sql = "SELECT * FROM users WHERE id = :user_id;";
$params = array(
':user_id' => $user_id
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// users are unique, there should only be 1 record
return $records[0];
}
return NULL;
}
function find_session($session) {
global $db;
if (isset($session)) {
$sql = "SELECT * FROM sessions WHERE session = :session;";
$params = array(
':session' => $session
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// No repetitive sessions
return $records[0];
}
}
return NULL;
}
function session_login() {
global $db;
global $current_user;
if (isset($_COOKIE["session"])) {
$session = $_COOKIE["session"];
$session_record = find_session($session);
if ( isset($session_record) ) {
$current_user = find_user($session_record['user_id']);
// The session will last for 1 more hour
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
return $current_user;
}
}
$current_user = NULL;
return NULL;
}
function is_user_logged_in() {
global $current_user;
// if $current_user is not NULL, then a user is logged in.
return ($current_user != NULL);
}
function log_out() {
global $current_user;
// Remove the session from the cookie and fgo back in time to expire the session.
setcookie('session', '', time() - SESSION_COOKIE_DURATION);
$current_user = NULL;
}
// ---- Check for login, logout requests. Or check to keep the user logged in. ----
// Check if we should login the user
if ( isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password']) ) {
$username = trim( $_POST['username'] );
$password = trim( $_POST['password'] );
log_in($username, $password);
} else {
// check if the user already logged in
session_login();
}
// Check if we should logout the user
if ( isset($current_user) && ( isset($_GET['logout']) || isset($_POST['logout']) ) ) {
log_out();
}
?>
$_POST is not getting any values and i have tried a lot of procedure already mentioned on stack overflow but they are not working for me. I have tried printing the $_POST it is empty. i need some suggestions on it..please help
It was previously working when it was in mysql database but i tried to change the database to sqlserver and now its not working but i am not understanding i have not made any changes to this particular code and i have seen this also that it is not being affected by some other file.
there is no mistake in empty condition i wrote it myself to check whether it was empty or not and it was always showing empty whether i submit data or not
i am attaching some codes which are related to this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<?php
ob_start();
session_start();
require_once 'config.php';
?>
<?php
if(empty($_POST)){
echo "hello";
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data){
$_SESSION['success'] = USER_REGISTRATION_SUCCESS;
header('Location: index.php');exit;
}
} catch (Exception $e) {
$_SESSION['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">
<meta name="description" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<meta name="keywords" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<title>PHP Quiz Script</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">
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">PHP Quiz Application</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" name="submit">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>
<?php unset($_SESSION['success'] ); unset($_SESSION['error']); ?>
<?php
$server="NIKUNJ";
$ci = array("Database" => "My database","UID"=>"sa", "PWD"=>"sql#123","Characterset"=>"UTF-8") or die( "check db connect1" );
$conn = sqlsrv_connect($server,$ci) or die ( "check db connect2" ) ;
function mssql_escape($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
function mssql_insert_id() {
$id = 0;
$res = sqlsrv_query("SELECT ##identity AS id");
if ($row = sqlsrv_fetch_array($res, MSSQL_ASSOC)) {
$id = $row["id"];
}
return $id;
}
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 )
{
echo "hello";
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$name = mssql_escape( $trimmed_data['name'] );
$password = mssql_escape( $trimmed_data['password'] );
$cpassword = mssql_escape( $trimmed_data['confirm_password'] );
// Check for an email address:
if (filter_var( $trimmed_data['email'], FILTER_VALIDATE_EMAIL)) {
$email = mssql_escape( $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 (id, name, email, password, created) VALUES (NULL, '$name', '$email', '$password', CURRENT_TIMESTAMP)";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_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 = mssql_escape( $this->_con, $trimmed_data['email'] );
$password = mssql_escape( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT id, name, email, created FROM users where email = '$email' and password = '$password' ";
$result = sqlsrv_query($this->_con, $query);
$data = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
$count = SQLSRV_num_rows($result);
echo $count;
sqlsrv_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 = mssql_escape( $this->_con, $trimmed_data['password'] );
$cpassword = $trimmed_data['confirm_password'];
$user_id = $_SESSION['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 id = '$user_id'";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This handle sign out process
*/
public function logout()
{
session_unset();
session_destroy();
session_start();
$_SESSION['success'] = LOGOUT_SUCCESS;
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 = mssql_escape( $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(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
$to = $email;
$subject = "New Password Request";
$txt = "Your New Password ".$password;
$headers = "From: rahul.ranjan72#hotmail.com" . "\r\n" .
"CC:rahul.ranjan72#hotmail.com";
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
}
public function pr($data = '' )
{
echo "<pre>"; print_r($data); echo "</pre>";
}
public function getCategory()
{
$query = "SELECT * FROM categories";
$results = sqlsrv_query($conn, $query) or die(SQLSRV_errors());
$categories = array();
while ( $result = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC) ) {
echo $result['id'];
$categories[$result['id']] = $result['category_name'];
}
return $categories;
}
public function getQuestions(array $data)
{
if( !empty( $data ) ){
// escape variables for security
$category_id = mssql_escape( $this->_con, trim( $data['category'] ) );
if((!$category_id) ) {
throw new Exception( FIELDS_MISSING );
}
$user_id = $_SESSION['id'];
$query = "INSERT INTO scores ( user_id,right_answer,category_id)VALUES ( '$user_id',0,'$category_id')";
sqlsrv_query( $this->_con, $query);
$_SESSION['score_id'] = mssql_insert_id();
$results = array();
$number_question = $_POST['num_questions'];
$total_question = $_POST['total_num_questions'];
$row = sqlsrv_query( $this->_con, "select * from questions where category_id=$category_id ORDER BY RAND()");
$check=SQLSRV_num_rows($row);
if($check<$total_question)
$rowcount=$check;
else
$rowcount = $total_question;
$remainder = $rowcount/$number_question;
$results['number_question'] = $number_question;
$results['remainder'] = $remainder;
$results['rowcount'] = $rowcount;
while ( $result = SQLSRV_FETCH_ASSOC($row) ) {
$results['questions'][] = $result;
}
sqlsrv_close($this->_con);
return $results;
} else{
throw new Exception( FIELDS_MISSING );
}
}
public function getAnswers(array $data)
{
if( !empty( $data ) ){
$right_answer=0;
$wrong_answer=0;
$unanswered=0;
$total_question = $_POST['total_num_questions'];
$keys=array_keys($data);
$order=join(",",$keys);
$query = "select id,answer from questions where id IN($order) ORDER BY FIELD(id,$order)";
$response=sqlsrv_query( $this->_con, $query) or die(SQLSRV_errors());
$user_id = $_SESSION['id'];
$score_id = $_SESSION['score_id'];
while($result=sqlsrv_fetch_array($response)){
if($result['answer']==$_POST[$result['id']]){
$right_answer++;
}else if($data[$result['id']]=='smart_quiz'){
$unanswered++;
}
else{
$wrong_answer++;
}
}
$results = array();
$results['right_answer'] = $right_answer;
$results['wrong_answer'] = $wrong_answer;
$results['unanswered'] = $unanswered;
$update_query = "update scores set right_answer='$right_answer', wrong_answer = '$wrong_answer', unanswered = '$unanswered' where user_id='$user_id' and id ='$score_id' ";
sqlsrv_query( $this->_con, $update_query) or die(SQLSRV_errors());
sqlsrv_close($this->_con);
return $results;
}
}
}
<?php
/**
#author vetripandi
#copyright http:www.vetbossel.in
*/
require_once 'messages.php';
//site specific configuration declartion
define( 'DB_HOST', 'NIKUNJ' );
define( 'DB_USERNAME', 'sa');
define( 'DB_PASSWORD', 'sql#123');
define( 'DB_NAME', 'user_login');
function __autoload($class)
{
$parts = explode('_', $class);
$path = implode(DIRECTORY_SEPARATOR,$parts);
require_once $path . '.php';
}
its the image of the data i am sending but $_POST is not getting any values and nothing happens after signup button is pressed
Your code is only running if the $_POST array is empty.
Change your code to the following.
if(!empty($_POST))
Other than that, I see no problems.
It's better practice to take the submit button as a centre of attention for the execution of the server side coding executing.
Therefore check if the $_POST data has been sent using isset:
if (isset($_POST['submit']))
{
// the data has successfully been sent
}
are you sure is's ok ?
if(empty($_POST))
you always execute code in if if $_POST is empty
if(!empty($_POST))
execute when $_POST NOT empty
This may not be your problem, but generally the submit button is
<input type="submit" value="submit">
rather than
<button type="submit">Submit</button>
From: W3schools.com
I got my mistake. I dont know how but the value of the forms were not only transferred to this php file but also in another php file names check-email.php which was part of my project which was not mentioned anywhere in register.php.
I got to know the problem by seeing some post related to this kind of problem on stack overflow where he said to check you PHP_error_log and Apache error log. The error was clearly stated there. By doing some changes to check-email.php it is working fine now. Thank you everybody for your help anyway
I have a PHP script which will return order information from the Magento API depending upon the order ID entered. I added two additional input fields to the form for the API username and password so that they weren't stored on the PHP script file.
This works great, except I need to be able for the script to catch the error that is caused when the API username and/or password are incorrect.
Here is a successful query:
The bottom line is what was returned when clicking Submit. If the query is unsuccessful, the script will not return back to the initial form page and looks like this:
Please see my code below:
Form Page
<?php
session_start();
?>
<html>
<head>
<title>Retrieve Order</title>
<link rel="stylesheet" type="text/css" href="/matt/api.css">
</head>
<body>
<form class="get_value" action="get_order.php" method="post">
Enter username and password.
<input type="text" name="api_user">
<input type="password" name="api_pass"><br><br>
Enter an order ID to retrieve the grand total order value.<br><br>
<input type="text" name="order_id">
<input type="submit" class="form_submit">
</form>
</body>
</html>
<?php
if (isset($_SESSION['query_result'])) {
echo $_SESSION['query_result'];
unset($_SESSION['query_result']);
}
?>
PHP Script
<link rel="stylesheet" type="text/css" href="/matt/api.css">
<?php
$order_id = $_POST['order_id'];
$user = $_POST['api_user'];
$pass = $_POST['api_pass'];
$client = new SoapClient('https://ts564737-container.zoeysite.com/api/v2_soap/?wsdl');
$session = $client->login($user, $pass);
$filter = array('filter' => array(array('key' => 'order_id', 'value' => $order_id)));
$result = $client->salesOrderList($session, $filter);
session_start();
if ($result) {
foreach ($result as $returned_order) {
$_SESSION['query_result'] = 'The grand total of order ID <b>' . $order_id . '</b> is <span style="color: #ff0000; font-weight: bold;">£' . round($returned_order->grand_total, 2) . '</span>';
}
} else {
$_SESSION['query_result'] = 'Order ID <b>' . $order_id . '</b> does not exist in the database.';
}
header('Location: xxx/enter_order_id.php');
?>
How can I "catch" the error so that it is returned as part of the query_result session variable? Thank you very much for your insight.
Wrap the variables and the statement in a try-catch exception handler. Working code:
<?php
session_start();
try {
$order_id = $_POST['order_id'];
$user = $_POST['api_user'];
$pass = $_POST['api_pass'];
$client = new SoapClient('https://ts564737-container.zoeysite.com/api/v2_soap/?wsdl');
$session = $client->login($user, $pass);
$filter = array('filter' => array(array('key' => 'order_id', 'value' => $order_id)));
$result = $client->salesOrderList($session, $filter);
if ($result) {
foreach ($result as $returned_order) {
$_SESSION['query_result'] = '<span class="success_box">The grand total of order ID <b>' . $order_id . '</b> is <b>£' . round($returned_order->grand_total, 2) . '</b></span>';
}
} else {
$_SESSION['query_result'] = '<span class="error_box"><b>Error:</b> Order ID <b>' . $order_id . '</b> does not exist in the database.</span>';
}
} catch(exception $e) {
$_SESSION['query_result'] = '<span class="error_box"><b>Error:</b> ' . $e->getMessage() . '</span>';
}
header('Location: xxx');
?>
I am trying to figure out how I can create dynamic meta tags, using my mysql database to grab the info.
Right now I have
<meta name="twitter:card" content="player" />
<meta name="twitter:description" content="Share your sounds. Sign up with your Twitter account." />
<meta name="twitter:site" content="#Gabberus" />
<meta name="twitter:title" content="{$title}" />
<meta name="twitter:image" content="https://gabber.us/uploads/media/{$art}" />
<meta name="twitter:player" content="https://gabber.us/embed.php?id={$id}" />
Now, the problem that I have. Is the {$title} will set the correct title (song name) but {$id} {$name} and {$art} (id, name, art are the database columns) doesn't grab any info from the database.
I am not experienced in PHP and any input would be great.
Would it be possible to add something like this to my config.php file
$CONF['tplayer'] = 'https://gabber.us/embed.php?id=IDHERE';
so that I can use {$tplayer} in the meta?
If I am completly wrong please let me know, any help is appreciated.
Best,
Jamie
Added: index.php
<?php
session_start();
require_once('./includes/config.php');
require_once('./includes/skins.php');
require_once('./includes/classes.php');
require_once('info.php');
require_once(getLanguage(null, (!empty($_GET['lang']) ? $_GET['lang'] : $_COOKIE['lang']), null));
$db = new mysqli($CONF['host'], $CONF['user'], $CONF['pass'], $CONF['name']);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$db->set_charset("utf8");
if(isset($_GET['a']) && isset($action[$_GET['a']])) {
$page_name = $action[$_GET['a']];
} else {
$page_name = 'welcome';
}
// Extra class for the content [main and sidebar]
$TMPL['content_class'] = ' content-'.$page_name;
require_once("./sources/{$page_name}.php");
$resultSettings = $db->query(getSettings());
// Added to verify whether the user imported the database or not
if($resultSettings) {
$settings = $resultSettings->fetch_assoc();
} else {
echo "Error: ".$db->error;
}
// Store the theme path and theme name into the CONF and TMPL
$TMPL['theme_path'] = $CONF['theme_path'];
$TMPL['theme_name'] = $CONF['theme_name'] = $settings['theme'];
$TMPL['theme_url'] = $CONF['theme_url'] = $CONF['theme_path'].'/'.$CONF['theme_name'];
$TMPL['volume'] = $settings['volume'];
$TMPL['supplied_formats'] = $settings['trackformat'];
$TMPL['site_title'] = $settings['title'];
if(isset($_SESSION['username']) && isset($_SESSION['password']) || isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$loggedIn = new loggedIn();
$loggedIn->db = $db;
$loggedIn->url = $CONF['url'];
$loggedIn->username = (isset($_SESSION['username'])) ? $_SESSION['username'] : $_COOKIE['username'];
$loggedIn->password = (isset($_SESSION['password'])) ? $_SESSION['password'] : $_COOKIE['password'];
$verify = $loggedIn->verify();
}
$TMPL['content'] = PageMain();
if(!empty($verify['username'])) {
$TMPL['menu'] = menu($verify);
$TMPL['menu_buttons'] = menuButtons($verify);
$TMPL['url_menu'] = $CONF['url'].'/index.php?a=stream';
} else {
$TMPL['menu'] = menu(false);
$TMPL['menu_buttons'] = menuButtons(false);
$TMPL['url_menu'] = $CONF['url'].'/index.php?a=welcome';
}
if($settings['captcha']) {
// Captcha
$TMPL['captcha'] = '<div class="modal-captcha"><input type="text" name="captcha" placeholder="'.$LNG['captcha'].'"></div>
<span class="register-captcha" id="captcha-register"><img src="'.$CONF['url'].'/includes/captcha.php" /></span>';
}
if($settings['fbapp']) {
// Generate a session to prevent CSFR
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
// Facebook Login Url
$TMPL['fblogin'] = '<div class="modal-btn modal-btn-facebook">Facebook</div>';
}
$TMPL['url'] = $CONF['url'];
$TMPL['year'] = date('Y');
$TMPL['powered_by'] = 'Powered by '.$name.'.';
$TMPL['language'] = getLanguage($CONF['url'], null, 1);
$skin = new skin('wrapper');
echo $skin->make();
mysqli_close($db);
?>
I have read the previous questions with similar titles, none seem to provide me with an answer to this particular situation. I am receiving the error mentioned above on a specific functionality. I am not sure what is making it pop up. This is my first development so, unless it is specific to resolving the bug, please leave out the fact that I should be using PDO or mysqli.
this is the function i am trying to instantiate. when the sql command is executed in isolation, it returns the proper results.
public function search_for_candidates_by_technology($technology, $seniority){
$technology = $this->real_escape_string($technology);
$seniority = $this->real_escape_string($seniority);
$this->query("SELECT * FROM candidates WHERE technology LIKE ". $technology ." AND seniority LIKE ". $seniority ."");
}
The class to which the function belongs is tecnoDB
In the actual page where I am trying to instantiate, this is the code:
<form name="buscarBase" action="buscarCV.php" method="POST">Que technologia:<input type="text" name="usertech" value=""/><br/>
Que seniority:<input type="text" name="userSeniority" value="" />
<input type="submit" name="buscar" value="Buscar" />
<input type="submit" name="back" value="Panel de Control"/>
</form>
<table border="black">
<tr><th>Technology</th><th>Seniority</tr>
<?php
$search = tecnoDB::getInstance()->search_for_candidates_by_technology($_POST['usertech'], $_POST['userSeniority']);
while($searchResult = mysql_fetch_array($search)){
echo "<tr><td>" . htmlentities($searchResult['technology']) ."</td>";
echo "<td>". htmlentities($searchResult['seniority']) . "</td></tr>";
}
?>
</table>
The error is coming on the line: while($searchResult = mysql_fetch_array($search))....
That makes me think that the problem is that $search is not being created as an instance. Any ideas?
This is my first project and first question, please be gentle.
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
session_start();
if (!array_key_exists("user", $_SESSION)) {
header('Location: index.php');
exit;
}
require_once("Includes/tecnoDB.php");
$company_id = tecnoDB::getInstance()->get_company_id_by_name($_SESSION['user']);
if ($_SERVER['REQUEST_METHOD'] == "POST"){
if (array_key_exists("back", $_POST)) {
header('Location: companyControlPanel.php' );
exit;
}
else{
$service_user = tecnoDB::getInstance()->verify_service_status($company_id);
$access = $service_user->fetch_row();
if (array_key_exists ("buscar", $_POST)){
if($access[0] < 2 ){
header("Location: selectServicePackage.php" );
exit;
}
}
}
}
// put your code here ?>
<form name="buscarBase" action="buscarCV.php" method="POST">Que tecnologia:<input type="text" name="usertech" value=""/><br/>
Que seniority:<input type="text" name="userSeniority" value="" />
<input type="submit" name="buscar" value="Buscar" />
<input type="submit" name="back" value="Panel de Control"/>
</form>
<table border="black">
<tr><th>Technology</th><th>Seniority</tr>
<?php
$search = tecnoDB::getInstance()->search_for_candidates_by_technology($_POST['usertech'], $_POST['userSeniority']);
while($searchResult = mysql_fetch_array($search)){
echo "<tr><td>" . htmlentities($searchResult['technology']) ."</td>";
echo "<td>". htmlentities($searchResult['seniority']) . "</td></tr>";
}
?>
</table>
</body>
</html>
here goes the tecnoDB class:
class tecnoDB extends mysqli {
// single instance of self shared among all instances
private static $instance = null;
// db connection config vars
private $user = "phpuser";
private $pass = "phpuserpw";
private $dbName = "tecnosearch";
private $dbHost = "localhost";
//This method must be static, and must return an instance of the object if the object
//does not already exist.
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
// The clone and wakeup methods prevents external instantiation of copies of the Singleton class,
// thus eliminating the possibility of duplicate objects.
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
// private constructor
private function __construct() {
parent::__construct($this->dbHost, $this->user, $this->pass, $this->dbName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
parent::set_charset('utf-8');
}
public function get_company_id_by_name($name) {
$name = $this->real_escape_string($name);
$company = $this->query("SELECT id FROM company WHERE name = '"
. $name . "'");
if ($company->num_rows > 0){
$row = $company->fetch_row();
return $row[0];
} else
return null;
}
public function get_searches_by_company_id($company_id) {
return $this->query("SELECT id, description, technology FROM searches WHERE company_id=" . $company_id);
}
public function create_company ($name, $password){
$name = $this->real_escape_string($name);
$password = $this->real_escape_string($password);
$this->query("INSERT INTO company (name, password) VALUES ('" . $name . "', '" . $password . "')");
}
public function verify_company_credentials ($name, $password){
$name = $this->real_escape_string($name);
$password = $this->real_escape_string($password);
$result = $this->query("SELECT 1 FROM company
WHERE name = '" . $name . "' AND password = '" . $password . "'");
return $result->data_seek(0);
}
public function verify_service_status ($company_id){
$company_id = $this->real_escape_string($company_id);
$service = $this->query("SELECT service FROM company WHERE id = '". $company_id ."'");
return $service;
}
function insert_search($company_id, $description, $technology){
$description = $this->real_escape_string($description);
$technology = $this->real_escape_string($technology);
$this->query("INSERT INTO searches (company_id, description, technology)" .
" VALUES (" . $company_id . ", '" . $description . "','" .$technology. "')");
}
public function search_for_candidates_by_technology($technology, $seniority){
$technology = $this->real_escape_string($technology);
$seniority = $this->real_escape_string($seniority);
$this->query("SELECT * FROM candidates WHERE technology LIKE ". $technology ." AND seniority LIKE ". $seniority ."");
}
}
?>
I fixed the bug by setting the query in search_for_candidates_by_technology = $variable and returning the variable as well as in the actual page requiring the file where I have this function specified. I set the instance of the search_for_candidates_by_technology equal to $variable1 and created another object as the result of $variable1->get_array; . My error messages are now gone but the results are not appearing in the search. I am assuming because the action is on the same page and it causes the page to reload and when it reloads it essentially is resetting. I am looking at using an AJAX to show the results instead but I have never used asynchronous javascript and have only briefly seen XMLs. Any pointers or ideas that won't require AJAX?