Jump to content

Fatal error: Uncaught TypeError: sha1() expects parameter 1 to be string, integer given


phpsane

Recommended Posts

Guys,

 

Even though my Sha1 has string, I get this error:

 

Fatal error: Uncaught TypeError: sha1() expects parameter 1 to be string, integer given in C:\xampp\htdocs\id\register.php:31 Stack trace: #0 C:\xampp\htdocs\id\register.php(31): sha1(16) #1 {main} thrown in C:\xampp\htdocs\id\register.php on line 31

 

 

<?php
 
/*
ERROR HANDLING
*/
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
 
include 'config.php';
 
// check if user is already logged in
if (is_logged() === true) {
die("You are already logged-in! No need to register again!");
}
 
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST["username"]) && 
  isset($_POST["password"]) &&
  isset($_POST["password_confirmation"]) && 
  isset($_POST["email"]) && 
  isset($_POST["email_confirmation"]) && 
  isset($_POST["first_name"]) && 
  isset($_POST["gender"]) &&
  isset($_POST["surname"])) {
 
// create random hash for email confirmation
   $account_activation_code = sha1(mt_rand(5, 30));
$account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
 
    // remove space in start of string
    /*
* passwords and email are leaved unescaped here because
* if you put them into mysqli_real_escape_string they are not empty
    */
        $username  = trim(mysqli_real_escape_string($conn, $_POST["username"]));
$password  = $_POST["password"];
$password2  = $_POST["password_confirmation"];
        $first_name = trim(mysqli_real_escape_string($conn, $_POST["first_name"]));
        $surname  = trim(mysqli_real_escape_string($conn, $_POST["surname"]));
$gender  = trim(mysqli_real_escape_string($conn, $_POST["gender"]));
        $email  = $_POST["email"];
        $email_confirmation = $_POST["email_confirmation"];
        $email2  = trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
        $account_activation = 0; // 1 = active | 0 = not active
 
        //Hashed Password.
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
//SEE IF BELOW CODE AFTER FOLLOWING WORKS OR NOT AS SUBSTITUTE FUNCTION OVER mysqli_stmt_get_result FUNCTION
//Select Username and Email to check against Mysql DB if they are already registered or not.
$stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
mysqli_stmt_bind_param($stmt, 'ss', $username, $email_2);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
 
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        
// Check if inputted Username is already registered or not.
if ($row['usernames'] == $username) {
$_SESSION['error'] = "That username is already registered.";
// Check if inputted Username is between 8 to 30 characters long or not.
} elseif (strlen($username) < 8 || strlen($username) > 30) {
$_SESSION['error'] = "Username must be between 8 to 30 characters long!";
// Check if inputted Email is already registered or not.
} elseif ($row['emails'] == $email_2) {
$_SESSION['error'] = "That email is already registered.";
// Check if both inputted EMails match or not.
} elseif ($email != $email_confirmation) {
$_SESSION['error'] = "Emails don't match!";
// Check if inputed Email is valid or not.
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
// Check if both inputted Passwords match or not.
} elseif ($password != $password_confirmation) {
$_SESSION['error'] = "Passwords don't match.";
// Check if Password is between 8 to 30 characters long or not.
} elseif (strlen($password) < 8 || strlen($password) > 30) {
$_SESSION['error'] = "Password must be between 6 to 30 characters long!";
} else {
 
//Insert the user's input into Mysql database using php's sql injection prevention method.
$stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email2, $first_name, $surname, $gender, $account_activation_code, $account_activation);
mysqli_stmt_execute($stmt);
 
//Check if user's registration data was successful submitted or not.
if (mysqli_stmt_insert_id($stmt)) {
echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";
 
//Send account activation link by email for user to confirm his email and activate his new account.
$to = $email;
$subject = "Your ".$site_name." account activation!";
$body  = nl2br("
===============================\r\n
".$site_name." \r\n
===============================\r\n
From: ".$site_admin_email."\r\n
To: ".$email."\r\n
Subject: Yours ".$subject." account activation \r\n
Message: ".$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
$headers = "From: " . $site_admin_email . "\r\n";
 
   if (mail($to,$subject,$body,$headers)) {
    $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
 
//Clear the Session Error so it can no longer be used.
unset($_SESSION['error']);
unset($_POST);
exit();
 
//Redirect user to login page after 5 seconds.
header("refresh:5;url=login.php");
   } 
else 
{
    $_SESSION['error'] = "Email not sent, please contact website administrator!";
   }     
} 
else 
{
$_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
}
   }
}
}
 
