Calling Method on Action Form PHP - php

I'm trying to make a login form using function, Im using class and function in different file. Here my code.
Login Form
<?php
require_once("controller/ED_Setting.php");
?>
<!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>Example Test</title>
</head>
<body>
<?php
if(isset($_REQUEST['failure']))
{
echo "User/Password Wrong";
}
?>
<form action=""<?php echo "/mvc/controller/login.php";?>"" method="post">
<label>Email:</label>
<input type="text" name="username" />
<br />
<label>Password:</label>
<input type="password" name="password" />
<br />
<input type="submit" name="cmdlogin" value="Login" />
</form>
</body>
</html>
And the login Function I Call
<?php
require_once("ED_Setting.php");
class login
{
function index()
{
$db = new ED_Setting();
$db->connect();
if(isset($_REQUEST['cmdlogin']))
{
$rs = $db->select("SELECT * FROM tbl_user where username = '".$_REQUEST['username']."' and password= '".($_REQUEST['password'])."'");
$res = $db->getResult();
if($res)
{
header('location: http://blup2h.rf.gd');
}
else
{
header('location: http://localhost/project/index.php?failure');
}
}
}
}
?>
And the Setting Connection is like this
<?php
class ED_Setting
{
private $db_host = "localhost"; // Change as required
private $db_user = "root"; // Change as required
private $db_pass = ""; // Change as required
private $db_name = "db_pembukuan"; // Change as required
private $con = false; // Check to see if the connection is active
private $result = array(); // Any results from a query will be stored here
// Function to make connection to database
public function connect(){
if(!$this->con){
$myconn = #mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name); // mysql_connect() with variables defined at the start of Database class
if($myconn){
return true;
}else{
array_push($this->result,mysqli_error());
return false; // Problem connecting return FALSE
}
}else{
return true; // Connection has already been made return TRUE
}
}
// Function to disconnect from the database
public function disconnect(){
// If there is a connection to the database
if($this->con){
// We have found a connection, try to close it
if(#mysql_close()){
// We have successfully closed the connection, set the connection variable to false
$this->con = false;
// Return true tjat we have closed the connection
return true;
}else{
// We could not close the connection, return false
return false;
}
}
}
public function select($sql){
$query = #mysqli_query($sql);
// $this->myQuery = $sql; // Pass back the SQL
if($query){
// If the query returns >= 1 assign the number of rows to numResults
$this->numResults = mysqli_num_rows($query);
// Loop through the query results by the number of rows returned
for($i = 0; $i < $this->numResults; $i++){
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])){
if(mysqli_num_rows($query) >= 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else{
$this->result = null;
}
}
}
}
return true; // Query was successful
}else{
array_push($this->result,mysqli_error());
return false; // No rows where returned
}
}
// Function to update and delete into the database
public function query($sql)
{
if($query = #mysql_query($sql)){
array_push($this->result,mysql_affected_rows());
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}
// Public function to return the data to the user
public function getResult(){
$val = $this->result;
$this->result = array();
return $val;
}
}
?>
But it did'nt work. Any answers please?

Probably the problem is "" using on form action attribute.
Use this line
<form action="<?php echo "/mvc/controller/login.php";?>" method="post">
Instead of
<form action=""<?php echo "/mvc/controller/login.php";?>"" method="post">

Related

Website crashes after clicking sign in --Uncaught Error: Call to a member function prepare() on null

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();
}
?>

How can I call this PDO function within another function using PHP?

