Value already exist in mysql database and php - php

I have the code below to check on (a web registration form) whether the e-mail address is already exist in the db or not
It works good, it shows the e-mail already exist once i load the page. but it keeps process the form and input the same e-mail into the mysql database?
How can i stop the form from submitting if the e-mail address is already exist?
my code below:
$email = $_POST["email"];
$query = mysql_query("SELECT * FROM users WHERE email='$email'");
if(mysql_num_rows($query) != 0)
{
echo "email already exists";
}

A good idea is to run an AJAX check prior to posting the form, ie in the client form verification state. Hence the user will know before posting the form that email is already added...
An AJAX solution would be:
On the FORM page, having an jQuery function similar to this:
Add jQuery with the validator plugin:
<script type="text/javascript" src="/js/jquery.1.7.2.min.js"></script>
<script type="text/javascript" src="/js/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery.validator.addMethod("emailunique",function(value){
return eval($.ajax({
url: 'phptocheckunique.php',
data: "email="+value,
type: 'post',
async: false
}).responseText);
}, 'Email address already exists, must be unique!');
$(function() {
$('#yourform').validate();
});
</script>
Then in your form add the classes to the email input field:
<input type="text" name="email" value="" size="30" class="required email emailunique" />
Then make a separate PHP-script just for checking the DB (mail-address posted with $_POST['email'], similar to your above function (BUT SECURE!) that returns TRUE if there is an email already.
phptocheckunique.php:
<?php
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$sth = $dbh->prepare("SELECT FROM users WHERE email = ?");
$sth->execute(mysql_real_escape_string($_POST['email']));
if ($sth->rowCount() > 0):
return true;
else:
return false;
endif;
But if you still use your method, add an ELSE statement in the last if routine, then you will only add the person if email is unique... Also your code is very unsecure, you should consider using PDO.

You probably don't want to stop the form being submitted as such, but rather have the form submitted, run the check (as your code does) and if there is a match, redirect the user back to the form page along with an error message telling them the email address already exists.
That way the form will be submitted - but not processed into the database until the email address is unique.
To borrow from your code:
$email = $_POST["email"];
$query = mysql_query("SELECT * FROM users WHERE email='$email'");
if(mysql_num_rows($query) != 0)
{
echo "email already exists";
// redirect back to form and populate with
// data that has already been entered by the user
}
else
{
// insert form contents into the database.
}
On that note, your code is rather vulnerable to injection attacks. You should switch to PDO or mysqli prepared statements when processing form data like this.

if(mysql_num_rows($query) != 0)
{
echo "email already exists";
}
else
{
mysql_query($ur_query);
}
Just put the "INSERT INTO ... " query for your database in the else part.

you need to give like this,
if(isset($_POST["email"])
{
$email = $_POST["email"];
$query = mysql_query("SELECT * FROM users WHERE email='$email'");
if(mysql_num_rows($query) != 0)
{
echo "email already exists";
}
}
it will executes after you submit the form.

Related

Random numbers are generated twice when verifying email

I'm new to PHP. I'm currently doing an email validation. My code is supposed to generate a random number, send to user via email and verify it when user enters.
Here is my code:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
session_start();
// initializing variables
$email = $_SESSION ['email'];
$user_code = "";
$errors = array();
// generate a four digit random number
$gen_code = strval (rand (10000, 99999));
// send code to user email
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'register');
// REGISTER USER
if (isset($_POST['email_confirm'])) {
// receive all input values from the form
$user_code = mysqli_real_escape_string($db, $_POST['code']);
// check whether both codes match
if ($user_code != $gen_code) { array_push($errors, "The codes do not match"); }
else {
// set isConfirmed == true
if (count($errors) == 0) {
$query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
mysqli_query($db, $query);
$_SESSION['email'] = $email;
header('location: user_details.php');
}
}
}
?>
Here email_confirm is the name of my submit button and code is the name of text box.
It all works fine when page is first loaded. I get an email with a random integer.
Problem starts when I click my submit button. I receive another email with different number and the number I already entered is not equal to the one I received from email.
Please help
If this is a simpler and an experimental application, you should store gen_code in this session soon after its sent to the user confirmation email. Otherwise, store the code in db and retrieve it when your application receives email confirm POST request and compare the code that was sent by the user against the session or db wherever you'd stored it.
if (isset($_POST['email_confirm'])) {
// receive all input values from the form
$code = $_SESSION['gen_code']; // in case you would wish to store and retrieve code from db, replace this code with one which retrieved from db by email id... SELECT code from user where email=$email
$user_code = mysqli_real_escape_string($db, $_POST['code']);
// check whether both codes match
if ($user_code != $code) {
array_push($errors, "The codes do not match");
} else {
if (count($errors) == 0) {
$query = "UPDATE user_database SET isConfirmed = true WHERE email = '$email'";
mysqli_query($db, $query);
$_SESSION['email'] = $email;
header('location: user_details.php');
}
}
}

How do I add a condition where a certain email and password get redirected to a different page in PHP?

I want to add a condition where if the email is admin#example.com and password is admin, then the admin will be redirected to admin.html, which is different to what a normal user will be redirected to (user.html). P.S. the admin and users are in the same table. Thanks in advance.
<?php
require_once ('../../connect.php');
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
if ($user_email != NULL AND $user_password != NULL)
{
$login = "SELECT * FROM tblusers where user_email = '$user_email' AND user_password = '$user_password' AND user_type=0";
$result = mysqli_query($dbc, $login);
if (mysqli_num_rows($result) >0 )
{
setcookie('user_email', $user_email);
setcookie('user_password', $user_password);
echo '<script type="text/javascript"> window.location ="register.php"; </script>';
}
else
{
echo '<script type="text/javascript"> alert("The email or password you have entered may be incorrect"); window.location ="login.html"; </script>';
}
}
else ($user_email != NULL AND $user_password != NULL)
{
$login = "SELECT * FROM tblusers where user_email = '$user_email' AND user_password = '$user_password' AND user_type=1";
$result = mysqli_query($dbc, $login);
if (mysqli_num_rows($result) >0 )
{
setcookie('user_email', $user_email);
setcookie('user_password', $user_password);
echo '<script type="text/javascript"> window.location ="members.php"; </script>';
}
else
{
echo '<script type="text/javascript"> alert("The email or password you have entered may be incorrect"); window.location ="login.html"; </script>';
}
}
else
{
echo '<script type="text/javascript"> alert("Please enter your email and password in the relative fields"); window.location ="login.html"; </script>';
}
mysqli_close($dbc);
?>
Hmm, your post makes it really difficult to properly provide an answer, but I will try. Before that, know that #RiggsFolly really has made the most important point - get a better tutorial. I would use comments because there are some things that could be clarified but my reputation does not allow me to do that yet. So here goes an attempt at an answer.
What exactly is the logic you are trying to implement? It seems to roughly be:
if (user provides credentials AND credentials exist in database AND credentials are for user_type == 0) {
save credentials;
send user to registration page;
} else if (user provides credentials AND credentials exist in database AND credentials are for user_type == 1) {
save credentials;
send user to members page;
} else {
send user to login page;
}
We can streamline this logic a bit:
if (user has provided credentials) { // if this fails, user is sent to login page
// Now check if credentials exist in database
// Notice I am using comments? Use them to make your code more readable and to better explain what you're doing/what you did!!!
// Query the database only for matching username and password first.
$login = "SELECT * FROM tblusers where user_email = '$user_email' AND user_password = '$user_password'";
$result = mysqli_query($dbc, $login);
// If this returns a match, then check for user_type. Otherwise, prompt user to provide correct credentials.
if (mysqli_num_rows($result) > 0 ) {
// Obtain the results of the query in an associative array so that you can easily access the value of 'user_type'
$row = mysqli_fetch_assoc($result);
// We have confirmed that the credentials exist. So we can save them
// But as RiggsFolly correctly points out, PLEASE look for alternatives more secure than cookies
save credentials;
// Now check the value of user_type and respond accordingly
if ($row["user_type"] == 1) { // admin
send user to admin page; // which seems to be members.php;
} else { // user
// I assume there is no other user_type.
// If there is, make this an elseif statement that checks if user_type == 0
send user to user page; //which seems to be register.php
}
} else {
display message that credentials are incorrect;
send user to login page;
}
} else {
send user to login page;
}
Again, read ALL the links provided by #RiggsFolly and implement them. As he pointed out, we try to improve your code not to write it for you, which is why I tried to stick to the code you provided.
I do hope this helps you. Wish you the best as you learn.

Login Validation - Database populates all data except email and doesn't throw any errors

I'm so close to completing the login/registration section of my site but I've got some bugs that don't show up in error_log or anything.
About an hour ago, the script worked for the most part. It would validate, insert into/check database, and redirect to index.php (located in user directory along with login and register forms).
Contents of index.php:
/*
If validation script is successful, continue to $destinationUrl, otherwise, go back to try
again. Ultimately, the TRUE statement's output will be the referring page's URL stored as
$_SESSION['Return_Url'] to send users back to where they were, simply as a convenience.
*/
session_start();
if(isset($_SESSION['UserData'])) {
exit(header("location:" . $destinationUrl));
} else {
exit(header("location:" . $loginUrl));
}
That's exactly what I want except one detail: it won't show any user input errors. While trying to fix that, I've managed to screw everything up again and now it still submits data and inserts into the database but doesn't insert $email, and doesn't redirect or anything. On top of that, I don't get any PHP errors so I'm at a loss.
I know the login and registration will work because it did before, but I don't know what I did to cause this issue due to know errors being thrown. I just want the input errors to show up. I'm going to post the original code I copied and edited because what I'm messing with right now is a mess but the validation section is the same.
I did not write these, they were found online after hours of trying script after script. Only this one worked. Therefore, I don't understand exactly what's going on with every part of the script, but I do understand the basic mechanics of what happens, or is supposed to happen as far as validation of input data and adding to/checking data against the database when the form is submitted. The only thing that I have absolutely no idea what and how it works is the output($var) function
Included Scripts
$db= mysqli_connect($dbhost,$dbuser,$dbpwd,$dbase); }
function safe_input($db, $data) {
return htmlspecialchars(mysqli_real_escape_string($db, trim($data)));
}
/*
Currently, I have no idea about JSON or any other languages. Only a decent
portion of PHP, and HTML, of course. Can I just forget this function and use
{return $var;} instead? Because that would make everything so much easier
and I probably wouldn't even be posting these questions... but it's a new
language to me that I couldn't tell you the first thing about.
*/
function output($Return=array()){
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
exit(json_encode($Return));
}
Validation Scripts
(Both scripts are in one file)
<?
require 'config.php';
require 'functions.php';
if(!empty($_POST) && $_POST['Action']=='login_form'){
$Return = array('result'=>array(), 'error'=>'');
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid email address.";
}elseif($password===''){
$Return['error'] = "Please enter password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' AND password='".md5($password)."' LIMIT 1");
if(mysqli_num_rows($result)==1){
$row = mysqli_fetch_assoc($result);
$Return['result'] = $_SESSION['UserData'] = array('id'=>$row['id']);
} else {
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
if(!empty($_POST) && $_POST['Action']=='registration_form'){
$Return = array('result'=>array(), 'error'=>'');
$name = safe_input($db, $_POST['Name']);
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if($name===''){
$Return['error'] = "Please enter Full name.";
}elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid Email address.";
}elseif($password===''){
$Return['error'] = "Please enter Password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' LIMIT 1");
if(mysqli_num_rows($result)==1){
$Return['error'] = 'The email you entered already belongs to an account, please login.';
}else{
mysqli_query($db, "INSERT INTO tbl (GUID, email, password, entry_date) values(MD5(UUID()), '$email', '".md5($password)."' ,NOW() )");
$id = mysqli_insert_id($db);
mysqli_query($db, "INSERT INTO `tbl' (id,name) VALUES('$id','$name')");
$Return['result'] = $_SESSION['UserData'] = array('id'=>$id);
}
output($Return);
}
?>
I'm not sure how I would echo the $Return array values. I tried making a function out of it like so:
function inputErr($Return) {
if($Return['error']!=''){
output($Return);
}
}
but that didn't work either. Is there a special way to echo an array value? Without the index name attached
Also, if you have any ideas why the email $var is not being added to db while everything else is, please, do share! With the script not throwing any PHP errors, I have no idea where to start.