?>
<!DOCTYPE html>
<html>
<head>
<title><?php $social_network_name ?> Signup Page</title>
</head>
<body>
<div class ="container">
 
<?php
 
// error messages
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}
 
?>
 
<form method="post" action="">
<center><h2>Signup Form</h2></center>
<div class="form-group">
<center><label>Username:</label>
<input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
</div>
<div class="form-group">
<center><label>Password:</label>
<input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>Repeat Password:</label>
<input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
</div>
<div class="form-group">
<center><label>First Name:</label>
<input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
</div>
<div class="form-group">
<center><label>Surname:</label>
<input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
</div>
<div class="form-group">
<center><label>Gender:</label>
<input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
</div>
<div class="form-group">
<center><label>Email:</label>
<input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
</div>
<div class="form-group">
<center><label>Repeat Email:</label>
<input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
</div>
<center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
<center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
 
</form>
 
</div>
</body>
</html>
Link to comment
Share on other sites

If you could only learn to look things up before using them......

 

RTFM!

 

This is what it shows you:

 

 


int mt_rand ( int $min , int $max )

 

And then you try wrapping the function name in quotes!  Do  you have no idea on how to code???? 

You have made 30+ posts here and this is how you think things work?

 

OMG!!

 

I'll probably get flagged for these comments but watching you struggle and meander and refuse to do the proper reading and learning is just so sad.

Link to comment
Share on other sites

In case the function definition, as quoted by ginerjm, isn't obvious, the manual has a section that describes what the function returns:

 

A random integer value between min (or 0) and max (or mt_getrandmax(), inclusive), or FALSE if max is less than min.

 

 

More information can be found here:

http://php.net/manual/en/function.mt-rand.php

Link to comment
Share on other sites

If you could only learn to look things up before using them......

 

RTFM!

 

This is what it shows you:

 

 

 

And then you try wrapping the function name in quotes!  Do  you have no idea on how to code???? 

You have made 30+ posts here and this is how you think things work?

 

OMG!!

 

I'll probably get flagged for these comments but watching you struggle and meander and refuse to do the proper reading and learning is just so sad.

 

GinerJM.

 

 

Boy oh boy! You did not understand my original post now did you ?

My code was like this:

sha1(mt_rand(5, 30))

Note, the 2nd param. Min, Max.

But this was showing error:

Fatal error: Uncaught TypeError: sha1() expects parameter 1 to be string, integer given in C:\xampp\htdocs\id\register.php:31 Stack trace: #0 C:\xampp\htdocs\id\register.php(31): sha1(16) #1 {main} thrown in C:\xampp\htdocs\id\register.php on line 31

 

Now, what is the error saying ? It is saying the 1st param (min. max) should be a STRING and not an INT. Hence, I had no choice but to "wrap it in single quotes" to turn that into a string. Don't blame me if I am going against the manual. Blame the error for forcing me to go against the manual.

What have you got to say now about this issue other than RTFM? Same question asked to cyberRobot.

 

Kicken, your type-casting link lead me to this link:

http://php.net/manual/en/language.types.string.php

 

Anyway, switching to STRING yields error stating to switch the parameter to INT. Now, we are going in a never-ending loop!

Link to comment
Share on other sites

Now, what is the error saying ? It is saying the 1st param (min. max) should be a STRING and not an INT.

 