When I try to call the function "getAverage" within "storeRating", I get a HTML 500 server error. If I comment out that function, everything works perfectly. How can I call function "getAverage" withing function "storeRating"? Even if I leave that function uncommented, the code still checks for a duplicate rating and posts the new rating to the "rating" table. Please look at my code at the getAverage function. I need to be able to update the rating in the "products" table with the average.
Here are my PHP classes.
DB Functions:
<?php
class DB_TestFunctions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
// Storing new rating
public function storeRating($pid, $userid, $ratingpnt) {
$stmt = $this->conn->prepare("INSERT INTO rating(ProductID,UserID,prod_rating) VALUES(?, ?, ?)");
$stmt->bind_param("sss", $pid, $userid, $ratingpnt);
$result = $stmt->execute();
$stmt->close();
getAverage($pid);
// check for successful store
/* if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM products WHERE pid = ?");
$stmt->bind_param("s", $pid);
$stmt->execute();
$rating = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $rating;
} else {
return false;
} */
}
/**
* Check if rating exists
*/
public function checkDuplicate($pid, $userid) {
$stmt = $this->conn->prepare("SELECT prod_rating from rating WHERE ProductID = ? AND UserID = ?");
$stmt->bind_param("ss", $pid, $userid);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
public function getAverage($pid){
$stmt = $this->conn->prepare("UPDATE products SET prod_rating = (SELECT AVG(prod_rating) FROM rating WHERE ProductID = ?) WHERE pid = ?");
$stmt->bind_param("s", $pid);
$stmt->execute();
$stmt->close();
}
public function getNewRating($pid){
$stmt = $this->conn->prepare("SELECT * FROM products WHERE pid = ?");
$stmt->bind_param("s", $pid);
$stmt->execute();
$rating = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $rating;
}
}
?>
postRate
<?php
require_once 'include/DB_TestFunctions.php';
$db = new DB_TestFunctions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['pid']) && isset($_POST['userid']) && isset($_POST['rating'])) {
// receiving the post params
$pid = $_POST['pid'];
$userid = $_POST['userid'];
$rating = $_POST['rating'];
// check if user already rated product
if ($db->checkDuplicate($pid, $userid)) {
// user already rated this product
$response["error"] = TRUE;
$response["error_msg"] = "Rating already exists." ;
echo json_encode($response);
} else {
$db->storeRating($pid, $userid, $rating);
// get new rating
$rating = $db->getNewRating($pid);
if ($rating) {
// Rating successful
$response["error"] = FALSE;
$response["prod_rating"] = $rating["prod_rating"];
echo json_encode($response);
} else {
// Rating failed
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in posting rating!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (pid, userid or rating) are missing!";
echo json_encode($response);
}
?>
<!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>Test Post Rating</title>
</head>
<body>
<h1>Add Comment</h1>
<form action="postRate.php" method="post">
Product ID:<br />
<input type="text" name="pid" placeholder="Product ID" />
<br /><br />
Userid:<br />
<input type="text" name="userid" placeholder="Username" />
<br /><br />
Rating:<br />
<input type="text" name="rating" placeholder="rating" />
<br /><br />
<input type="submit" value="Rate" />
</form>
</body>
</html>
The problem is that you are calling getAverage() that is a method of yor class.
So you need to $this, that is a reference to the current object, in order to call that function from your object.
Changing your code to :
$this->getAverage()
will solve your problem.
You need to call $this->getAverage()
Probably you should have a look at the PHP manual

Having Problems with PHP Mysql Sessions

Recently, I have been having a problem with my sessions, and corresponding session variables.
The problem, is that, when I POST sessions1.php, the session variable seems to work, and gets carried over into sessions2.php.
But, when the link to go to sessions3.php is clicked, the session variable doesn't seem to be set, when in sessions3.php. Thus, returning code from the "else" block, within the "if/else" conditional.
Something similar seems to be happening when I use either a database, or /tmp file setup, for storing data.
In the database example, the session is written to the sessions table. However, when I click the link, going from sessions2.php, which takes me to sessions3.php, the session variable doesn't seem to be set. And, when I click the "logout" button, within sessions3.php, the link takes me back to sessions1.php, which is what is supposed to happen. However, when I check the database (or at least refresh the sessions table), the session is not removed, or destroyed, according to what should be happening in line with the SessionHandler class.
Furthermore, still with the database example: when I submit sessions1.php, and am taken to sessions2.php, the right session row is created within the sessions table. However, when I click on the link that takes me to sessions3.php, another row is created, within the sessions table: this time, without any data, in the data column.
On the other hand, in an test without a database, thus, resorting to using the file-system instead: after submitting sessions1.php, the file appears in the /tmp directory. However, on inspection, that file remains empty. Please, also bear in mind that, when using a simple file-system example, the "SessionHandler", and db connection, code is not present within the files.
Any possible solutions?.
I am using PHP7, Apache 2.4, and MySQL 5.6.27. And, I am wondering whether my config settings (php.ini, and/or httpd) may have anything to do with the problem (since, even without a database, the interactions between sessions2.php, and sessions3.php produce somewhat similar results (session variable not set, by the time I get to sessions3.php)).
THE CODE:
sessions1.php(below)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<form method="post" action="sessions2.php">
<p>
<label for="name">Enter your first name: </label>
<input type="text" name="name" id="name">
</p>
<p>
<input type="submit" name="submit" value="Submit">
</p>
</form>
</body>
</html>
session2.php (below)
<?php
use SomeNamespace\Sessions\SessionHandler;
require_once('/databases/dbConnect.php');
require_once('/classes/Sessions/SessionHandler.php');
$handler = new SessionHandler($db);
session_set_save_handler($handler);
session_start();
if (isset($_POST['name'])) {
if (!empty($_POST['name'])) {
$_SESSION['name'] = htmlentities($_POST['name']);
} else {
$_SESSION['name'] = 'Nobody Here!';
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<p>Hello, <?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
} else {
echo 'stranger';
}
?>.</p>
<p>Go to page 3</p>
</body>
</html>
session3.php (below)
<?php
use SomeNamespace\Sessions\SessionHandler;
require_once('/databases/dbConnect.php');
require_once('/classes/Sessions/SessionHandler.php');
$handler = new SessionHandler($db);
session_set_save_handler($handler);
session_start();
if (isset($_POST['logout'])) {
$_SESSION = [];
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 86400, $params['path'],
$params['domain'], $params['secure'], $params['httponly']);
session_destroy();
header('Location: sessions1.php');
exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<p>Hello<?php
if (isset($_SESSION['name'])) {
echo ' again, ' . $_SESSION['name'];
} else {
echo ', Nobody!';
}
?>.</p>
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<p><input type="submit" name="logout" value="Log Out"></p>
</form>
</body>
</html>
SessionHandler.php (below) The session handler class.
namespace SomeNamespace\Sessions;
class SessionHandler implements \SessionHandlerInterface
{
protected $db;
protected $useTransactions;
protected $expiry;
protected $table_sess = 'sessions';
protected $col_sid = 'sessionID';
protected $col_expiry = 'expiry';
protected $col_data = 'data';
protected $unlockStatements = [];
protected $collectGarbage = false;
public function __construct(\PDO $db, $useTransactions = true)
{
$this->db = $db;
if ($this->db->getAttribute(\PDO::ATTR_ERRMODE) !== \PDO::ERRMODE_EXCEPTION) {
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
$this->useTransactions = $useTransactions;
$this->expiry = time() + (int) ini_get('session.gc_maxlifetime');
}
public function open($save_path, $name)
{
return true;
}
public function read($session_id)
{
try {
if ($this->useTransactions) {
$this->db->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
$this->db->beginTransaction();
} else {
$this->unlockStatements[] = $this->getLock($session_id);
}
$sql = "SELECT $this->col_expiry, $this->col_data
FROM $this->table_sess WHERE $this->col_sid = :sessionID";
if ($this->useTransactions) {
$sql .= ' FOR UPDATE';
}
$selectStmt = $this->db->prepare($sql);
$selectStmt->bindParam(':sessionID', $session_id);
$selectStmt->execute();
$results = $selectStmt->fetch(\PDO::FETCH_ASSOC);
if ($results) {
if ($results[$this->col_expiry] < time()) {
return '';
}
return $results[$this->col_data];
}
if ($this->useTransactions) {
$this->initializeRecord($selectStmt);
}
return '';
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollBack();
}
throw $e;
}
}
public function write($session_id, $data)
{
try {
$sql = "INSERT INTO $this->table_sess ($this->col_sid,
$this->col_expiry, $this->col_data)
VALUES (:sessionID, :expiry, :data)
ON DUPLICATE KEY UPDATE
$this->col_expiry = :expiry,
$this->col_data = :data";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);
$stmt->bindParam(':data', $data);
$stmt->bindParam(':sessionID', $session_id);
$stmt->execute();
return true;
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollback();
}
throw $e;
}
}
public function close()
{
if ($this->db->inTransaction()) {
$this->db->commit();
} elseif ($this->unlockStatements) {
while ($unlockStmt = array_shift($this->unlockStatements)) {
$unlockStmt->execute();
}
}
if ($this->collectGarbage) {
$sql = "DELETE FROM $this->table_sess WHERE $this->col_expiry < :time";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->execute();
$this->collectGarbage = false;
}
return true;
}
public function destroy($session_id)
{
$sql = "DELETE FROM $this->table_sess WHERE $this->col_sid = :sessionID";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':sessionID', $session_id);
$stmt->execute();
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollBack();
}
throw $e;
}
return true;
}
public function gc($maxlifetime)
{
$this->collectGarbage = true;
return true;
}
protected function getLock($session_id)
{
$stmt = $this->db->prepare('SELECT GET_LOCK(:key, 50)');
$stmt->bindValue(':key', $session_id);
$stmt->execute();
$releaseStmt = $this->db->prepare('DO RELEASE_LOCK(:key)');
$releaseStmt->bindValue(':key', $session_id);
return $releaseStmt;
}
protected function initializeRecord(\PDOStatement $selectStmt)
{
try {
$sql = "INSERT INTO $this->table_sess ($this->col_sid, $this->col_expiry, $this->col_data)
VALUES (:sessionID, :expiry, :data)";
$insertStmt = $this->db->prepare($sql);
$insertStmt->bindParam(':sessionID', $session_id);
$insertStmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);
$insertStmt->bindValue(':data', '');
$insertStmt->execute();
return '';
} catch (\PDOException $e) {
if (0 === strpos($e->getCode(), '23')) {
$selectStmt->execute();
$results = $selectStmt->fetch(\PDO::FETCH_ASSOC);
if ($results) {
return $results[$this->col_data];
}
return '';
}
if ($this->db->inTransaction()) {
$this->db->rollback();
}
throw $e;
}
}
}

