mysqli_real_escape_string() expects parameter 1 to be mysqli; mysql_result() expects parameter 1 to be resource - mysqli

I'm getting these errors:
Notice: Undefined variable: link in login.php on line 11
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli,
null given in login.php on line 11
Notice: Undefined variable: link in login.php on line 18
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in login.php on line 18
Warning: mysql_result() expects parameter 1 to be resource, null given
in login.php on line 19
Here's the code:
<?php
session_start();
$link = mysqli_connect('localhost','root','') or die();
mysqli_select_db($link,'lr') or die();
function sanitize($data) {
return mysqli_real_escape_string($link, $data); <<line 11
}
function user_exists($username) {
$username = sanitize($username);
$query = mysqli_query($link, "SELECT COUNT('user_id') FROM 'users' WHERE 'username' = '$username'"); <<line 18
return (mysql_result($query, 0) ==1) ? true : false; <<line19
}
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password';
} else if (user_exists($username) === false) {
$errors[] = 'User not found';
}
}
?>
What's the problem?

You need to use $_GLOBALS['link'] inside function.
Like this:
function sanitize($data) {
return mysqli_real_escape_string($_GLOBALS['$link'], $data); <<line 11
}
Same thing inside user_exist function.

Global may have worked to fix the problem, but it's better to pass the variable into the function.
function sanitize($data, $A) {
return mysqli_real_escape_string($A, $data); <<line 11
}
function user_exists($username, $A) {
$username = sanitize($username);
$query = mysqli_query($A, "SELECT COUNT('user_id') FROM 'users' WHERE 'usernam' = '$username'"); <<line 18
return (mysql_result($query, 0) ==1) ? true : false; <<line19
}
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username, $link) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password';
} else if (user_exists($username, $link) === false) {
$errors[] = 'User not found';
}
}

Related

PHP Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array

Since I've updated to PHP 8.x the toolptips aren't working anymore:
'PHP message: PHP Warning: Undefined array key "game_id" in /var/www/vhosts/my-domain.net/httpdocs/_eqdkp/infotooltip/infotooltip_feed.php on line 86PHP message: PHP Warning: Undefined array key "data" in /var/www/vhosts/my-domain.net/httpdocs/_eqdkp/infotooltip/infotooltip_feed.php on line 86PHP message: PHP Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in /var/www/vhosts/my-domain.net/httpdocs/_eqdkp/infotooltip/infotooltip.class.php:362\nStack trace:\n#0 /var/www/vhosts/my-domain.net/httpdocs/_eqdkp/infotooltip/infotooltip.class.php(362): implode()\n#1 /var/www/vhosts/my-domain.net/httpdocs/_eqdkp/infotooltip/infotooltip_feed.php(86): infotooltip->getitem()\n#2 {main}\n thrown in /var/www/vhosts/my-domain.net/httpdocs/_eqdkp/infotooltip/infotooltip.class.php on line 362', referer: https://www.my-domain.net/
infotooltip_feed.php:
$item = $itt->getitem($data['name'], $data['lang'], $data['game_id'], $data['update'], $data['data']);
infotooltip.class.php:
public function getitem($item_name, $lang=false, $game_id=false, $forceupdate=false, $data=array()) {
$item_name = htmlspecialchars_decode($item_name, ENT_QUOTES);
$game = $this->config['game'];
$this->pdl->log('infotooltip', 'getitem called: item_name: '.$item_name.', lang: '.$lang.', game_id: '.$game_id.', forceupdate: '.(($forceupdate) ? 'true' : 'false') .', data: '.implode($data, ', '));
$lang = (!$lang || $lang == '') ? $this->config['game_language'] : $lang;
$this->init_cache();
$ext = '';
if(count($data) > 0) {
$ext = '_'.base64_encode(serialize($data));
}
if(!$forceupdate) {
$cache_name = $this->config['game'].'_'.$lang.'_'.($game_id ? $game_id : $item_name).$ext;
$this->pdl->log('infotooltip', 'Search in cache: '.$cache_name);
$cache_name = md5($cache_name).'.itt';
if(in_array($cache_name, $this->cached)) {
$item = unserialize(file_get_contents($this->pfh->FilePath($cache_name, 'itt_cache')), array('allowed_classes' => false));
if(isset($item['baditem'])){
$this->pdl->log('infotooltip', 'Item found, but item is baditem. forceupdate set to true.');
$forceupdate = true;
} else {
$this->pdl->log('infotooltip', 'Item found.');
return $this->item_return($item);
}
} else { //check for language
$this->pdl->log('infotooltip', 'Item not found. Check if language '.$lang.' is available.');
$this->load_parser(false, true);
$new_lang_set = false;
$before_lang = $lang;
foreach($this->config['prio'] as $parsing) {
if(!isset($this->parser_info[$game][$parsing]->av_langs[$before_lang])) {
$mid_lang = $this->config['game_language'];
$new_lang_set = true;
if(!isset($this->parser_info[$game][$parsing]->av_langs[$mid_lang])) {
$mid_lang = key($this->parser_info[$game][$parsing]->av_langs);
}
} else {
$new_lang_set = false;
break;
}
}
if($new_lang_set) {
$this->pdl->log('infotooltip', 'Language was not available. Changed language to '.$mid_lang.'. Search again.');
$lang = $mid_lang;
return $this->getitem($item_name, $lang, $game_id, $forceupdate, $data);
}
$this->pdl->log('infotooltip', 'Language is available.');
}
}
if($forceupdate) {
$this->pdl->log('infotooltip', 'Force item-update.');
$this->delete_item($item_name, $lang, $game_id, $ext);
}
$item = $this->update($item_name, $lang, $game_id, $data);
return $this->item_return($item);
}