Just to clarify, the call to mt_rand() is fine. The error is caused by the first parameter for sha1(), which needs to be a string. Since mt_rand() returns an integer, you need to use something like type casting, as mentioned by kicken.

 

 

Hence, I had no choice but to "wrap it in single quotes" to turn that into a string.

 

 

All the following does is break the call to mt_rand().

sha1('mt_rand'(5, 30))
Link to comment
Share on other sites

You poor egotistical noob.  As I pointed out - you dont' even know what coding is all about.  Your attempt to use the mt_rand function without reading up on its syntax was the first problem.  Then when you thought you needed a string, your foolish mistake in wrapping A FUNCTION NAME in quotes to make it a string was just hilarious!  As I also said - you have no idea what coding is all about.

 

The problem with your code (including the "first line" that you wondered about how it could be wrong) is you can't relate the error messages to it.  If you had done any real learning and understood syntax you might realize that a function returns a result.  The result from mt_rand AS POINTED OUT IN THE MANUAL  is an answer of type Integer.  Hence the error message.  Now why would you want to encrypt a random number?  We'll never know but, as others are trying to tell you, you need to typecast the RESULT of the call, not the function name itself.

 

If you spent anywhere near as much time LEARNING as you do attempting to ridicule me and making funnies in all of your other posts you might actually accomplish something that resembled programming.  

 

I'll repeat my first comment from before:  RTFM!!!  From start to finish!

Link to comment
Share on other sites

Link to comment
Share on other sites

The PHP manual as well as other solid reference works would not be 'confusing' to you IF you Spent Some Time Trying To Learn From Them.

 

What?  You think this business is easy?  It takes quite a bit of mental prowess and diligence in doing the necessary research on how to best solve a problem and code a solution that is correct, efficient and resource-conscious.  Without becoming something other than a 'layman' you will never get there.

 

PS - I LOVE the fact that the link in your previous post takes me to a page that discusses and shows an example of how typecasting works.  MORE IMPORTANT is that the very next paragraph of it tells you to RTFM!!!!

Link to comment
Share on other sites

Hmm...the type-casting link brings me to the type-casting page in the manual.  :confused:

http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

 

Yes. The Type Casting link in the manual did bring me to a page that did not explain how to do the Type Casting from INT to STRING. Dear me!

All it says, on the topic is this:

"Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.".
I did not understand that atall. Beginners tend to miss things, you see! Even though it is now very clear the phrase was giving out the format on how to write the code. But at the time, I was searching for sample codes and this was not what I was looking for as it did not provide a simple code sample. Therefore, GinerJM's RTFM was, again, proving to be useless to me.
 

That manual link, gave this link instead which teaches what a STRING is. But that link is irrelevant as it never teaches how to Type Cast from INT to STRING.

http://php.net/manual/en/language.types.string.php

 

So, you see why I hate the manual and why most programmer in other forums told me to learn from tutorial sites (pdodelusions.com, codeacademy.com, etc.)  and not from the manual as a beginner but only use it as a reference guide ?

Anyway, about 8hrs ago, I googled for proper tutorial on the topic and found it.

http://www.dyn-web.com/php/strings/type.php#f1

Used it to fix my code.

I grabbed these codes:

$val = 24; // integer
// set $val type to string
settype($val, 'string');
// check type and value of $val
var_dump($val); // string(2) "24"

Then I modified it to following. But no luck ridding the error!

/*
//$mt_rand_min = 5; // integer
//$mt_rand_max = 30; // integer
 
 
/* SET TYPE
// set $mt_rand_min and $mt_rand_max type to string
settype($mt_rand_min, 'string');
// check type and value of $mt_rand_min
var_dump($mt_rand_min); // string(1) "5"
settype($mt_rand_max, 'string');
// check type and value of $mt_rand_min
var_dump($mt_rand_max); // string(2) "30"
*/

The SET TYPE did not work.

Then found TYPE CAST and remembered Kicken's advice to use it. But the following code looked mostly empty and I had not a feintest clue how to proceed.

