Jump to content

Call to undefined function Login_sucess()


Ehsan_collboy
Go to solution Solved by mac_gyver,

Recommended Posts

function Login_sucess($Username,$Password){
    global $cn;
    $sql = "SELECT * FROM admin WHERE username=:username AND password=:password LIMIT 1";
    $stmt = $cn->prepare($sql);
    $stmt->bindValue(":username",$Username);
    $stmt->bindValue(":password",$Password);
    $stmt->execute();
    $Result = $stmt->rowCount();
    if($Result==1) {
        return $Found_Account = $stmt->fetch();
    }else {
        return null;
    }

}

Here is my Calling Function 

 else {
     $login =Login_sucess($Username,$Password);
       if($login){
        $_SESSION["successMessage"] = "Login Sucess ";

        redirect("login.php");
       }else {
        $_SESSION["ErrorMessage"] = "Username/Password Incorrect Please Try Again...!";
        redirect("login.php");
       }
}

When i execute my code thy show me the error

 

Uncaught Error: Call to undefined function Login_sucess() in C:\xampp\htdocs\CMS\login.php:19 Stack trace: #0 {main} thrown in C:\xampp\htdocs\CMS\login.php on line 19

 

line 19 is $login = login_sucess($username,$password)

Link to comment
Share on other sites

function Login_sucess($Username,$Password){
    global $cn;
    $sql = "SELECT * FROM admin WHERE username=:username AND password=:password LIMIT 1";
    $stmt = $cn->prepare($sql);
    $stmt->bindValue(":username",$Username);
    $stmt->bindValue(":password",$Password);
    $stmt->execute();
    $Result = $stmt->rowCount();
    if($Result==1) {
        return $Found_Account = $stmt->fetch();
    }else {
        return null;
    }

}
I create this function for userlogin 
when user press the login button here the other code

if(isset($_POST["login"])) {

    $Username = $_POST["username"];
    $Password = $_POST["password"];

    if(empty($Username)||empty($Password)){
        $_SESSION["ErrorMessage"] = "All fields must bee fills";
        redirect("login.php");
    }
   /////Checking username and password from  database 
      else {
     $login =Login_sucess($Username,$Password);
       if($login){
        $_SESSION["successMessage"] = "Login Sucess ";

        redirect("login.php");
       }else {
        $_SESSION["ErrorMessage"] = "Username/Password Incorrect Please Try Again...!";
        redirect("login.php");
       }
    }
}

Uncaught Error: Call to undefined function Login_sucess() in C:\xampp\htdocs\CMS\login.php:19 Stack trace: #0 {main} thrown in C:\xampp\htdocs\CMS\login.php on line 19

Link to comment
Share on other sites

2 things.

you are spelling a word inconsistently and that is 'sucess'  The name of your function is Login_sucess and you call it that way but your success message index is spelled correctly.

The other - What is a 'redirect'?  I went to the manual and see a lot of talk about being out of date and references to using Header("Location:$url") but nothing about using a redirect.  Actually the use of the Header IS a redirect.

The only thing that this could be is that you are NOT writing your own code but rather doing copy and pastes of blocks of code that you are finding and one of them is written using a different character set.  Be sure your editor is using a character set that works for you and then make sure that all of you copied blocks are using the same.

Link to comment
Share on other sites

@Ehsan_collboywhatever you are using to translate our replies into your native language is not working.

5 hours ago, mac_gyver said:

where exactly is the function defined at

'defined at' in this means location, i.e. what file name is it in?

5 hours ago, mac_gyver said:

how is it being made available to ...

this means how are you getting the function definition into the login.php code? typically, you would 'require' the file containing a function definition into any code that needs to call the function.

Link to comment
Share on other sites

i create this function if login_sucess and save this redirect.php file

function Login_sucess($Username,$Password){

    global $cn;

    $sql = "SELECT * FROM admin WHERE username=:username AND password=:password LIMIT 1";

    $stmt = $cn->prepare($sql);

    $stmt->bindValue(":username",$Username);

    $stmt->bindValue(":password",$Password);

    $stmt->execute();

    $Result = $stmt->rowCount();

    if($Result==1) {

        return $Found_Account = $stmt->fetch();

    }else {

        return null;

    }

}

