Getting php fatal error
PHP Fatal error: Cannot redeclare page_protect() (previously declared
on line 48) on line 103
my code looks like that. What's wrong? Please search for "line 48" and "line 103" in the code
<?php
/*db connection*/
$db=...;
/*ip detection*/
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
//shared client check
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//proxy check
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
$ip = sprintf('%u', ip2long($ip));
/* Registration Type (Automatic or Manual)
1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1; // set 0 or 1
define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password
//define ("ADMIN_NAME", "admin"); // sp
/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);
function page_protect() {
/*line 48*/session_start();
global $db;
/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
logout();
exit;
}
}
// before we allow sessions, we need to check authentication key - ckey and ctime stored in database
/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['id']) && !isset($_SESSION['login']) )
{
if(isset($_COOKIE['id']) && isset($_COOKIE['key'])){
/* we double check cookie expiry time against stored in database */
$cookie_user_id = filter($_COOKIE['id']);
$rs_ctime = $db -> query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die($db->error);
list($ckey,$ctime) = $rs_ctime->fetch_row();
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {
logout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/
if( !empty($ckey) && is_numeric($_COOKIE['id']) && isUserID($_COOKIE['login']) && $_COOKIE['key'] == sha1($ckey) ) {
session_regenerate_id(); //against session fixation attacks.
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['login'] = $_COOKIE['login'];
/* query user level from database instead of storing in cookies */
$level=$db->query("select user_level from users where id='$_SESSION[id]'");
$_SESSION['level'] = $level->fetch_row();
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
} else {
logout();
}
} else {
if($page!='main'){
header("Location: login.php");
exit();
}
}
}
/*line 103*/ }
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
global $db;
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = $db->real_escape_string($data);
return $data;
}
function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}
function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}
function ChopStr($str, $len)
{
if (strlen($str) < $len)
return $str;
$str = substr($str,0,$len);
if ($spc_pos = strrpos($str," "))
$str = substr($str,0,$spc_pos);
return $str . "...";
}
function isEmail($email){
return preg_match('/^\S+#[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}
function isUserID($login)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $login)) {
return true;
} else {
return false;
}
}
function isURL($url)
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
return true;
} else {
return false;
}
}
function checkPwd($x,$y)
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }
if (strcmp($x,$y) != 0) {
return false;
}
return true;
}
function GenPwd($length = 7)
{
$password = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function GenKey($length = 7)
{
$password = "";
$possible = "0123456789abcdefghijkmnopqrstuvwxyz";
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function logout()
{
global $db;
session_start();
if(isset($_SESSION['id']) || isset($_COOKIE['id'])) {
$db->query("update `users`
set `ckey`= '', `ctime`= ''
where `id`='$_SESSION[id]' OR `id` = '$_COOKIE[id]'") or die($db->error);
}
/************ Delete the sessions****************/
unset($_SESSION['id']);
unset($_SESSION['login']);
unset($_SESSION['level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy();
/* Delete the cookies*******************/
setcookie("id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("login", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
$link = $_SERVER["PHP_SELF"];
header("Location: http://localhost/");
}
// Password and salt generation
function PwdHash($pwd, $salt = null)
{
if ($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else {
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($pwd . $salt);
}
function checkAdmin() {
if($_SESSION['level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}
}
?>
The function page_protect() is declared twice. Either this function name is already in use in another file in your application, or your includeing this file twice.
It means there is already a function page_protect when you try to define that function. That is, you have two functions page_protect, which is an error. May you are including this file twice.
Related
I really need you kind help here, can someone be kind enough to show me how can i do a Ip check in the following codes? as of now it checks username and password thats ok but i wish to assign IP of users assigned to their tables so while doing a login check it also checks whether the users current ip matches with the one stored in database?
its not like i haven't tried, I have been trying but not getting any output after adding the IP field it stops logging me in
here is my form section from login.php
<p><input type="text" class="form-control" name="username" value="" placeholder="Username" required /></p>
<p><input type="password" class="form-control" name="password" value="" placeholder="Your Password" /></p>
<p><input type="text" class="form-control" name="IP" value="<?php echo get_client_ip(); ?>" readonly/></p>
here is the login.php validation
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: memberpage.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}
and here is the user.php codes i guess this is where the ip needs to be checked?
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password, username, memberID, IP FROM members WHERE username = :username AND IP = :IP ');
$stmt->execute(array('username' => $username, 'IP ' => $ip));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
return true;
}
}
}
and here is the password.php codes
if (!defined('PASSWORD_DEFAULT')) {
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
}
Class Password {
public function __construct() {}
function password_hash($password, $algo, array $options = array()) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null;
}
if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
return null;
}
if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
return null;
}
switch ($algo) {
case PASSWORD_BCRYPT :
// Note that this is a C constant, but not exposed to PHP, so we don't define it here.
$cost = 10;
if (isset($options['cost'])) {
$cost = $options['cost'];
if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null;
}
}
// The length of salt to generate
$raw_salt_len = 16;
// The length required in the final serialization
$required_salt_len = 22;
$hash_format = sprintf("$2y$%02d$", $cost);
break;
default :
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
return null;
}
if (isset($options['salt'])) {
switch (gettype($options['salt'])) {
case 'NULL' :
case 'boolean' :
case 'integer' :
case 'double' :
case 'string' :
$salt = (string)$options['salt'];
break;
case 'object' :
if (method_exists($options['salt'], '__tostring')) {
$salt = (string)$options['salt'];
break;
}
case 'array' :
case 'resource' :
default :
trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
return null;
}
if (strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING);
return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt = str_replace('+', '.', base64_encode($salt));
}
} else {
$buffer = '';
$buffer_valid = false;
if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
$buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$buffer = openssl_random_pseudo_bytes($raw_salt_len);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && is_readable('/dev/urandom')) {
$f = fopen('/dev/urandom', 'r');
$read = strlen($buffer);
while ($read < $raw_salt_len) {
$buffer .= fread($f, $raw_salt_len - $read);
$read = strlen($buffer);
}
fclose($f);
if ($read >= $raw_salt_len) {
$buffer_valid = true;
}
}
if (!$buffer_valid || strlen($buffer) < $raw_salt_len) {
$bl = strlen($buffer);
for ($i = 0; $i < $raw_salt_len; $i++) {
if ($i < $bl) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else {
$buffer .= chr(mt_rand(0, 255));
}
}
}
$salt = str_replace('+', '.', base64_encode($buffer));
}
$salt = substr($salt, 0, $required_salt_len);
$hash = $hash_format . $salt;
$ret = crypt($password, $hash);
if (!is_string($ret) || strlen($ret) <= 13) {
return false;
}
return $ret;
}
function password_get_info($hash) {
$return = array('algo' => 0, 'algoName' => 'unknown', 'options' => array(), );
if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) {
$return['algo'] = PASSWORD_BCRYPT;
$return['algoName'] = 'bcrypt';
list($cost) = sscanf($hash, "$2y$%d$");
$return['options']['cost'] = $cost;
}
return $return;
}
function password_needs_rehash($hash, $algo, array $options = array()) {
$info = password_get_info($hash);
if ($info['algo'] != $algo) {
return true;
}
switch ($algo) {
case PASSWORD_BCRYPT :
$cost = isset($options['cost']) ? $options['cost'] : 10;
if ($cost != $info['options']['cost']) {
return true;
}
break;
}
return false;
}
public function password_verify($password, $hash) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false;
}
$ret = crypt($password, $hash);
if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) {
return false;
}
$status = 0;
for ($i = 0; $i < strlen($ret); $i++) {
$status |= (ord($ret[$i]) ^ ord($hash[$i]));
}
return $status === 0;
}
}
Really hoping someone you experts could help me out in here, will be really greatful.
Thanks a ton in advance
I keep getting this error when I try to log in to my site and I have no idea how to fix it. What is missing? Someone edit this thing for me!
PHP Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in client_config.php on line 147
I have tried almost all other solutions posted on this forum but none seems to work for me. Actually almost all other errors are coming from this same file so anyone who can spot any errors in the code can help. Any guidance will be highly appreciated. I am currently logged out of my site until this is fixed.
PS. I have no programming knowledge.
<?php
error_reporting( error_reporting() & ~E_NOTICE );
$GLOBALdatabase_cf = array();
$GLOBALdatabase_cf['host'] = 'localhost';
$GLOBALdatabase_cf['username'] = 'myusername';
$GLOBALdatabase_cf['password'] = 'password';
$GLOBALdatabase_cf['database'] = 'database';
$GLOBALdatabase_cf['prefix'] = 'mu_';
$GLOBALdatabase_cf['cookieName'] = 'cookiename';
$GLOBALdatabase_cf['cookieKey'] = 'cookiekey';
$connect = #mysql_connect($GLOBALdatabase_cf['host'] , $GLOBALdatabase_cf['username'] , $GLOBALdatabase_cf['password']);
if (!$connect)
{
die ("Couldn't make connection.");
}
#mysql_select_db($GLOBALdatabase_cf['database'], $connect) or die ("Couldn't select database");
list($admin_domain_name) = mysql_fetch_row(mysql_query("select domain_name from system where site_type = 'backend'"));
$domain_name = stripit($_SERVER['HTTP_HOST']);
$url = $_SERVER['REQUEST_URI'];
$urlParse = parse_url($url);
$path = explode('/',$urlParse ['path']);
$site_URL= get_base_url($host_this);
$siteUrl = stripit($site_URL);
if (!defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
require_once(ABSPATH . 'wp-config.php');
require_once(ABSPATH . 'wp-settings.php');
if (!defined('ROOT_DIR_C') )
define('ROOT_DIR_C', dirname(__FILE__) . '/');
if (!defined('BASE_URL_C') )
define('BASE_URL_C', substr($_SERVER['PHP_SELF'], 0, - (strlen($_SERVER['SCRIPT_FILENAME']) - strlen(ROOT_DIR_C))));
define('DOWNLOAD_URL', BASE_URL_C . 'orders/download?f=');
$upload_download_dir = '/home/essaycoachonline/crownresearchcenter.com/uploads/';
list($curr_symbol) = mysql_fetch_row(mysql_query("select sys_curr from settings")); // currency symbol
list($admin_site_email) = mysql_fetch_row(mysql_query("select site_email from system where site_type = 'backend'"));
list($admin_site_name) = mysql_fetch_row(mysql_query("select site_name from system where site_type = 'backend'"));
list($admin_site_base_price) = mysql_fetch_row(mysql_query("select base_price from system where site_type = 'backend'"));
$sql_site_settings = "select * from system where url = '$siteUrl'";
$result_site_settings = mysql_query($sql_site_settings) or die(mysql_error());
$row_site_settings = mysql_fetch_array($result_site_settings);
list($site_support) = mysql_fetch_row(mysql_query("select email from mu_members where role = 'sub_admin'"));
$site_email= $row_site_settings['site_email'];
$admin_email =$row_site_settings['admin_email'];
$basePrice =$row_site_settings['base_price'];
$price_override = $row_site_settings['price_override'];
define ("SITE_HOST_NAME", $domain_name);
define ("SITE_NAME", $row_site_settings['site_name']);
$academicEmail= $admin_site_email;
define ("ACADEMIC_SITE_NAME",$admin_site_name);
$user_registration = 1; // set 0 or 1
$writer_registration = 0;
define("COOKIE_TIME_OUT", 1); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password
/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("WRITER_LEVEL", 3);
define ("CLIENT_LEVEL", 2);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);
function page_protect() {
if(!isset($_SESSION))
{
session_start();
date_default_timezone_set('Africa/Nairobi');// Africa/Nairobi
}
global $GLOBALdatabase_cf;
/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
logout();
exit;
}
}
// before we allow sessions, we need to check authentication key - ckey and ctime stored in database
/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['id']) && !isset($_SESSION['username']) )
{
if(isset($_COOKIE['id']) && isset($_COOKIE['user_key'])){
/* we double check cookie expiry time against stored in database */
$cookie_user_id = filter($_COOKIE['id']);
$rs_ctime = mysql_query("select `ckey`,`ctime` from `mu_members` where `id` ='$cookie_user_id'") or die(mysql_error());
list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {
logout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/
if( !empty($ckey) && is_numeric($_COOKIE['id']) && isUserID($_COOKIE['username']) && $_COOKIE['user_key'] == sha1($ckey) ) {
session_regenerate_id(); //against session fixation attacks.
date_default_timezone_set('Africa/Nairobi');// Africa/Nairobi
$_SESSION['id'] = $_COOKIE['id'] ;
$_SESSION['username'] = $_COOKIE['username'];
/* query user level from database instead of storing in cookies */
list($user_level) = mysql_fetch_row(mysql_query("select user_level from mu_members where id='$_SESSION[id]'"));
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
} else {
logout();
}
} else {
header("Location: ../login/");
exit();
}
}
}
function filter($data) {
if(is_scalar($data))
{
$data = trim(htmlentities(strip_tags($data)));
}
if (get_magic_quotes_gpc())
$data = stripslashes($data);
if(is_scalar($data))
{
$data = mysql_real_escape_string($data); **--->Line 147**
}
return $data;
}
function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}
function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}
function ChopStr($str, $len)
{
if (strlen($str) < $len)
return $str;
$str = substr($str,0,$len);
if ($spc_pos = strrpos($str," "))
$str = substr($str,0,$spc_pos);
return $str . "...";
}
function isNum($price){
return preg_match("/[^0-9]/", "",$price)? TRUE : FALSE;
}
function isEmail($email){
return preg_match('/^\S+#[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}
function isUserID($username)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
return true;
} else {
return false;
}
}
function isURL($url)
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
return true;
} else {
return false;
}
}
function checkPwd($x,$y)
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }
if (strcmp($x,$y) != 0) {
return false;
}
return true;
}
function GenPwd($length = 7)
{
$password = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function GenKey($length = 7)
{
$password = "";
$possible = "0123456789abcdefghijkmnopqrstuvwxyz";
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function rand_my_string( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
function logout()
{
global $GLOBALdatabase_cf;
session_start();
if(isset($_SESSION['id']) || isset($_COOKIE['id'])) {
mysql_query("update `mu_members`
set `ckey`= '', `ctime`= ''
where `id`='$_SESSION[id]' OR `id` = '$_COOKIE[id]'") or die(mysql_error());
}
/************ Delete the sessions****************/
unset($_SESSION['id']);
unset($_SESSION['username']);
unset($_SESSION['email']);
unset($_SESSION['user_level']);
unset($_SESSION['writer']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy();
/* Delete the cookies*******************/
setcookie("id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("username", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
$lg= 'You are now logged out';
header("Location: login/?sign=$lg");
}
// Password and salt generation
function PwdHash($pwd, $salt = null)
{
if ($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, 9);
}
else {
$salt = substr($salt, 0, 9);
}
return $salt . sha1($pwd . $salt);
}
function checkAdmin() { //admin
if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}
}
function checkWriter() { //writer
if($_SESSION['user_level'] == WRITER_LEVEL) {
return 1;
} else { return 0 ;
}
}
function checkClient() { //client
if($_SESSION['user_level'] == CLIENT_LEVEL) {
return 1;
} else { return 0 ;
}
}
function ShortenText($text) {
$chars = 30;
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' ')).'.....';
return $text;
}
//
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Set default diff to 0
$diffs[$interval] = 0;
// Create temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
$time1 = $ttime;
$diffs[$interval]++;
// Create new temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
}
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
//
function get_base_url()
{
/* protocol the website is using */
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"], 0, 5)) == 'https' ? 'https://' : 'http://';
/* returns /myproject/index.php */
$path = $_SERVER['PHP_SELF'];
$path_parts = pathinfo($path);
$directory = $path_parts['dirname'];
$directory = ($directory == "/") ? "" : $directory;
/* Returns localhost OR mysite.com */
$host_this = $_SERVER['HTTP_HOST'];
return $protocol . $host_this ;
}
function stripit ( $url ) {
$url = trim($url);
$url = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url);
$url = preg_replace("/\/.*$/is" , "" ,$url);
return $url;
}
?>
You mentioned in a comment that you are using PHP 7.2, so you will have problems using any mysql_ function because this extension is deprecated since 5.5.
You should try using mysqli or PDO instead.
You showed in screenshot that you tried using mysqli_real_escape_string function in line 147 which takes two parameters: 1- the mysqli connection, 2- the string to escape ($data)
You did it like this: $data = mysqli_real_escape_string($_GLOBALS['$con'], $data);
You have two problems here with $_GLOBALS['$con'] it should be $GLOBALS['con'] : the GLOBALS variable without the underscore _ and the key without '$'.
So you should replace the line 147 with:
$data = mysqli_real_escape_string($GLOBALS['con'], $data);
Also I don't know if GLOBALS variable is the safest way to get variables!
I user opencart v2.3.0.2 and after finished my site I use a scanner to scan my website but after while I get this error :
Fatal error: session_set_save_handler(): Session handler's function
table is corrupt in \system\library\session.php on line 16
I have try to add this in my php.ini
session.save_path = "/temp";
but I still get the same error. I use XAMPP.
the session file :
<?php
class Session {
public $session_id = '';
public $data = array();
public function __construct($adaptor = 'native') {
$class = 'Session\\' . $adaptor;
if (class_exists($class)) {
$this->adaptor = new $class($this);
} else {
throw new \Exception('Error: Could not load session adaptor ' . $adaptor . ' session!');
}
if ($this->adaptor) {
session_set_save_handler($this->adaptor);
}
if ($this->adaptor && !session_id()) {
ini_set('session.use_only_cookies', 'Off');
ini_set('session.use_cookies', 'On');
ini_set('session.use_trans_sid', 'Off');
ini_set('session.cookie_httponly', 'On');
if (isset($_COOKIE[session_name()]) && !preg_match('/^[a-zA-Z0-9,\-]{22,52}$/', $_COOKIE[session_name()])) {
exit('Error: Invalid session ID!');
}
session_set_cookie_params(0, '/');
session_start();
}
}
public function start($key = 'default', $value = '') {
if ($value) {
$this->session_id = $value;
} elseif (isset($_COOKIE[$key])) {
$this->session_id = $_COOKIE[$key];
} else {
$this->session_id = $this->createId();
}
if (!isset($_SESSION[$this->session_id])) {
$_SESSION[$this->session_id] = array();
}
$this->data = &$_SESSION[$this->session_id];
if ($key != 'PHPSESSID') {
setcookie($key, $this->session_id, ini_get('session.cookie_lifetime'), ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
}
return $this->session_id;
}
public function getId() {
return $this->session_id;
}
public function createId() {
if (version_compare(phpversion(), '5.5.4', '>') == true) {
return $this->adaptor->create_sid();
} elseif (function_exists('random_bytes')) {
return substr(bin2hex(random_bytes(26)), 0, 26);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
return substr(bin2hex(openssl_random_pseudo_bytes(26)), 0, 26);
} else {
return substr(bin2hex(mcrypt_create_iv(26, MCRYPT_DEV_URANDOM)), 0, 26);
}
}
public function destroy($key = 'default') {
if (isset($_SESSION[$key])) {
unset($_SESSION[$key]);
}
setcookie($key, '', time() - 42000, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
}
}
not important section ://
blablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablabla//
Just restart the apache & mysql. It will solve the error.
I've faced this problem maybe a week ago and still unable to figure out what is wrong.
I have 2 machines, one is running Windows, the other is running Debian 8.
So the thing is:
On Windows code executes as it should
On Linux it is a total mess
The problem is with sessions, i'm unable to make them work on Linux.
How they work:
Client Access Website --> PHP Creates Session --> Write to DB (ID, Key, Data) --> Get DB Session --> Check if it correct --> Update Data --> User leaves/log out --> Delete session
What i have:
On Windows it works exactly as i described above
On Linux script keep adding values to DB (ID and KEY are identical) and not deleting them after logout
From here i cant use authorization on Linux, but it works perfectly on Windows.
Here is a Sessions Class:
<?php
Class Session
{
public static $DBConnection;
private static $SessionCreated = false;
private static $Salt;
public function __construct($Database)
{
session_set_save_handler(array($this, 'Open'), array($this, 'Close'), array($this, 'Read'), array($this, 'Write'), array($this, 'Destroy'), array($this, 'GarbageCollector'));
register_shutdown_function('session_write_close');
Session::$DBConnection = $Database::$Connection;
$FileLocation = getcwd().DS.'Core'.DS.'Libraries'.DS.'FreedomCore';
$Files = scandir($FileLocation);
for($i = 0; $i < 4; $i++)
unset($Files[$i]);
if(!empty($Files))
{
Session::$Salt = file_get_contents($FileLocation.DS.$Files[4]);
}
else
{
$RandomFileName = substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 );
$RandomSalt = Session::GenerateRandomSalt();
file_put_contents($FileLocation.DS.$RandomFileName, $RandomSalt);
Session::$Salt = $RandomSalt;
}
}
public static function UpdateSession($Data)
{
if (session_status() != PHP_SESSION_NONE)
foreach($Data as $key=>$value)
$_SESSION[$key] = $value;
}
public static function SessionStatus()
{
if(session_status() == PHP_SESSION_NONE)
return false;
else
return true;
}
private static function GenerateRandomSalt()
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*+|/-';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $charactersLength; $i++)
$randomString .= $characters[rand(0, $charactersLength - 1)];
return $randomString;
}
public static function GenerateCSRFToken()
{
$InitialString = "abcdefghijklmnopqrstuvwxyz1234567890";
$PartOne = substr(str_shuffle($InitialString),0,8);
$PartTwo = substr(str_shuffle($InitialString),0,4);
$PartThree = substr(str_shuffle($InitialString),0,4);
$PartFour = substr(str_shuffle($InitialString),0,4);
$PartFive = substr(str_shuffle($InitialString),0,12);
$FinalCode = $PartOne.'-'.$PartTwo.'-'.$PartThree.'-'.$PartFour.'-'.$PartFive;
$_SESSION['generated_csrf'] = $FinalCode;
return $FinalCode;
}
public static function ValidateCSRFToken($Token)
{
if(isset($Token) && $Token == $_SESSION['generated_csrf'])
{
unset($_SESSION['generated_csrf']);
return true;
}
else
return false;
}
public static function UnsetKeys($Keys)
{
foreach($Keys as $Key)
unset($_SESSION[$Key]);
}
public static function Start($SessionName, $Secure)
{
$HTTPOnly = true;
$Session_Hash = 'sha512';
if(in_array($Session_Hash, hash_algos()))
ini_set('session.hash_function', $Session_Hash);
ini_set('session.hash_bits_per_character', 6);
ini_set('session.use_only_cookies', 1);
$CookieParameters = session_get_cookie_params();
session_set_cookie_params($CookieParameters["lifetime"], $CookieParameters["path"], $CookieParameters["domain"], $Secure, $HTTPOnly);
session_name($SessionName);
session_start();
//session_regenerate_id(true);
Session::$SessionCreated = true;
}
static function Open()
{
if(is_null(Session::$DBConnection))
{
die("Unable to establish connection with database for Secure Session!");
return false;
}
else
return true;
}
static function Close()
{
Session::$DBConnection = null;
return true;
}
static function Read($SessionID)
{
$Statement = Session::$DBConnection->prepare("SELECT data FROM sessions WHERE id = :sessionid LIMIT 1");
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
$Result = $Statement->fetch(PDO::FETCH_ASSOC);
$Key = Session::GetKey($SessionID);
$Data = Session::Decrypt($Result['data'], $Key);
return $Data;
}
static function Write($SessionID, $SessionData)
{
$Key = Session::GetKey($SessionID);
$Data = Session::Encrypt($SessionData, $Key);
$TimeNow = time();
$Statement = Session::$DBConnection->prepare('REPLACE INTO sessions (id, set_time, data, session_key) VALUES (:sessionid, :creation_time, :session_data, :session_key)');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->bindParam(':creation_time', $TimeNow);
$Statement->bindParam(':session_data', $Data);
$Statement->bindParam(':session_key', $Key);
$Statement->execute();
return true;
}
static function Destroy($SessionID)
{
$Statement = Session::$DBConnection->prepare('DELETE FROM sessions WHERE id = :sessionid');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
Session::$SessionCreated = false;
setcookie("FreedomCoreLanguage", null, time()-3600);
setcookie("FreedomCore", null, time()-3600);
return true;
}
private static function GarbageCollector($Max)
{
$Statement = Session::$DBConnection->prepare('DELETE FROM sessions WHERE set_time < :maxtime');
$OldSessions = time()-$Max;
$Statement->bindParam(':maxtime', $OldSessions);
$Statement->execute();
return true;
}
private static function GetKey($SessionID)
{
$Statement = Session::$DBConnection->prepare('SELECT session_key FROM sessions WHERE id = :sessionid LIMIT 1');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
$Result = $Statement->fetch(PDO::FETCH_ASSOC);
if($Result['session_key'] != '')
return $Result['session_key'];
else
return hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
}
private static function Encrypt($SessionData, $SessionKey)
{
$Salt = Session::$Salt;
$SessionKey = substr(hash('sha256', $Salt.$SessionKey.$Salt), 0, 32);
$Get_IV_Size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$IV = mcrypt_create_iv($Get_IV_Size, MCRYPT_RAND);
$Encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $SessionKey, $SessionData, MCRYPT_MODE_ECB, $IV));
return $Encrypted;
}
private static function Decrypt($SessionData, $SessionKey)
{
$Salt = Session::$Salt;
$SessionKey = substr(hash('sha256', $Salt.$SessionKey.$Salt), 0, 32);
$Get_IV_Size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$IV = mcrypt_create_iv($Get_IV_Size, MCRYPT_RAND);
$Decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $SessionKey, base64_decode($SessionData), MCRYPT_MODE_ECB, $IV);
return $Decrypted;
}
}
?>
Here is how session initialized:
if(session_status() == PHP_SESSION_NONE)
{
$Session = new Session($Database);
$InstallationIsInProgress = false;
if(isset($_COOKIE['FreedomCore']))
Session::Start('FreedomCore', false);
}
Folder with scripts on github
Important files are Database.FreedomCore.php and Sessions.FreedomCore.php
The main question is:
Why exactly the same code works perfectly on Windows, and cant to work at all on Linux?
P.S. Servers running exactly the same versions of Apache and PHP
Thanks for any help!
I am working on a PHP application wherein, i have written a Session Class. However, i am running into a strange issue. Everytime i refresh the page a new session is created.
Also, C:\xampp\tmp is writable (i am on xampp) and session_id() always returns null.
Below is my Session Class
<?php
/**
* Class and Function List:
* Function list:
* - __construct()
* - start()
* - stop()
* - generate_sid()
* - set()
* - delete()
* - get()
* - check()
* - flash()
* Classes list:
* - Session
*/
class Session
{
public $flashElements = array();
public function __construct($autoStart = true)
{
$this->started = isset($_SESSION);
e("The Session Id is " . session_id());
if (!is_writable(session_save_path()))
{
echo 'Session save path "' . session_save_path() . '" is not writable!';
}
e(session_save_path());
if ($this->started && $autoStart === false)
{
$this->start();
}
e("The Session Id is " . session_id());
}
public function start()
{
if (!$this->started)
{
session_id($this->generate_sid());
session_start();
$this->started = true;
}
}
public function stop($clearCookie = true, $clearData = true)
{
if ($this->started)
{
if (($clearCookie) && Configure::get('session.useCookie'))
{
$params = session_get_cookie_params();
setcookie(session_name() , '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
}
if ($clearData)
{
$_SESSION = array();
}
session_destroy();
session_write_close();
$this->started = false;
}
}
public function generate_sid($chars = 100, $alpha = true, $numeric = true, $symbols = true, $timestamp = true)
{
if ($chars < 0 || !is_numeric($chars))
{
return false;
}
$salt = Configure::get('security.salt');
if ($alpha)
{
$salt.= 'abcdefghijklmnopqrstuvwxyz';
}
if ($numeric)
{
$salt.= '1234567890';
}
if ($symbols)
{
$salt.= '-_';
}
$sid = null;
for ($i = 1;$i <= $chars;$i++)
{
$sid.= $saltmt_rand(0, strlen($salt) - 1);
if (mt_rand(0, 1) === 1)
{
$sid
{
strlen($sid) - 1} = strtoupper($sid
{
strlen($sid) - 1});
}
}
if ($timestamp)
{
$sid.= time();
}
return $sid;
}
public function set($keyword, $value)
{
$_SESSION[$keyword] = $value;
}
public function delete($keyword)
{
unset($_SESSION[$keyword]);
$this->flashElements[$keyword] = null;
unset($this->flashElements[$keyword]);
}
public function get($keyword)
{
$returnVar = isset($_SESSION[$keyword]) ? $_SESSION[$keyword] : false;
if (isset($this->flashElements[$keyword]))
{
$this->delete($keyword);
}
return $returnVar;
}
public function check($keyword)
{
return isset($_SESSION[$keyword]) ? true : false;
}
public function flash($value)
{
$this->set('flash', $value);
$this->flashElements['flash'] = $value;
}
}
Please suggest where am i going wrong
I think you're not creating a session because you only call the start function when
$autostart === false
Where it is true by default;
Silly of me. Got it working.
changed the below code in __construct() function
if ($this->started == false && $autoStart != false)
{
$this->start();
}
Thanks Guys!