PHP and Javascript - Problems with undefinded variable - javascript

Hey guys i am very new to this so i am sorry if there is just something completely stupid i am missing here. I have the following Sign Up Form. And in the URL http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de i am trying to submit the value e. However, in all cases e is simply empty or undefined:
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$p = $_POST['p'];
$e = $_GET['e'];
echo "test";
echo "$e";
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM team WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "UPDATE team
SET username='$u',password='$p_hash',ip='$ip',signup=now(),lastlogin=now(),notecheck=now()
WHERE email='$e'";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>yoursitename Message</title></head>
<body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">
<div style="padding:10px; background:#333; font-size:24px; color:#CCC;">
<img src="http://www.rockaholics-cologne.de/root/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">Account Activation</div>
<div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
I do get new entries into the database when i fill out the form. But it does neither send me an email or UPDATE the database at the specified email. It simply updates all the entries with a blank email. The echo "$e" within the script also return nothing.
I used this code to check:
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
$e = $_GET['e'];
echo "$e";
?>
And in this case it does return an array with [e]=cataras#gmx.de and it also prints out $e. But why doesnt it work in the other skript? I'm using the exact same methods to get e from the URL.
When i run my Javascript function:
function signup(){
var u = _("username").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, "") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&p="+p1);
}
}
I get Uncaught ReferenceError: e is not defined. And the site stops at "please wait...". I just took out the +e+ in the js to get to the php above. Sorry for the long post but i am really running out of ideas. THANKS in advance!!!

I think $_GET['e'] is not working in your original script because it's not getting passed to that processing script from your form page. I accessed the URL you provided (http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de). Note that when you submit your form, the value of "e" in your URL is not being passed to whatever is processing your script. In your form, you need to either do this:
<form action="{yourscripturl}?e=<?php echo $_GET['e']?>" {rest of form tag}>
Or, add a hidden to hold the value of "e", and then use $_POST['e'] on your processing script instead of $_GET['e'].
<input type="hidden" name="e" value="<?php echo $_GET['e']?>" />

Related

alert not popping up in php