How to post Integer in Alamofire Parameters

i followed a tutorial for Register and Login Request in xcode.
But i have a problem with the Code because i changed some values of it.
My variables in the php script are ssiss (string, string, int, string, string). In the swift file i am using Alamofire. Here it is:
#IBAction func buttonRegister(_ sender: UIButton) {
let ageINT = Int(ageTF.text!);
//creating parameters for the post request
let parameters: Parameters=[
"name":nameTF.text!,
"username":usernameTF.text!,
"age": ageINT ?? 0,
"country":countryTF.text!,
"password":passwordTF.text!,
]
//Sending http post request
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
//converting it as NSDictionary
let jsonData = result as! NSDictionary
//displaying the message in label
self.labelMessage.text = jsonData.value(forKey: "message") as! String?
}
}
I think the problem is i pass an String value instead of a integer value. That is why i already have changed the value for "age" from "age":ageTF.text!, to "age": ageINT ?? 0,
The error i am get is "Required parameters are missing".
I am getting this "error-response" message because of this php-script:
<?php
//importing required script
require_once '../includes/DbOperation.php';
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!verifyRequiredParams(array('name', 'username', 'age', 'country', 'password'))) {
//getting values
$name = $_POST["name"];
$username = $_POST["username"];
$age = $_POST["age"];
$country = $_POST["country"];
$password = $_POST["password"];
//creating db operation object
$db = new DbOperation();
//adding user to database
$result = $db->createUser($name, $username, $age, $country, $password);
//making the response accordingly
if ($result == USER_CREATED) {
$response['error'] = false;
$response['message'] = 'User created successfully';
} elseif ($result == USER_ALREADY_EXIST) {
$response['error'] = true;
$response['message'] = 'User already exist';
} elseif ($result == USER_NOT_CREATED) {
$response['error'] = true;
$response['message'] = 'Some error occurred';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are missing';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid request';
}
//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{
//Getting the request parameters
$request_params = $_REQUEST;
//Looping through all the parameters
foreach ($required_fields as $field) {
//if any requred parameter is missing
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
//returning true;
return true;
}
}
return false;
}
print_r(json_encode($response));
?>
And this is the other php script:
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Constants.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createUser($name, $username, $age, $country, $password)
{
if (!$this->isUserExist($username)) {
$password = md5($pass);
$stmt = $this->conn->prepare("INSERT INTO user (name, username, age, country, password) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("ssiss", $name, $username, $age, $country, $password);
if ($stmt->execute()) {
return USER_CREATED;
} else {
return USER_NOT_CREATED;
}
} else {
return USER_ALREADY_EXIST;
}
}
private function isUserExist($username)
{
$stmt = $this->conn->prepare("SELECT id FROM user WHERE username = ? ");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}

Laravel 5.6 Error NotFoundHttpException in RouteCollection.php (line 179)

I try login facebook it's error NotFoundHttpException in RouteCollection.php (line 179)
I using Laravel 5.6
public function facebookAuthRedirect()
{
return Socialite::with('facebook')->redirect();
}
if facebook login success it's Redirect to facebook
public function facebookSuccess()
{
$provider = Socialite::with('facebook');
if (Input::has('code')){
$user = $provider->stateless()->user();
//dd($user); // print value debug.
$email = $user->email;
$name = $user->name;
$password = substr($user->token,0,10);
$facebook_id = $user->id;
//เช็คว่า email เป็น null หรือไม่
if($email == null){ // case permission is not email public.
$user = $this->checkExistUserByFacebookId($facebook_id);
if($user == null){
$email = $facebook_id;
}
}
else
{
$user = $this->checkExistUserByEmail($email);
if($user != null){
if($user->facebook_id == ""){ // update account when not have facebook id.
$user->facebook_id = $facebook_id;
$user->save();
}
}
}
if($user!=null){ // Auth exist account.
Auth::login($user);
return redirect('index/');
}
else{ // new Account.
$user = $this->registerUser($email,$name,$password,$facebook_id);
Auth::login($user);
return redirect('index/');
}
}
return redirect('/');
}
Check Email and facebook
private function checkExistUserByEmail($email)
{
$user = \App\User::where('email','=',$email)->first();
return $user;
}
private function checkExistUserByFacebookId($facebook_id)
{
$user = \App\User::where('facebook_id','=',$facebook_id)->first();
return $user;
}
Member Register
private function registerUser($email,$name,$password,$facebook_id)
{
$user = new \App\User;
$user->email = $email;
$user->name = $name;
$user->password = Hash::make($password); // Hash::make
$user->balance = 0;
$user->level = "member";
$user->facebook_id = $facebook_id;
$user->save();
return $user;
}
M Route file web.php
Route::get('login/facebook', 'Auth\LoginController#facebookAuthRedirect');
Route::get('login/facebook/callback', 'Auth\LoginController#facebookSuccess');
Clear route cache:
php artisan route:cache
and then check results

Login Page Hash issue UPDATE

I am having a issue with my login page reading a function to login
on my register page which I'm proud to say works perfect
this is my password hash code
$password = password_hash($password, PASSWORD_BCRYPT);
my login page has 2 fields
email &
password
I have re cleaned my code and solved the issue some what
functions are working
when I enter email and password it triggers
Warning! Email or Password Incorrect
plus an error at the top
Notice: Undefined index: password in C:\Program Files (x86)\Zend\Apache2\htdocs\CMS\functions\functions.php on line 249
this is line 249
$db_password = $row['password'];
/* Validate Login */
function validate_login()
{
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$email = clean($_POST['email']);
$password = clean($_POST['password']);
if (empty($email)) {
$errors[] = "Email Required";
}
if (empty($password)) {
$errors[] = "Password Required";
}
if (! empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
if (login_user($email, $password)) {
redirect("../account/profile.php");
} else {
echo validation_errors("Email or Password Incorrect");
}
}
}
} // End Function
/* User Login */
function login_user($email, $password)
{
$sql = "SELECT user_pwd, uid FROM userss WHERE user_email = '" . escape($email) . "'";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['password'];
if (hash_algos($password) == $db_password) {
return true;
} else {
return false;
}
}
}// End Function
It looks like you are missing a closing bracket for your validate_login() function so it is defining the login_user() function only after the first function is called. Therefore as you progress through your validate_login() function you call the login_user() function before it is created since it is created after the if statement completes.
OK I just figured out the issue
if (hash_algos($password) == $db_password) {
return true;
} else {
return false;
}
changed it to this
if(password_verify($password, $db_password)){
return true;
} else {
return false;
}