and then i call this function in login.php

<?php

require_once("include/db.php");

require_once("include/session.php");

require_once("include/redirect.php");

?>

<?php



if(isset($_POST["login"])) {



    $Username = $_POST["username"];

    $Password = $_POST["password"];



    if(empty($Username)||empty($Password)){

        $_SESSION["ErrorMessage"] = "All fields must bee fills";

        redirect("login.php");

    }

      else {

     $login =Login_sucess($Username,$Password);//// line 19

       if($login){

        $_SESSION["successMessage"] = "Login Sucess ";



        redirect("login.php");

       }else {

        $_SESSION["ErrorMessage"] = "Username/Password Incorrect Please Try Again...!";

        redirect("login.php");

       }

    }

}

?>

When i hit login button its show me this error

Uncaught Error: Call to undefined function Login_sucess() in C:\xampp\htdocs\CMS\login.php:19 Stack trace: #0 {main} thrown in C:\xampp\htdocs\CMS\login.php on line 19

 

Link to comment
Share on other sites

I looked at your code, but I don't see a problem.  What are the full contents of redirect.php?  Is it possible you are including the wrong redirect.php?  There could also be some sort of syntax issue.  I'm not sure what is going on.  Are you possibly using Opcache?  There are times that Opcache gets a file stuck in cache, and it doesn't read changes.  If you are using opcache, you should either turn it off for development purposes, or learn how to clear the cache.  I've seen that cause major confusion plenty of times, where people had code that should work, but doesn't and they can't figure out why.

 

This has nothing to do with your problem but since I looked at your code, I figured I'd refactor it for you.

 

function loginSuccess($username, $password) {
    global $cn;

    $sql = "SELECT COUNT(*) as countOf FROM admin WHERE username=:username AND password=:password";

    $stmt = $cn->prepare($sql);
    $stmt->bindValue(":username", $username);
    $stmt->bindValue(":password", $password);
    $stmt->execute();

    $countOf = $stmt->fetchColumn();
    return ($countOf > 0);
}
  • I fixed your spelling.  The word is spelled "success".
  • Use PHP community standards for naming your functions, methods and variables.  The standard is to use camelcase. 
    •  See https://www.php-fig.org/psr/psr-12/ for this and more standards you should conform your code to
    • Writing code to these standards has many benefits including the avoidance of bugs where you mix up case, as php variables are case sensitive, better readability, and support for tools that can be integrated into the best PHP code editors to maintain standards and reformat your code
    • It's also easier for others to read
    • Don't use underscores, except in special circumstances.  Use camelCase to differentiate words.  Some people will use an _ as the first character of a name to indicate private/protected variables in OOP, but I'd avoid them entirely.  Underscores are used to name certain special PHP method names, like __construct for example.
  • Your query does not need to return anything from the database other than a count of rows that match your criteria.  Just use COUNT(*) for that, and this will always return a result that will either be 0 or something > 0
  • Have your function return a boolean, so it's clear that it's true/false.
    • Ideally you would use return ($countOf == 1) however, I don't know if you guarantee uniqueness for usernames in your database.  You should do that, with a Unique constraint on username, as this would insure that it's impossible to insert more than one row in your admin table with the same username. 
    • Not preventing the insertion of multiple admin rows with the same username can lead to terrible bugs in your system.   
      • If you do have a unique constraint on username in your admin table, then change the code to return ($countOf == 1).  

This is also semantics, but the name of your function "loginSuccess" isn't a great name.  The function, despite your name does not indicate "login success".  All it indicates is that you verified the existence of a row.  The concept of a "login" is more complicated and typically involves setting up some session variables and regenerating the session, if you are using sessions generically (for unauthenticated users).

A better name for this function would be:  function canAuthenticate() or isAuthenticated().  

  • Like 1
Link to comment
Share on other sites

First sorry for my wrong type code posting

 

I use visual studio code for coding and Firefox (in private mode) for viewing in(private mode) Firefox doesn't store the cache every thing is working fine instead of this code

 

any other solution for this i will try on my code 

 

or i try your suggestion code .instead of my code

Edited by Ehsan_collboy
Link to comment
Share on other sites

