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 am quite new to php and payment integration.
But I have successfully integrated the payment system but the problem I am facing is how to store those confirmation values in database.
Here is my response.php code where the confirmation response from gateway is sent back to response page. With the code I am able to get the confirmation status output, problem is how to store it in db.
[this is the output][1]
<?php
include 'header.php';
include 'dbconnect.php';
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
?>
<html>
<head></head>
<body>
<?php
// following files need to be included
require_once("./paytm/PaytmKit/lib/config_paytm.php");
require_once("./paytm/PaytmKit/lib/encdec_paytm.php");
$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";
$paramList = $_POST;
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg
//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your application’s MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.
if($isValidChecksum == "TRUE") {
echo "<b>Checksum matched and following are the transaction details:</b>" . "<br/>";
if ($_POST["STATUS"] == "TXN_SUCCESS") {
echo "<b>Transaction status is success</b>" . "<br/>";
//Process your transaction here as success transaction.
//Verify amount & order id received from Payment gateway with your application's order id and amount.
}
else {
echo "<b>Transaction status is failure</b>" . "<br/>";
}
if (isset($_POST) && count($_POST)>0 )
{
//here iam trying to store it but it is not working as shows undefined functions
foreach($_POST as $paramName => $paramValue) {
echo "<br/>" . $paramName . " = " . $paramValue;
$sql = "INSERT INTO txn_details (MID, ORDERID, TXNAMOUNT, CURRENCY, TXNID, BANKTXNID, STATUS, RESPCODE, RESPMSG, TXNDATE, GATEWAYNAME, BANKNAME, PAYMENTMODE)
VALUES ('$MID', '$ORDERID', '$TXNAMOUNT', '$CURRENCY', '$TXNID', '$BANKTXNID', '$STATUS', '$RESPCODE', '$RESPMSG', '$TXNDATE', '$GATEWAYNAME', '$BANKNAME', '$PAYMENTMODE')";
$result = $conn->query($sql);
}
}
}
else {
echo "<b>Checksum mismatched.</b>";
//Process transaction as suspicious.
}
include 'footer.php';
?>
</body>
</html>
[1]: https://i.stack.imgur.com/DnNRg.png
These is the pgredirect.php where i Mid AND OTHERS ARE defined.
<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
$checkSum = "";
$paramList = array();
$ORDER_ID = $_POST["ORDER_ID"];
$CUST_ID = $_POST["CUST_ID"];
$INDUSTRY_TYPE_ID = $_POST["INDUSTRY_TYPE_ID"];
$CHANNEL_ID = $_POST["CHANNEL_ID"];
$TXN_AMOUNT = $_POST["TXN_AMOUNT"];
$EMAIL = $_POST["EMAIL"];
$MSISDN = $_POST["MSISDN"];
// Create an array having all required parameters for creating checksum.
$paramList["MID"] = PAYTM_MERCHANT_MID;
$paramList["ORDER_ID"] = $ORDER_ID;
$paramList["CUST_ID"] = $CUST_ID;
$paramList["INDUSTRY_TYPE_ID"] = $INDUSTRY_TYPE_ID;
$paramList["CHANNEL_ID"] = $CHANNEL_ID;
$paramList["TXN_AMOUNT"] = $TXN_AMOUNT;
$paramList["WEBSITE"] = PAYTM_MERCHANT_WEBSITE;
$paramList["CALLBACK_URL"] = "http://localhost/wd/response.php";
$paramList["MSISDN"] = $MSISDN; //Mobile number of customer
$paramList["EMAIL"] = $EMAIL; //Email ID of customer
$paramList["VERIFIED_BY"] = "EMAIL"; //
$paramList["IS_USER_VERIFIED"] = "YES"; //
//Here checksum string will return by getChecksumFromArray() function.
$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
?>
<html>
<head>
<title>Merchant Check Out Page</title>
</head>
<body>
<center><h1>Please do not refresh this page...</h1></center>
<form method="post" action="<?php echo PAYTM_TXN_URL ?>" name="f1">
<table border="1">
<tbody>
<?php
foreach($paramList as $name => $value) {
echo '<input type="hidden" name="' . $name .'" value="' . $value . '">';
}
?>
<input type="hidden" name="CHECKSUMHASH" value="<?php echo $checkSum ?>">
</tbody>
</table>
<script type="text/javascript">
document.f1.submit();
</script>
</form>
</body>
</html>
You have to define all variables value and write INSERT statement out side of foreach loop.
your insert statement should look like.
if (isset($_POST) && count($_POST)>0 )
{ //here iam trying to store it but it is not working as shows undefined functions
$sql = "INSERT INTO txn_details (MID, ORDERID, TXNAMOUNT, CURRENCY, TXNID, BANKTXNID, STATUS, RESPCODE, RESPMSG, TXNDATE, GATEWAYNAME, BANKNAME, PAYMENTMODE)
VALUES ('".$_POST['MID']."', '".$_POST['ORDERID']."', '".$_POST['TXNAMOUNT'].", '".$_POST['CURRENCY']."', '"..$_POST['TXNID']."', '"..$_POST['BANKTXNID']."', '".$_POST['STATUS']."', '".$_POST['RESPCODE']."', '".$_POST['RESPMSG']."', '".$_POST['TXNDATE']."', '".$_POST['GATEWAYNAME']."', '".$_POST['BANKNAME']."', '".$_POST['PAYMENTMODE']."')";
$result = $conn->query($sql);
}
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.
Hi I am trying to develop a login sistem but I seem to be getting an error on a condition.This is my code:
//header.php
if($_SESSION['signed_in']){
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else{
echo 'Sign in or create an account.';
}
//Signin.php
if(mysql_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
The error is pointed on the first condition : if($_SESSION['signed_in']) and it says that:
Notice: Undefined variable: _SESSION in C:\xampp\htdocs\Tutorials\Forum\header.php on line 21
How can I corect this?
EDIT:session_start() is included at the top of the header.php file in the doctype and header.php is included in Signin.php
Full Code:
header.php
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" lang="nl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="A short description." />
<meta name="keywords" content="put, keywords, here" />
<title>PHP-MySQL forum</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<h1>My forum</h1>
<div id="wrapper">
<div id="menu">
<a class="item" href="/forum/index.php">Home</a> -
<a class="item" href="/forum/create_topic.php">Create a topic</a> -
<a class="item" href="/forum/create_cat.php">Create a category</a>
<div id="userbar">
<div id="userbar">
<?php
if($_SESSION['signed_in']){
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else{
echo 'Sign in or create an account.';
}
?>
</div>
</div>
<div id="content">
Signin.php
<?php
//signin.php
include 'conn.php';
include 'header.php';
echo '<h3>Sign in</h3>';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
Username: <input type="text" name="user_name" />
Password: <input type="password" name="user_pass">
<input type="submit" value="Sign in" />
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Varify if the data is correct and return the correct response
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysql_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
}
}
}
}
include 'footer.php';
?>
Before you store something into the session, the variable $_SESSION['signed_in'] will be empty. The warning occurs because you ask for this value, but nothing is inside.
if (isset($_SESSION['signed_in']) && $_SESSION['signed_in'])
{
}
To avoid the warning, you should first check if the variable exists, then you can read from it. Of course this is a bit cumbersome, so most developers create a function just for reading safely from an array.
Edit:
Actually the problem above would lead to another message...
Notice: Undefined index: ...
...so it is as Mob said, the variable $_SESSION doesn't exist at all, because no session was started. I will let this answer stay, because this will be the next pitfall.
There's no session_start(); That's the reason, you have to always declare that befoe using sessions in PHP.