Unable to add user to MySQL database using PHP, error code #1064

UPDATE:
My initial question was regarding an issue with adding a user to the database. It was solved but now I am having trouble logging in (login.php). My database has a current email entry of test#test.com , but when I try to login with this email, it says "Login failed".
I tried to incorporate the initial question's solution into login.php but it seems the code was already present. So I'm stuck... here is my register.php page and my login.php page.
I have a feeling it has to do with :email somehow. What is wrong with my login.php file?
register.php
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
login.php
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retreives the user's information from the database using
// their email.
$query = "
SELECT
email
FROM users
WHERE
email = :email
";
// The parameter values
$query_params = array(
':email' => $_POST['email']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the email
// they entered is not registered.
$row = $stmt->fetch();
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
header("Location: private.php");
die("Redirecting to: private.php");
}
else
{
// Tell the user they failed
print("Login Failed.");
}
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Email:<br />
<input type="text" name="email" value="My Email" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
Thank you!
You can disregard the text below.
OLD QUESTION (for register.php):
I'm trying to create a simple login system for my site, where only an email address is needed for registration/login. The problem arises when I try to add a user to the database using phpMyAdmin, I get an error (more below).
I've successfully created a MySQL database using:
CREATE TABLE `users` (
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
and then on the register.php page I have this code.
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
The problem might be due to this code:
INSERT INTO users (
email
) VALUES (
:email
)
which is the code causing me problems in phpMyAdmin. It gives me this error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':email
)' at line 4
The register.php page is successfully connecting to my DB and is also redirecting me as it should, so I feel the problem is adding the user.
It doesn't look like your INSERT statement is executing the query or assigning the email parameter.
Under
$query = "
INSERT INTO users (
email
) VALUES (
:email
)
";
Add
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: ");
}
I've added/adjusted your code. I've used different placeholder names to make debugging easier
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['email']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter an email.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$checkSQL = <<<SQL1
SELECT
1
FROM users
WHERE
email = :checkemail
SQL1;
$insertSQL = <<<SQL2
INSERT INTO users (
email
) VALUES (
:insertemail
)
SQL2;
try
{
$s_ps = $db->prepare($checkSQL);
$s_ps -> bindValue(':checkemail',$_POST['email'],PDO::PARAM_STR);
$s_ps -> execute();
$checkRow = $s_ps->fetch();
if($checkRow)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$i_ps=$db -> prepare($insertSQL);
$i_ps -> bindValue(':insertemail',$_POST['email'],PDO::PARAM_STR);
$i_ps -> execute();
}
catch(PDOException $ex)
{
die("Failed to run query: ".$ex->getMessage());
}
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
use
":email"
This might work...
The issue is mysql doens't know what :email is... Try...
$email = mysql_real_escape_string($_POST['email']);
$query = "
INSERT INTO users (
email
) VALUES (
'$email'
)
";