In a particular php file iam using a header and an alert box before it executes header, but its neglecting alert and executing header directly..!!please help me resolving this...!!pardon if i went wrong somewere.
.php
<?php
header('location: formprofile.php');
session_start();
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['salutation']) && !empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['dob']) && !empty($_POST['mobile']) && !empty($_POST['country']) && !empty($_POST['state']) && !empty($_POST['city']) && !empty($_POST['pin'])){
/*
if required include seperate validation
for some fields which require validation
*/
// receiving the post params
$salutation = ($_POST['salutation']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$dob = trim($_POST['dob']);
$mobile = trim($_POST['mobile']);
$country = trim($_POST['country']);
$state = trim($_POST['state']);
$city = trim($_POST['city']);
$pin = trim($_POST['pin']);
/*
validation process
starts from here
*/
// validate your email address
if(strlen($mobile) == 10){
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
}else{
// create a new user
$user = $db->storeUser($salutation, $fname, $lname, $dob, $mobile, $country, $state, $city, $pin);
if ($user) {
// user stored successfully
$response["error"] = false;
$_SESSION['fullname'] = $user['fullname'];
$_SESSION['vault_no'] = $user['vault_no'];
$message = "Registration successful";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}else{
//invalid mobile number
$response["error"] = true;
$response["error_msg"] = "PLEASE ENTER VALID MOBILE NUMBER!";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
header('location: formprofile.php');
This line is redirecting the page to formprofile.php and that causes to ignore everything below it. Just remove that line or if you want redirect after execution, then move it to the end of the file and do not echo or print anything before it.
But if you want to have some alert before redirecting to other page don't use header() for redirect. Add this JavaScript at the end of the file.
?>
<script>
alert("your message");
document.location = "formprofile.php";
</script>

Popup alert script in a php file [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.
But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">alert("Please enter valid username and password");</script>';
header("location:index.php");
}
?>
//login.php
<?php
$username = "exampleuser";
$password = "examplepass";
$host = "localhost";
$dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("database_name", $dbHandle);
$myUserName = $_POST['user'];
$myPassword = $_POST['pass'];
if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
$query1 = "SELECT * FROM users WHERE username='$myUserName'";
$result1 = mysql_query($query1);
$count1 = mysql_num_rows($result1);
if($count1 == 1){
$query2 = "SELECT password FROM users WHERE username='$myUserName'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if(password_verify($myPassword, $pass)){
$seconds = 120 + time();
setcookie(loggedIn, date("F js - g:i a"), $seconds);
header("location:mysite.php");
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
?>
If you send headers to php it goes directly on index.php after the page goes in your condition.
If you try this code:
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.
EDIT 1:
Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.
Here's the code.
<?php
//login.php
//connection via PDO
try{
$pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//alert errors and warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('Database Error.');
}
//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;
if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
$query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
//bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
$query1->bindParam("username_param", $myUserName);
$result = $query1->fetch();
// or you can do $result = $query1->fetchColumn(); to get directly string instead of array
if($result['password']){
//you should use password_verify() if you have an hash stored in database, you should not save password in database.
//please google about best practice storing password, it's full of beautiful guides
//bad practice but will do the work
if($myPassword == $result){
$seconds = 120 + time();
setcookie('loggedIn', date("F js - g:i a"), $seconds);
header("location:mysite.php");
}else{
printAlert("Password incorrect");
}
}else{
printAlert("Username not valid");
}
}
else{
printAlert("Invalid data");
}
function printAlert($text){
echo "<script language='javascript'>
alert('$text');
window.location.href = 'http://index.php';
</script>";
die();
}
?>

php login form pass vars

i have a page login
in page have html form with textboxes and submit button
and in top of page i have PHP code thet chacke if name and password in database
if name and password in database page go to new page and pass the name and password to next page
i can do it with get metod like the vars in the URL
but i want to pass and go to new page with Post metod
how i can do it??
pleas help me with code....
in code html :
form name="frmlogin"action="<?= $_SERVER['PHP_SELF'] ?>" method="post" >
and in top of the page have PHP code:
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
/*header('Location: YOUR_LOCATION');
exit;*/
$msg = "Username and password match";
echo '<script type="text/javascript">
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
help me to change the javascript window.location to post metod
You can go for php redirect also.
header('location:smartphon100.php?name='. $name .'&password='. $password) ;
BTW: you are passing password in browser?
If I understand correctly, you're trying to redirect a user after successfully logging in.
I see that your current code attempts to redirect using Javascript, the issue seems to be with the quotes on the value you tried to enter.
Try to change this line:
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
to this:
window.location.href = "smartphon100.php?name='.$name.'&password='. $password";
Overall you should read about security as the code you presented is very vulnerable.
PHP: SQL Injection - Manual
If you're trying to pass the values to another page in a POST method using Javascript, you could take a look at this answer:
JavaScript post request like a form submit
Although as I don't see a reason for posting the values more than once,
I recommend you to read about PHP sessions, cookies, and encryption, which allow you to store values that you can use across the website securely.
A simple example to using session:
<?php
//Starts the session, you need to use this line in every PHP file that'll need to access session variables
session_start();
$_SESSION['user'] = "Donny"; //Storing a user name
?>
A simple example of session use with your code:
Foo.php
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['user'] = $name;
$_SESSION['pass'] = $password;
$msg = "Username and password match";
echo '<script type="text/javascript">window.location.href = "smartphon100.php";</script>';
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
Bar.php
<?php
session_start();
//Accessing the values:
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>
NOTE:
It's not good to store values like that as again, they're not secure, please read about hashing passwords.
PHP: Password Hashing

Modifications to a php form

Beginner in php here.
I have the following form script:
<?php
if (isset($_POST['name']) && isset($_POST['email']) && isset($_FILES['uploaded_file']['name'])) {
$db_name = "xx";
$server = "localhost";
$DBuser = "xxx";
$DBpass = "xxxx";
$name = $_POST['name'];
$email = $_POST['email'];
$file = "Imagini_lume/" . $email . ".jpg";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Adresa de e-mail este incompleta!";
} else {
$name = trim($name);
if ($name != '') {
$temp_file = trim($_FILES['uploaded_file']['name']);
if ($temp_file != '') {
// here
mysql_connect($server, $DBuser, $DBpass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
// check for existing
//$result = mysql_query("select email from Emails where email='$email'") or die(mysql_error());
$data = mysql_fetch_array($result);
if ($data == null) {
mysql_query("insert into Emails (Email,Full_Name,Image) values('$email','$name','$file');") or die(mysql_error());
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file)) {
//sucess
} else {
echo "Eroare incarcare imagine!";
}
// email sending
sendEmail("xx#gmail.com", getContent($name, $email, $file));
echo "Sucessfull!";
//} else {
//echo "Adresa de e-mail este folosita de cineva.";
}
} else {
echo "Trebuie sa selectati desenul dvs.!";
}
} else {
echo "Introduceti numele complet!";
}
}} else {
echo "Va rugam sa completati spatiile de mai sus!";
}
Note: if (isset($_POST['name']) && isset($_POST['email']) && isset($_FILES['uploaded_file']['name'])) { and } else {
echo "Va rugam sa completati spatiile de mai sus!";}
are on different lines than stated above. I only added that way so I can include all script inside the "code sample".
The questions are:
If the user uploads several files using the same name and e-mail address, the files will overwrite and I would like to differentiate the files (e.g. "name#email.com1.jpg","name#email.com2.jpg" and on).
I already found the script but being a beginner, I don't know where to insert the following code (another note- I don't know if it's the full code or some script is missing):
while(file_exists($name . $extension)) {
$name .= '1';
}
I would like to "oblige" the user to type it's full name. Due to design reasons I have only one "Full name" text box and I would like to force the user to type at least 2 words (first and last name) - basically a word minimum nr, not characters nr. Again, I have found a code, but still, I don't know how to apply it to my code, where to insert it:
if ($("#et_newpost_content").text().split(/\s+/).length < 250) {
alert('Message must be at least 250 words.')
}
Please advise.
Ok, it's quite simple. The first script to increment the image name counter is quite simple to implement:
1)
$db_name = "xx";
$server = "localhost";
$DBuser = "xxx";
$DBpass = "xxxx";
$name = $_POST['name'];
$email = $_POST['email'];
// Now checking the name existence
// Defining the initial state: the format is: my#email.com + counter + extension
// i.e. my#mail.com1.jpg
$ext = ".jpg";
$count = 1;
$base_file_name = "Imagini_lume/" . $mail;
// while already exists a file name like that, increment count
while (file_exists($base_file_name.$count.$ext))
$count++;
// finally define the official name of the file!
$file = $base_file_name.$count.$ext;
2) the code you wrote is javascript (jquery), not php... If you want to check the parameter server side you can use filter_var:
if (filter_var($name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[A-Z][a-z]* [A-Z][a-z]*/"))) === FALSE)
die("Error: You should enter your complete name. i.e. John Black");
(take a look to regular expression chapter on the php guide)
Finally, please don't use that code in a real web application. As it's written, it's not safe on SQL injection attacks:
SQL Injection
Moreover you are not checking the correctness of each user input parameter. Take your time to make some experience ;)

Registration Form (HTML, PHP & MySQL) redirect after error or missing values

I am new to development with HTML, PHP, CSS etc.
I need to do this small Registration and Login Form. I haven't gone into detail in Object-Oriented PHP and I'm working in the simplest manner as this task needs to be done in a short time and I've only been coding and experimenting with these languages these past two days.
What I already have is a working Registration and Login forms that when they are submitted the information is posted to another php file. Than it verifies that the data has been entered and that the e-mail isn't already used. What i need is that when either the e-mail is already used and when a field is left empty that it automatically goes back to Registration/Login forms and displays a message with their respective errors.
I know this might have been done in a different way but the deadline is really close and so i need a solution that works with what I already have.
I'm sorry if a similar question is already available, but i might be using incorrect keywords to search for the solution.
Keywords currently that I'm using are Redirection, "Going back to previous page".
If JavaScript is more suitable for this kind of operation it is also excepted and would like this to be pointed out, although a php solution would be appreciated a bit more as i currently obtain more knowledge on PHP than on JavaScript.
Thanks, any help or directions to suitable solutions would be mostly appreciated.
You can use
A) PHP header() function
B) echo a META HTTP - EQUIV=" refresh "
CONTENT=" seconds; URL = \the-other-url">
C) Use JS like this but you
will need to set a timeout
Example:
if (empty ($_POST ['username']) || empty ($_POST ['password']))
{
echo "Please enter a username, or password";
header ("refresh:5; url=back.php");
exit;
}
There are many different ways to do this. If when the form is submitted your executing the code on a different php file then you could have an IF statement there which redirects the headers back to the form page if there are errors with the users input such as:
if($username == "")
{
header("Location: YOUR_FORM_PAGE.php");
}
Hope this helps.
To add the execution to the same page you can do this.
add these buttons;
<input type="hidden" id="submitted" name="submitted" value="1">
<span class="label"></span><input type="submit" class="submit" value="Submit"><input type="reset" class="submit" value="Clear">
set the form action to the form page. Add this to the top of the page and add any PHP you want to it;
if(isset($_POST["submitted"]) && $_POST["submitted"] == 1)
{
for example;
if($from_fullname == "")
{
$submission_status = '<div class="vpb_info" align="left">Please enter your fullname in the required field to proceed. Thanks.</div>';
}
and add this to the page where you want the error displayed;
<p> <?php echo $submission_status; ?></p>
Sounds like http-redirect (http://php.net/manual/en/function.http-redirect.php) should help you out. You can redirect on your error conditions with that.
Update
With redirect you can attatch QueryString Parameters so you could redirect back to the login.php page with an errror code and/or message as a query string perameter.
These will get you started, a registration or signup php file and a login php file I made once
(personal info is faked).
SignUp.php
<?php
session_start();
$name = $_REQUEST['name'] ;
$userpassword = hash('sha512',$_REQUEST['password'] );
$signature = $_REQUEST['signature'] ;
$image = $_REQUEST['image'];
$email = $_REQUEST['email'] ;
$emailreplies = $_REQUEST['emailreplies'] ;
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query=sprintf("SELECT Name FROM users WHERE Name LIKE '%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
$_SESSION['NameTaken'] = true;
$_SESSION['UsedName'] = $name;
$_SESSION['UsedEmail'] = mysql_result($query,0);
header("Location: SignUp.html");
}else{
$query=sprintf("SELECT Email FROM users WHERE Email LIKE '%s';",
mysql_real_escape_string($email));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$_SESSION['EmailTaken'] = true;
$_SESSION['UsedEmail'] = $email;
header("Location: SignUp.html");
}else{
$query = sprintf(" INSERT INTO users VALUES (
NULL , '%s', '%s' , '%s', '%s', '%s', CURRENT_TIMESTAMP , 0, $emailreplies);",
mysql_real_escape_string($name),
$userpassword,
mysql_real_escape_string($signature),
mysql_real_escape_string($image),
mysql_real_escape_string($email));
mysql_query($query);
$query = sprintf("SELECT JoinDate FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$vcode=md5(mysql_result(mysql_query($query),0));
mysql_close();
require_once "Mail.php";
$from = "PocketWoods Hunting Hall<pwoods#email.com>";
$to = $email;
$subject = "Welcome to Motes Blog";
$body = "<html>
<body>Thank you for your time. <br/>
To ensure a human made this account and not an
automated process please click the link below:<br>
<a href=\"http://site.com/MotesBlog/verifyaccount.php?vcode=".$vcode."&name=".$name."\">
Activate Account
</a>
</body>
</html>";
$host = "mail.root.com";
$username = "root#root.com";
$password = "root";
$headers = array ( 'From' => $from,
'To' => $to,
'Subject' => $subject,
'MIME-Version' => "1.0",
'Content-type' => "text/html; charset=iso-8859-1");
$smtp = Mail::factory('smtp',
array ( 'host' => $host,
'auth' => false,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
header("Location: success.html");
}
}
}
?>
Login.php
<?php
session_start();
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$user_name = $_REQUEST['name'];
$user_password = $_REQUEST['password'];
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
if(isset($_SESSION['User'])){
if( ($_SESSION['CreatedTime'] + 3600) < time() ){
$_SESSION['Expired'] = true;
}
unset($_SESSION['User']);
}
$query = sprintf("SELECT Password FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$real_password=mysql_result($query,0);
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
$email = mysql_result($query,0);
if($real_password == hash('sha512',$user_password)){
$query = sprintf("SELECT Validated FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
mysql_close();
if(mysql_result($query,0)){
$_SESSION['User'] = $user_name;
$_SESSION['CreatedTime'] = time();
setcookie("User", $_REQUEST['name'], time() + 60*60*24*365);
header( "Location: MotesBlog.php" );
}else{
$_SESSION['resend_name'] = $user_name;
$_SESSION['resend_email'] = $email;
$_SESSION['NotValidated'] = true;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongPW'] = true;
$_SESSION['UsedEmail'] = $email;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongName'] = true;
header( "Location: MotesBlog.php" );
}
}
?>

Categories

Resources