$val = true; // boolean
// cast $val to string and check return value with var_dump
var_dump( (string)$val ); // string(1) "1"
// check type and value of $val
var_dump($val); // bool(true) 

Nwo, how on earth was I gonna make use of the above code to fix my problem ? Remember, I am a complete beginner and GinerJm did growl that I know nothing about coding. And, he is absolutely right (even though I did manage to fix the problem all by my humblest self after 10 mins!).

The following was my 1st unsuccessful attempt:

/* TYPE CAST
var_dump( (string)$mt_rand_min); // string(1) "5"
var_dump( (string)$mt_rand_max); // string(1) "30"
// check type and value of $mt_rand_min
var_dump($mt_rand_min); // int(5)
// check type and value of $mt_rand_min
var_dump($mt_rand_max); // int(30)
*/

Then, GinerJm's soul probably possessed me and I came-out with this piece:

//Original code of mlukac89: "$account_activation_code = sha1(mt_rand(5, 30));"
//https://www.sitepoint.com/community/t/improvements-to-member-registration-site-reg-php/260491/52
//https://cdn-enterprise.discourse.org/sitepoint/community/uploads/default/original/3X/a/9/a95efc90ebc6d93872d602dbe0246d43d77b618b.zip 
// My modified Code (next 8 lines) to fix error: "Fatal error: Uncaught TypeError: sha1() expects parameter 1 to be string, integer given in ..."
$mt_rand = mt_rand(5, 30);
settype($mt_rand, 'string');
var_dump($mt_rand);
   $account_activation_code = sha1($mt_rand);
var_dump($mt_rand);
echo "$account_activation_code";
$account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
echo "$account_activation_link";

The above is debugging mode coding.

 

The registration.php is now working smoothly. I wonder why I did not face this error before in the last 3 mnths both on my website and Xampp! Else, I could have pestered GinerJm man enough to get him to fix it! Lol!

Psycho, GinerJm, Sepodati, Mac_Guyver and Requinix (and let us not forget YOU!) can now pat me on my back and say:

"Well Done! Even though your code is not perfect, you did atleast manage to get rid of the error all by yourself using Type Casting which is actually an adv level stuff. And, you're a beginner and a bad one at that!! Lol!

Link to comment
Share on other sites

You poor egotistical noob.  As I pointed out - you dont' even know what coding is all about.  Your attempt to use the mt_rand function without reading up on its syntax was the first problem.  Then when you thought you needed a string, your foolish mistake in wrapping A FUNCTION NAME in quotes to make it a string was just hilarious!  As I also said - you have no idea what coding is all about.

 

The problem with your code (including the "first line" that you wondered about how it could be wrong) is you can't relate the error messages to it.  If you had done any real learning and understood syntax you might realize that a function returns a result.  The result from mt_rand AS POINTED OUT IN THE MANUAL  is an answer of type Integer.  Hence the error message.  Now why would you want to encrypt a random number?  We'll never know but, as others are trying to tell you, you need to typecast the RESULT of the call, not the function name itself.

 

If you spent anywhere near as much time LEARNING as you do attempting to ridicule me and making funnies in all of your other posts you might actually accomplish something that resembled programming.  

 

I'll repeat my first comment from before:  RTFM!!!  From start to finish!

 

Spot on, old man! You actually figured all that out how I operate and what is on my mind. Have to give you a meddle for that. You are right. I do not know coding. Still learning.

This complicated crappy half-crafted so-called tutorial from the manual is no good to me. Me, the beginner.

http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

 

But this was ok enough for me to solve the issue:

http://www.dyn-web.com/php/strings/type.php#f1

 

Give me good enough tutorials, like that, Old Man! And before you know it, I've become a rocket scientist dragging you off to the moon! ;)

I'm not really the problem. The real problem is: There are not good enough tutorials. The popular tutorial sites don't cover the adv stuffs like this. That is the real problem.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.