Php/sqli executed by referencing the link in a send email function?

So i have this page called unsubscribe_process which when given a url query, e.g. www.example.com/unsubscribe_process.php?passkey=123, it will then find and delete the member using mysqli.
The problem I am having is with my unsubscribe.php page. It includes a form and allows the user to put in their email. The form will be submitted, and then an email is sent to the user linking the unsubscribe_process.php page with the specific query and passkey for that user. The hope would be then the user checks their email and clicks the link and then the unsubscribe_process page would remove them from the database.
Back to subscribe.php page, it has no DELETE slqi function anywhere in it, however somehow the user gets deleted after submitted the form. It seems to execute the www.example.com/unsubscribe_process.php?passkey=123 within subscribe.php, without the user having to click on it in the email.
Here is the function that is executed once a user submits their email:
function sendEmail() {
//enter details into db automatically
$con = #require './../dbcon.php';
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$email = mysqli_real_escape_string($dbConnection, $_POST['email']);
$atIndex = strrpos($email, "#");
$emailindex = substr($email, 0, $atIndex);
if ($email=='')
{
echo "<p>No Username has been specified. Please <a href=http://www.example.com/unsubscribe.php> try again.</a></p>";
}
//check if username exists in database
$result = mysqli_query($DB,"SELECT * FROM members WHERE user='". $emailindex ."'") or die(mysql_error());
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$passkey = $row['confirmcode'];
//if password is set then erase password and send an email to user to update details/create new password.
if ($row['paid'] ==1){
$to=$email;
$subject="Unsubscribe";
$header="from: webmaster#example.com";
$message.="You can now unsubscribe yourself in one click with the following link: \r\n";
$message.="http://www.example.com/unsubscribe_process.php?passkey=$passkey\r\n\r\n";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail){
echo "</br><p class='maintextSubmit' align='center'> Please check your email to complete the process.</p>";
}
else echo "</br><p class='maintextError' align='center'> An error occurred. Please try again.</p>";
}
mysqli_close($DB);
}
}
}
SO: Does php execute the link for me when sending the email? This is literally the only reference to the unsubscribe_process.php page anywhere on the subscribe.php page. Why does the unsubscribe_process.php?passkey=$passkey get executed when the email is sent? How can I prevent this from happening (aka only when the link is clicked via the email)? Am I missing something?

Categories