Proper indenting and formatting makes this kind of nesting error much easier to spot.
I tried writing code that had a catch without a try but I couldn’t get anything that didn’t error.
I think the “may be” in the docs, though it says try, applies to try - catch as paired. i.e. code does not need try - catch and custom handling can be used instead (IMHO often a better approach as it can be logged to a file or emailed) eg.
<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
//try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
//} catch (Exception $e) {
// echo 'Caught exception: ', $e->getMessage(), "\n";
//}
// Continue execution
echo "Hello World\n";
?>
uniqueideaman if you’re having trouble pairing up your curly braces, you could try a simple custom exception handler.
You was puting a try,catch code in wrong place. Give me your database i will test this.
I was gived you a working example of code, i don’t know why you don’t use code editor and why you have problems all time with this simple script.
EDIT :
I created a database and try to insert some user, and problem is in your insert query you need to change $registration_random_numbers variable with $account_activation_code because $registration_random_numbers variable don’t exists and query fail because of it.
Other time check your variables.
He doesn’t need no custom wrappers. It will add yet another straw plane to his cargo cult code, which he has no idea how to deal with.
Neither your example makes any sense. If you take out from this code that handler of yours, the outcome will be exactly the same.
Neither one needs a handler to log or email an error - PHP proper already can do it, without yet another piece of pointless code.
All he needs to is to leave exceptions alone. It will serve him well now, an will make it possible to add his own error handling with Go and geishas in the future.
Thanks for pointing this out! Silly me!
Yes, you typed $registration_random_numbers and I changed it to $account_activation_code on one place but forgot it on another in the register.php.
Next time I change a variable name, I might aswell get note pad CTRL H to do it on all places in all files. That way, I never miss out a spot doing it manually.
I’ve also replaced it now in the account_activation.php. I hope things work now. Will keep everyone updated tomorrow or so as I cannot test it on my localhost as I need to get confirmation email and localhost Xampp is unable to do it. Tried testing it on my site but to my horror I find my domain not working. Checking my domain acc I find 3 of my domains suspended due to me not confirming the email on their yearly routine contact update check. Hadn’t logged into my email acc for a long time and so missed the alert email. Got the domain registrer to sort this out now. They say, will take 24hrs to get everything back to normal. And so, tomorrow night, will check the scripts on my site and then provide feedback.
In the meanwhile, I might aswell harass everyone on other issues while I wait for this issue to be sorted! Lol!
Where was it not properly indented ?
Just to start:
1 - comes back out, even though you opened an if()
so it should move in.
2 - randomly indents for no reason.
Look at the closing curly braces towards the bottom of the code as well - if indenting is correct, I’d expect each closing-brace to step out by your fixed indent step each time, yet they don’t.
It’s not the end of the world, but it does make things easier to read, and in cases where you’re trying to follow if/then/else structures especially so.
Adding onto this
$account_activation_link = "http://www.'".$site_domain."'.com/'".$social_network_name."'/activate_account.php?email='".$_POST['email']."'&hash='".$account_activation_code."'";
This line will make the link look like this
http://www.'mysite'.com/'my_social_network'/activate_account.php?email='test@email.com'&hash='123'
Which is completely the wrong URL
if you are including all the single quotes. It would make the domain look like www.'mysite'.com
instead of www.mysite.com
. So the inconsistency of concatenation makes the URL
look like it’s an invalid URL
. Whoever wrote that part really doesn’t know how to concatenate properly. This is why I dislike people using concatenations because they bring in both single quotes and double quotes and have no clue which ones they are using anymore since it’s all spaghetti after that.
Quite frankly, I don’t know why the INDENTING got messed-up like that when copy-pasting to this forum. I have screen shot my notepad++ on spots where you say the indentation was wrong. Have a look. I’ll even attach the files and notice the prepared statements on the latter file because I’d appreciate your feedback if there is anything missing or wrong.
You’ll also notice the indentations are correct. This forum for some reason messes things up during code copy pasting.
register_editing.php (8.1 KB)
activate_account_edited.php (3.7 KB)
I guess, it’s my mistake then for making it a spaghetti and a noodle and a hotch potch aswell as a porridge! Lol!
I thought, when you mention a sanitized input then you add the single and double quotes to prevent sql injection on variables. Is it not that the case ?
Anyway, I’ve attached my full scripts to droopsnoot’s reply. No good attaching the same again here and wasting forum webspace. If you have the time, then do you mind having a look at them 2 files and making amendments wherever you deem I went wrong along with comments and then re-attach it here ? I don;t mind if the public get the scripts. I want newbies to learn from your contributions.
Thanks in advance for your time and support!
It isn’t the forum. And it is something that will plague you when you open files in different apps until you understand the cause.
It is the old “indent with spaces vs indent with tabs” problem.
You have your editor set so that a tab is displayed as 3 spaces. Other apps, such as this forum, may, and often do, have tab characters display as different numbers of spaces.
Without going into a debate about which is best, IMHO the main thing is to be consistent in how you indent. Spaces or tabs, pick one and try to not mix them in your code.
Friends,
You may remember that, I was building a member registration and login script few weeks ago.
I am now continuing it.
It has registration.php, login.php and account_activation.php.
So, when a user registers, the users tbl in the database holds the value “0” in the “account_activation” column and holds the “account activation random numbers (hashed)” as part of the account activation link.
User, then gets emailed a link (account activation link that contains the random numbers) to click to confirm his email and activate his account. When the user clicks this account activation link, the “account_activation.php” script gets triggered and takes-over.
That script, first grabs the user’s “email” and “account activation random numbers” details (GET Method) and checks them both against the “users” tbl. If it finds a match then it activates the account and creates a session. Names the session under the username. Then, redirects the user to his account homepage. He no longer needs to type his username and password to login as he is auto logged-in the very moment he clicks the link and activates his account.
This is very basic and standard stuff.
I am providing below the account_activation.php. I need you to look at it and tell me if I got the PREPARED STATEMENTS (Binding) correct or not. Throughout the code, I have included comments to make it easy for you to understand what I want the next line of codes to do.
Note that, I have a former version of this account_activation.php that is working 100%. However, that former version does not prevent sql injection (makes no use of PREPARED STATEMENTS). Hence, I created this new version withe the PREPARED STATEMENTS. I am not sure if I got the BINDING correct or not. I tried checking how the script is functioning by uploading the db to my website to test it on my website but having problems importing it to my website. Originally, I created this script and tested it on xampp. hence, the database and tbl is on xampp. I opened a ticket with my webhost for them to upload the db to my website. In the meanwhile, while I wait for their reply, we might aswell check the script and correct any errors. What do you say ?
Thanks for your help. Any code suggestions are welcome.
<?php
session_start();
include 'config.php';
//Grab User's (account activator's) email and account activation code from account activation link's url. Check for email and account activation code details in the account activation link's url.
if(!isset($_GET["email"], $_GET["account_activation_code"]) === TRUE)
{
$_SESSION['error']="Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
exit();
}
else
{
$confirming_email = trim(mysqli_real_escape_string($conn,$_GET["email"])));
$account_activation_code = trim(mysqli_real_escape_string($conn,$_GET["account_activation_code"])));
/*
Check User's Confirmed Email and Account Activation Code against the "users" tbl to see if it has already been registered or not.
Do this by selecting the Confirmed Email and Account Activation code to check against Mysql DB if they match or not.
*/
$stmt = mysqli_prepare($conn, "SELECT emails, accounts_activations_codes FROM users WHERE emails = ? AND accounts_activations_codes = ?");
mysqli_stmt_bind_param($stmt, 'si', $confirming_email, $account_activation_code);
mysqli_stmt_execute($stmt);
/*
If the account activation code matches with the confirming Email in the same row in the MySql DB then check if user has already activated his account or not.
Check if the associated row is 0" or "1". Must be "0" to indicate account activation is pending.
*/
if (mysqli_stmt_insert_id($stmt))
{
while($row = mysqli_fetch_assoc($result))
{
$db_username = $row["usernames"];
$db_confirmed_email = $row["emails"];
$db_account_activation = $row["account_activations"];
//If "account_activation" row shows "not equal to 0 (is: 1)", then show error indicating account has already been activated. Then re-direct user to Log-in Page.
if($db_account_activation != 0)
{
echo "<script>alert('Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login!')</script>";
echo "Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login from <a href=\"login.php\">this webpage</a> next time! Make a note of that webpage, ok ?";
$conn->close();
}
else
{
//Dump the account confirming User's details onto the same row in the "users" table.
if (mysqli_stmt_insert_id($stmt))
{
// Are lines 42 to 48 (next 5 lines) really necessary ?
$stmt = mysqli_prepare($conn, "SELECT usernames, emails, account_actvations FROM users WHERE usernames = ? AND emails = ? AND account_activations_codes = ?");
mysqli_stmt_bind_param($stmt, 'ssi', $username, $email, $account_activations_code);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
// Update 'account_activation' row to '1' to indicate account and email has now been confirmed.
$stmt = mysqli_prepare($conn, "UPDATE users SET account_activations = ? WHERE emails = ? AND account_activation_codes = ?";
mysqli_stmt_bind_param($stmt, 'isi', 1, $db_confirmed_email, $account_activations_code);
//Execute the statement.
mysqli_stmt_execute($stmt);
//If statement execution a success then create a session under the user's Username.
if (mysqli_stmt_insert_id($stmt))
{
echo "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> Redirecting you to the login page ...</h3>";
$_SESSION["user"] = $db_username;
//Redirecting the newly account activated user to his/her account homepage by identifying the user by his/her session name (username).
header("location:home.php");
}
}
}
}
}
else
{
//Give error that this email address (from where the user is clicking the account activation and email confirmation link) is not pending registration. Provide the unregistered user the registration link.
echo "<script>alert('Invalid Email Address or Invalid Account Activation Link! This Email $confirming_email was not pending registration with this Account Activation Code $account_activation_code! Try registering an account!')</script>";
echo "Invalid Email Address or Invalid Account Activation Link! This Email $confirming_email was not pending registration with this Account Activation Code $account_activation_code!
Try registering an account if you have not already done so! <a href=\"register.php\">Register here!</a>";
$conn->close();
exit();
}
}
?>
Also, uploading in this post the script. Incase, you want to download it and test it on your computer/server.
activate_account_edited.php (4.6 KB)
Instead of writing a wall of code, you should do only one thing at a time.
And verify the result.
And proceed further only if the result is correct.
this way you can be sure that all your code is correct.
Your current code goes astray quite early, and it is your job to detect this point.
Then you can come here asking how to solve this particular problem.
This way you won’t be a leech, wasting everyone’s time to review a deliberately not working code. And also you will save yourself from a waterfall of [sometimes contradicting and irrelevant] suggestions, in which you would drown, unable to tell essential ones from the pointless nitpicking, and no doubt overlooking some of them, making you deliberately go back over and over asking the same question again.
Remember - one thing at a time.
So start writing in iterations.
Turn on your xampp server and go.
Begin form the checking the User’s Confirmed Email and Account Activation Code.
Does this query return the desired result to you?
You don’t mention the first, most important point - does it actually work, or are you having problems with it? If you are having problems, what are they?
This line of code
if (mysqli_stmt_insert_id($stmt))
doesn’t make any sense to me. The documentation says “Get the ID generated from the previous INSERT operation”, but you don’t have a previous INSERT operation. Then once you’ve found a matching user account, you call it again for some reason, even though you still don’t have an INSERT operation on the go. The doc doesn’t actually say what happens in these circumstances, but I’d think there are better ways to check whether the statement executed.
Ok. Thanks for pointing-out my mistakes droopsnoot!
This code that I uploaded, I don’t know if it is working or not because the xampp does not SENDMAIL. Therefore, tried uploading everything to my website but the php myadmin keeps showing errors while trying to upload the db & tbl to my website. Therefore, could not check on my website if the script is working or not. That’s why I wanted you guys to have a look and let me know how I did on the PREPARED STATEMENTS. It is that, which I am not sure if I got correct.
Like I said in my previous post. I did create another version first but that did not have the PREPARED STATEMENTS and did not prevent sql injection. Else, that script worked as I managed to test it on my site. But that script’s tbl was different and this one’s is different. Hence, I cannot run this new script on the old working script’s db & tbl on my website.
I only made my previous post once I came to a dead-end.
Webhost now gave instructions but did not work. Asking for support again.
The new script’s tbl is really long, that I built on xampp. Don’t want to be writing 30-40 columns again on the online tbl. Therefore, trying to upload the old one I created on xampp but coming across errors. If I can sort this problem out then I can test the new script where it is fumbling. Right now, I’m in the total dark as I am unable to test it on my website due to this problem I am facing.
Anyway, you said you can code it a better way. So, what better way would you code it ? Do you mind showing a sample ? I did my best. I will try googling for code examples now but they might be no good as internet is full of crap and faulty codes. Therefore, want to see your solution first.
Most scripts I come across on Google are pdo and oop style that show examples of member reg & log-in sites. And my scripts are mysqli_ procedural style as I am learning that first due to all beginner tutorials on php being in that style. Therefore, the code examples I had found were useless to me.
If you guys ever come across a tutorial (text) that shows how to build a member reg & login site (procedural style using mysqli_ extension) then do let me know and I will try learning the PREPARED STATEMENTing from there. It has to show how to send email confirmation/account activation link and what actions would be triggered when that link gets clicked.
FYI, I have read on PEPARED STATEMENTS but as you know, whatever you learnt from the tutorials is not always enough to do the job. Like in this case.
Thanks!
What is the point of posting code if you don’t know whether it works or not? If you want people to help at least have the courtesy of checking what errors you get. How are you ever going to learn PHP if you go at everything half-cocked?
Look how droopsnoot pointed-out. That is how.
And like I said, I can’t test the script unless my site is co-operating. That is being dealt with. And I can’t test it on localhost as localhost does not send email. So, what other options do I have then get php experts check it out ? That is what I am doing.
When my site starts co-operating, I can test it on my site and see whether the code is working or not. I won’t need to bother anyone in the forum on that particular subject. Until then, I can’t test it. I am at a dead end, as of now.
Have you made the improvements/corrections suggested here? http://forums.devshed.com/php-development/977810-improvements-regsitration-site-reg-php-post2978305.html#post2978305
This is the first thing you should fix. You mentioned xampp earlier as the reason but xampp is not relevant when it comes to sending emails. Unless your development machine is not connected at all to the internet then email should work fine. It is just a question of setting up your ini files. Lots of examples.
If you want to send emails from XAMPP you have two options. 1. Configure Mercury so it can send emails direct from your localhost; or 2. Use PHPMailer or SwiftMailer instead of PHP’s mail() function. I wouldn’t recommend the first option.