The web browser cache has nothing to do with what I'm talking about.  I'm talking about Opcache.  Opcache is a PHP component that does serverside caching of your PHP scripts in compiled form.  It is frequently installed with packages like wamp, xamp etc. or at least I think that is the case.  I don't use those types of workstation installations for development.  You need to check with phpinfo() to see if you have opcache installed and turned on.

One way to clear the cache, although brute force, would be to restart the apache process (unless your configuration uses php-fpm.  In that case you'd need to restart the php-fpm process.

 

Link to comment
Share on other sites

7 hours ago, ginerjm said:

AND you did not give us ONE COMPLETE BLOCK of code to look at.  You gave us what looks like two separate scripts containing each piece of code which could be your problem.

It took a while but in the last post OP made, there was the function, which indicated that function was declared in redirect.php, and that script was require_once in the login.php script, so it *should* work.  Since it didn't that's why I suspected an opcache issue, where the old version of the script might be cached.  This also can happen if the new script has a syntax error, and opcache will hold onto the old version that did compile.  So in no particular order, here are possible explanations of what is going on:

  • opcache enabled
    • Syntax error in request
    • Syntax error in login.php
    • Some other problem where opcache is caching one or both of those scripts
  • multiple redirect.php scripts and OP is require_once() the wrong one that doesn't have the function defined
  • Some weird character in the redirect.php file like a BOM in the wrong place that is causing the full script not to be parsed
  • Dropping in/out of php incorrectly and the function definition is not in a php block
  • PEBKAC
    • OP is showing us versions of the code with things omitted, changed that hide the real problem

To your point, I also asked the OP to post the full code for the redirect.php script a day ago, and still nothing .....

 

Link to comment
Share on other sites

OK - I took the code from the topmost post of this topic (Sunday at 1:50pm) and it ran just fine.  Commented out the query code and faked a result and it not  only ran the function but output the message telling me that it failed on the query.

So - the code seems to be written properly.  I have included my version to see.

if($login = Login_sucess('user','pswd'))
{
	$_SESSION["login_msg"] = "Login Sucess ";
	header("Location: login.php");
	exit();
}
else
{
	$_SESSION["login_msg"] = "Username/Password Incorrect Please Try Again...!";
	header("Location: login.php");
	exit();
}
//************************************
function Login_sucess($Username, $Password)
{
	global $cn;
	$sql = "SELECT * FROM admin
		WHERE username=:username AND password=:password
		LIMIT 1";
/*	$stmt = $cn->prepare($sql);
	$stmt->bindValue(":username",$Username);
	$stmt->bindValue(":password",$Password);
	$stmt->execute();
	$Result = $stmt->rowCount();
*/
	$Result = 0;
	if($Result == 1)
		return $Found_Account = $stmt->fetch();
	else
		return null;
}

Note how I modified your results message to be stored in just one variable.  Saw no reason to have a different one for simply a different value.

I do hope that the OP posts his findings when he solves this riddle.  Would like to know where he went wrong.

 

Link to comment
Share on other sites

some other possibilities -

  1. it's conditionally defined - inside another function definition that hasn't been called yet or inside some conditional logic  that didn't execute
  2. it's not within php tags at all
  3. it's using a short opening tag that's not enabled
  4. it's within a comment

the OP needs to post the complete contents (including the opening php tag in the file) of redirect.php in order to either confirm or eliminate the various possibilities as the cause.

  • Great Answer 1
Link to comment
Share on other sites

Sorry from me for late reply  (You guys amazing .. No debit ..)

This code is redirect .php

<?php include_once("include/db.php"); ?>
<?php

function redirect($Newlocation){
    header("Location:".$Newlocation);
    exit;
}
function checkusername($Username){
    global $cn;
    $sql = "SELECT username FROM admin WHERE username=:username";
    $stmt = $cn->prepare($sql);
    $stmt->bindValue(":username",$Username);
    $stmt->execute();
    $Result = $stmt->rowCount();
    if($Result>0) {

        return $stmt->fetch();
    }else {
        return false;
    }
function Login_sucess($Username,$Password){
    global $cn;
    $sql = "SELECT * FROM admin WHERE username=:username AND password=:password LIMIT 1";
    $stmt = $cn->prepare($sql);
    $stmt->bindValue(":username",$Username);
    $stmt->bindValue(":password",$Password);
    $stmt->execute();
    $Result = $stmt->rowCount();
    if($Result==1) {
        return $Found_Account = $stmt->fetch();
    }else {
        return null;
    }

}
}
?>

And this code is login.php where i see the error

<?php
require_once("include/db.php");
require_once("include/session.php");
require_once("include/redirect.php");
?>
<?php

if(isset($_POST["login"])) {

    $Username = $_POST["username"];
    $Password = $_POST["password"];

    if(empty($Username)||empty($Password)){
        $_SESSION["ErrorMessage"] = "All fields must bee fills";
        redirect("login.php");
    }
   /////Checking username and password from  database 
      else {
     $login =Login_sucess($Username,$Password);
       if($login){
        $_SESSION["successMessage"] = "Login Sucess ";

        redirect("login.php");
       }else {
        $_SESSION["ErrorMessage"] = "Username/Password Incorrect Please Try Again...!";
        redirect("login.php");
       }
    }
}


?>
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="CSS/style.css">
        <script src="https://kit.fontawesome.com/46936f93f7.js" crossorigin="anonymous"></script>
     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
    <title>
        Welcome To the BummerStyle
    </title>
    </head>
<body>
    <!---navbar-->
    <div style="height: 10px; background: #27aae1;"></div>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
    <a href="#" class="navbar-brand" >BummerStyle.com</a>
    <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarcollapseCMS">
    <span class="navbar-toggler-icon"></span>
</button>
    <div class="collapse navbar-collapse" id="navbarcollapseCMS">
    
</div>
</div>
    </nav>
    <div style="height: 10px; background: #27aae1;"></div>
    <!---navbar End-->
    
    <header class="bg-dark text-white py-3">
        <div class="container ">
            <div class="row">
            </div>
        </div>
    </header>
    <!-- Main Area Start --->
    <section class="container py-2 mb-4">
        <div class="row">
        <div class="offset-sm-3 col-sm-6" style="min-height:500px;">
       <br><br><br>
       <?php
echo ErrorMessage();
echo SuccessMessage();
?>
            <div class="card bg-secondary text-light">
            <div class="card-header">
                <h4 style="text-align: center;">Welcome Back!</h4>
                </div>
                <div class="card-body bg-dark">
                
                <form method="POST" action="login.php">
                    <div class="form-group">
                    <label for="username" style="color: rgb(251, 174, 44);">Username:</label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                <span class="input-group-text text-white bg-info"><i class="fas fa-user"></i></span>
                        </div>
                        <input type="text" class="form-control" name="username" id="username">
                    </div>
                    </div>
                    <div class="form-group">
                    <label for="password" style="color: rgb(251, 174, 44);">Password:</label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                        <span class="input-group-text text-white bg-info"><i class="fas fa-lock"></i></span>
                        </div>
                        <input type="password" class="form-control" name="password" id="password">
                    </div>
                    </div>
                    <input type="submit" name="login" class="btn btn-info btn-block" value="Login">
                </form>
            </div>
            </div>
        </div>

        </div>




    </section>
    <!--- Main Area End   --->
    <!---Footer Start-->
<footer class="bg-dark text-white">
    <div class="container">
        <div class="row" >
            <div class="col">
            <p class="lead text-center">Theme By | Ehsan Nawaz | <span id="year"></span> &copy;  ----ALL Right Reserved.</p>
        </div>
    </div>
    </div>
</footer>
<div style="height: 10px; background: #27aae1;"></div>
<!--footer End-->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script>
<script>
    $('#year').text(new Date().getFullYear());
</script>
</body>
</html>

Please check my code and highlight my problem

Edited by Ehsan_collboy
Link to comment
Share on other sites

  • Solution
7 minutes ago, Ehsan_collboy said:

Please check my code and highlight my problem

you have actually been give the answer -

21 hours ago, mac_gyver said:

it's conditionally defined - inside another function definition that hasn't been called yet...

don't put function definitions inside of other function definitions.

Edited by mac_gyver
  • Thanks 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.