Calling functions which are defined in other php file wont work the way I want

I have followin PHP code, it is where I defined my functions:
<?php
function emaili_pikkus($email){
if (strlen($email)>45){
echo 'e-mail ei tohi olla pikem kui 45 tähemärki';
}
else{
$emaili_pikkus=True;
}
}
function parooli_pikkus($parool)
{
$pikkus = strlen($parool);
if ($pikkus<6){
echo "Parool peab olema vähemalt 6 tähemärki pikk";
}
else {
$parooli_pikkus=True;
}
}
function varasem_olemasolu($email)
{
if(!empty($_POST['email']))
{
$query = mysql_query("SELECT * FROM kasutajad WHERE e_mail = '$email'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
$varasem_olemasolu=True;
}
else
{
echo "Selle e-mailiga on kasutaja juba registreeritud.";
}
}
}
function paroolide_kattuvus($parool, $parool_uuesti)
{
if($parool==$parool_uuesti)
{
$paroolide_kattuvus=True;
}
else{
echo "Paroolid ei kattu.";
}
}
function NewUser()
{
global $sql;
if (mysql_query( $sql))
{
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Praks/templates/registreeritud.php'>";
}
}
?>
Then I have other PHP code where I call necessary functions(They are seperated, because I want to use my functions in other applications too):
<meta charset="UTF-8">
<?php
include_once 'init/init.funcs.php';
$email = mysql_real_escape_string($_POST['email']);
$eesnimi = mysql_real_escape_string($_POST['eesnimi']);
$perekonnanimi = mysql_real_escape_string($_POST['perekonnanimi']);
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
$salt = rand(10000,99999);
$hashed_pwd = sha1($parool.$salt);
$sql="INSERT INTO kasutajad (e_mail, eesnimi, perenimi, parool, salt ) VALUES ('$email','$eesnimi','$perekonnanimi','$hashed_pwd','$salt')";
emaili_pikkus($email);
if ($emaili_pikkus=True){
parooli_pikkus($parool);
}
if ($parooli_pikkus=True){
varasem_olemasolu($email);
}
if ($varasem_olemasolu=True){
paroolide_kattuvus($parool, $parool_uuesti);
}
if ($paroolide_kattuvus=True){
NewUser();
}
?>
And then I have my HTML code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>Registreerimine</title>
</head>
<body>
<strong>Registreerimiseks täida järgnevad väljad: </strong><br>
<br>
<form method="POST" action="registreerimine4.php">
<table>
<tr><td>Sinu Tieto e-maili aadress: </td><td><input type="text" name="email"></td></tr>
<tr><td>Eesnimi: </td><td><input type="text" name="eesnimi"></td></tr>
<tr><td>Perekonnanimi: </td><td><input type="text" name="perekonnanimi"></td></tr>
<tr><td>Parool: </td><td><input type="text" name="parool"></td></tr>
<tr><td>Parool uuesti: </td><td><input type="text" name="parooluuesti"></td></tr>
</table>
<br>
<input type="submit" value="Registreeri" name="Registreeri">
</form>
</body>
</html>
init.funcs.php looks like that:
<?php
session_start ();
$db = mysql_connect ( 'localhost', 'root', 'aaaa' );
if (! $db) {
header ( "location: /" );
die ();
} else {
mysql_select_db ( 'ta2014' );
}
include_once 'functions/user.funcs.php';
include_once 'functions/survey.funcs.php';
?>
It all together should be a registration form and it worked before I made few changes. Before those changes I had my functions defined to work only for this registration form and they had no parameters needed. Also they were nested in each other. My question is how should I write my second PHP code, so it all would work. Right now it creates new user even if some previous condition are not True. It is a long question and I would be very thankful if someone answers me.
You have a lot of errors in your code:
Your functions aren't returning any value. Variables intitalized inside the function will not be available outside it. The best way is to return a boolean value and check that outside
The function definition:
function some_func($param1, $param2) {
if (some_condition) {
// If everything okay, return TRUE
return TRUE;
} else {
// It's not gonna work with this, so return FALSE
return FALSE;
}
}
Checking the return value:
if (some_func($foo, $bar)) {
// some_func returned TRUE, do further processing
}
With if($var = True), you're not actually checking if a variable is true or not. You're assigning it the boolean value True. You need to write if($var == True instead.
You're using the deprecated mysql_* functions. They're deprecated. Use MySQLi or PDO instead.

PHP logging out

I am doing the Lynda.com learning PHP 2 videos and have run into a problem, in that the instructor seems to have neglected to tell us one of the steps he does in the video. I have uploaded the relevant video here http://www.youtube.com/watch?v=fFKgAa7RAjo but will also describe the problem. At 6:40 of the video, after logging in to our application, he arrives at public/admin/index.php which has two links on it. one link allows him to "view log file" which takes him to public/admin/logfile.php and the other link allows him to log out. He doesn't tell us how to make these links. I can obviously make a link to view logfile
View Logfile
but I don't know how to make the link that will log me out, because that will obviously involve some PHP.
I have included below the login.php file, the index.php file (it's redirected to index.php after logging in) and the functions.php file. Do you know how I would logout from this?
This is the login.php file
<?php
require_once("../../includes/initialize.php");
if($session->is_logged_in()){
redirect_to("index.php");
}
//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} logged in.");
redirect_to("index.php");
} else {
//username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else {//Form has not been submitted.
$username = "";
$password = "";
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Staff Login</h2>
<?php echo output_message($message); ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="<?php
echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="<?php
echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="login" />
</td>
</tr>
</table>
</form>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Functions.php
<?php
function strip_zeros_from_date( $marked_string=""){
//first remove the marked zeros
$no_zeros = str_replace('*0', '', $marked_string);
//then remove any remaining marks
$cleaned_string = str_replace('*', '', $no_zeros);
return $cleaned_string;
}
function redirect_to( $location= NULL) {
if($location != NULL) {
header("Location: {$location}");
exit;
}
}
function output_message($message=""){
if (!empty($message)) {
return "<p class=\"message\">{$message}</p>";
} else {
return "";
}
}
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = LIB_PATH.DS."{$class_name}.php";
if(file_exists($path)){
require_once($path);
} else {
die("The file {$class_name}.php could not be found.");
}
}
function include_layout_template($template=""){
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
function log_action($action, $message=""){
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
$new = file_exists($logfile) ? false : true;
if($handle = fopen($logfile, 'a')) { //apppend
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
$content = "{$timestamp} | {$action}: {$message}\n";
fwrite($handle,$content);
fclose($handle);
if($new) {chmod($logfile, 0755); }
} else {
echo "Could not open log file for writing.";
}
}
?>
Index.php
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Menu</h2>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Update
Initialize.php
<?php
//Directory_separator is a PHP pre-defined constant
// (\ for windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null :
define('SITE_ROOT', DS.'hsphere'.DS.'local'.DS.'home'.DS.'c263430'.DS.'quoralist.com');
// define('SITE_ROOT', realpath(dirname(__FILE__).'/../'));
//echo SITE_ROOT."<br/>";
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
// die(LIB_PATH);
//echo LIB_PATH."<br/>";
require_once(LIB_PATH.DS."config.php");
require_once(LIB_PATH.DS."functions.php");
require_once(LIB_PATH.DS."session.php");
require_once(LIB_PATH.DS."database.php");
require_once(LIB_PATH.DS."database_object.php");
require_once(LIB_PATH.DS."user.php");
//echo("You die here");
?>
User.php
<?php
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject{
protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public static function authenticate($username="",$password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
//common database methods
public static function find_all(){
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];
foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>
Session.php
<?php
class Session {
private $logged_in=false;
public $user_id;
function __construct() {
session_start();
$this->check_login();
if($this->logged_in){
//actions to take right away if user is logged in
} else {
//actions to take right away if user is not logged in
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function login($user) {
//database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function logout(){
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login(){
if(isset($_SESSION['user_id'])){
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
?>
<?php
session_start();
session_destroy();
?>
That should destroy all variables stored in the session. It is really primitive logging out, but it should work. After you do that just redirect to "index.php" or whatever page you want.

Categories