codeigniter form validation always returns false even when rules met

Problem: even if my form fields meet the rules the codeigniter form validation still returns false (error).
example:
public function edit(){
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'title', 'required|xss_clean|trim|is_unique[news.Title]');
$this->form_validation->set_rules('description', 'description', 'required|xss_clean|trim');
$this->form_validation->set_rules('notes', 'notes', 'required|xss_clean|trim');
if ($this->form_validation->run() == FALSE)
{
$data['error'] = '';
$data['page_title']="Edit News";
echo "error";
}
else {
..........
if i leave the fields empty it will tell me to enter something because they cant be left empty. if i type something then it returns error once i submit the form.
you have to use the callback validation function
you have to pass id also
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean|trim|callback_check_title');
function check_title($title) {
if($this->input->post('id'))
$id = $this->input->post('id');
else
$id = '';
$result = $this->news_model->check_unique_title($id, $title);
if($result == 0)
$response = true;
else {
$this->form_validation->set_message('check_title', 'Title must be unique');
$response = false;
}
return $response;
}
in model
function check_unique_title($id, $title) {
$this->db->where('title', $title);
if($id) {
$this->db->where_not_in('id', $id);
}
return $this->db->get('news')->num_rows();
}
it will work for both insert and update
no need for callback function
The problem is : codeigniter database class is not loaded;
You should load database : $this->load->database(); before running
if ($this->form_validation->run() == FALSE)
{
$data['error'] = '';
$data['page_title']="Edit News";
echo "error";
}