Jump to content

PHP inside variable to echo HTML?


jamesjmann

Recommended Posts

I'm redoing my login script using functions and a basic switch function checking against a $_GET variable (hope you guys know what I'm talking about).

 

What I want to do is create two functions:

 

1 that displays the login form

and 1 that processes the information

 

The form tag would look like this:

<form action=\"<?php $_SERVER['PHP_SELF']?>?action=process\" method=\"post\">

</form>

 

Here's my switch statement:

<?php

//****************************************
//****************Action******************
//****************************************

switch ($_GET["action"]) {
default:
case "index":
	if (!$_SESSION["member"]) {
		if (!$timeout) {
			display_form();
		} else {
			echo $timeout_error;
		}
	} else {
		echo "You are already logged in.";
	}
	break;
case "process":
	if (!$_SESSION["member"]) {
		if (!$timeout) {
			process_form();
		} else {
			echo $timeout_error;
		}
	} else {
		echo "You are already logged in.";
	}
	break;
}

?>

 

This runs as soon as "login.php" loads.

 

It'll automatically run the commands under case "default" and "index". It'll first check to see if the member's logged in. If not, it'll then check to see if "$timeout" is true ($timeout becomes true if the member has attempted to login 5 times and failed). If not, it'll display the login form, by running "display_form()".

 

Once the form has been filled and submitted, the commands under case "process" will be performed. Again it will first check to see if the member's logged in. If not, it'll check to see if "$timeout" is true. If not, it'll start validating the forms.

 

For the validation, I've created a variable called "$errors_found", and scripted one if statement checking to see if the email and password exist. If so, the variables "$rm_field_un" and "$rm_field_pw" become true, as well as "$errors_found".

 

So, back to submission of the form...

 

If "$errors_found" is true, display the form (when the form is displayed, there will be an if statement within that says "<?php if ($rm_field_un) { echo "Username is wrong."; } ?>", which will be displayed right underneath the username field and label. Same with the password elements). If "$errors_found" is not true, go ahead and register the member.

 

Now, here's where I need help, because I'm really confused as to how to accomplish this.

 

The "display_form()" function will contain a single variable called "$login_form". It will contain a value of the HTML constructed login form, and the function will return the variable.

 

Remember how I stated in the third paragraph up that I will have <php> statements within the form which would display errors if necessary? Well, how do I put those if statements within the HTML, which is contained within the variable?

 

If that last question confuses you, allow me to present you with an instance:

<?php

function display_form() {
$login_form = "
<form name=\"login_form\" method=\"post\" action=\"<?php $_SERVER['PHP_SELF']?>?action=process\">
Username:
<input type=\"text\">
<?php if ($rm_field_un) { echo "Username is wrong"; } ?>
";

return $login_form;
}

?>

 

See what I mean?

 

This code confuses me ALOT. I'm not sure if the <php> tags are needed as it is already contained within existing ones, or what. Can somebody please help me out?

 

Any and all help is much appreciated. =D

Link to comment
Share on other sites

You're already inside a block of PHP code started be "<?php", so you don't need the second "<?php". The correct way of doing what you want is

<?php
$login_form = "
<form name='login_form' method='post' action='{$_SERVER['PHP_SELF']}?action=process'>
Username:
<input type='text'>";
?>

But you don't even need "{$_SERVER['PHP_SELF']}", since an empty action makes the form get processed by the same script:

<?php
$login_form = "
<form name='login_form' method='post' action='?action=process'>
Username:
<input type='text'>";
?>

 

I'm not sure what you're trying to do with this line

<?php if ($rm_field_un) { echo "Username is wrong"; } ?>

since it's meaningless in the context of the function.

 

Ken

Link to comment
Share on other sites

You're already inside a block of PHP code started be "<?php", so you don't need the second "<?php". The correct way of doing what you want is

<?php
$login_form = "
<form name='login_form' method='post' action='{$_SERVER['PHP_SELF']}?action=process'>
Username:
<input type='text'>";
?>

But you don't even need "{$_SERVER['PHP_SELF']}", since an empty action makes the form get processed by the same script:

<?php
$login_form = "
<form name='login_form' method='post' action='?action=process'>
Username:
<input type='text'>";
?>

 

I'm not sure what you're trying to do with this line

<?php if ($rm_field_un) { echo "Username is wrong"; } ?>

since it's meaningless in the context of the function.

 

Ken

 

Thanks for clarifying that!

 

The if statement checks to see if variable "$rm_field_un" is true. "$rm_field_un" becomes true if the username does not exist in the database. So if it is true, in the form under the field "username", it'll display an error message saying, "Your username was incorrect." or "The username you entered does not exist."

 

Does that make sense? It's really confusing. My head goes in circles when I think about it haha.

Link to comment
Share on other sites

<?php

//****************************************
//***************Includes*****************
//****************************************
//Connects to database
include "connect.php";

//Selects database
include "select.php"; 

//****************************************
//****************Action******************
//****************************************

switch ($_GET["action"]) {
default:
case "index":
	if (!$_SESSION["member"]) {
		if (!$timeout) {
			display_form();
		} else {
			echo $timeout_error;
		}
	} else {
		echo "You are already logged in.";
	}
	break;
case "process":
	if (!$_SESSION["member"]) {
		if (!$timeout) {
			process_form();
		} else {
			echo $timeout_error;
		}
	} else {
		echo "You are already logged in.";
	}
	break;
}

//****************************************
//***************Functions****************
//****************************************
//........................................
//........Function 1: display_form()......
//........................................
function display_form() {

global $mysql_connect;

echo "
<form name=\"login_form\" action=\"?action=process\" method=\"post\">";
if ($rm_field_un || $rm_field_pw) { 
echo $rm_errors_msg; 
}
echo "<label for="username">Username: </label>
<input type=\"text\" name=\"username\" id=\"username\" value=\"$rm_username\">
<label for=\"password\">Password: </label>
<input type=\"password\" name=\"password\" id=\"password\">
<a href=\"../fans/forgot_password.php\">Forgot Password?</a>
<input type=\"check\" name=\"rememberme_check\" id=\"rememberme_check\" CHECKED>
<label for=\"rememberme_check\">Remember me for: </label>
<input type=\"text\" name=\"rememberme_days\" id=\"rememberme_days\" value=\"$rememberme_days\">
 days
<input type=\"hidden\" name=\"ip\" id=\"ip\" value=\"";
echo $_SERVER["REMOTE_ADDR"];
echo "\">";
<input type=\"hidden\" name=\"date\" id=\"date\" value=\"";
echo date('F d, Y');
echo "\">;
<input type=\"hidden\" name=\"time\" id=\"time\" value=\"";
echo date('g:I:sa');
echo "\">";
echo "<input type=\"submit\" name=\"submit\" id=\"submit\">
<input type=\"reset\" name=\"reset\" id=\"reset\">
";
}

//........................................
//........Function 2: process_form()......
//........................................
function process_form() {

global $mysql_connect;

//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
//,,,,,,,,,Validation,,,,,,,,,,
//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
//When user has failed to login 5 times, a cookie will be created that won't allow them to login until the cookie has expired
//In this case, it's 24 hours
if ($_SESSION["max_tries"] == 5) {
	setcookie ("timeout", "timeout", time() + 86400, ".djsmiley.net");
}

//While the cookie exists, their timeout exists
while ($_COOKIE["timeout"]) {
	timeout = true;
}

//Check database to see if both username and password are correct
$rm_cl_sql = "SELECT * FROM fans WHERE username = '$rm_username' and password = '$rm_password'";
$rm_cl_result = mysql_query($rm_cl_sql);
$rm_cl_count = mysql_num_rows($rm_cl_result);

//If username and password do not match...
if (!$rm_cl_count) {
	$rm_errors_found = true;
	$rm_field_un = true;
	$rm_field_pw = true;
} else {
	$rm_errors_none = true;
	$rm_field_un = false;
	$rm_field_pw = false;
}

//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
//,,,,,,,,,,,,,,Variables,,,,,,,,,,,,,,,,,
//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
//-----------------------------------------
//--------------Form Elements--------------
//-----------------------------------------
//Username and password sent from form
$rm_username = mysql_real_escape_string ($_POST["username"]);
$rm_password = mysql_real_escape_string ($_POST["password"]);

//IP address (records IP the member used last)
$rm_ip = $_POST["ip"];

//Submit Button
$rm_submit = $_POST["submit"];

//Time Stamp
$rm_time = $_POST["time"];
$rm_date = $_POST["date"];

//--------------------------------------------
//---------------Error Trapping---------------
//--------------------------------------------
$rm_errors_found = false;
$rm_errors_none = false;
$rm_errors_msg = "The username or password you entered is invalid. You have <strong>$tries_left</strong> tries left."

//----------------------------------------------
//----------------Invalid Fields----------------
//----------------------------------------------
//Username
$rm_field_un = false;
//Password
$rm_field_pw = false;

//----------------------------------------------
//----------------Miscellaneous-----------------
//----------------------------------------------
//Timeout
$_SESSION["max_tries"] = 0;
$tries_left = 5 - $_SESSION["max_tries"];
$timeout_error = "You have reached the maximum number of login tries. Please wait 24 hours before trying again.";

//Remember Me
$rememberme_check = $_POST["rememberme_check"];
$rememberme_days = $_POST["rememberme_days"];

//Days To Seconds
$rememberme_seconds = (($rememberme_days * 24) * 60) * 60);

//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
//,,,,,,,,,,,Action,,,,,,,,,,,,
//,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
//If one or more errors have been found
if ($rm_errors_found) {
	//Add 1 to max_tries
	$_SESSION["max_tries"] += 1;
		//Check to see if timeout is true/will only be true if this is the user's 5th try.
		if ($timeout) {
			echo $timeout_error;
		//If timeout is false, it'll check which fields contain invalid information, and decide which errors
		//exist. It'll then display the login form with error messages displayed
		} else {
			display_form();
		}

//If all of the information the user entered is correct...	
} else {
	//Display "Welcome" message
	echo "Welcome, $rm_username. You are now logged in.";

	//Insert timestamp into database
	mysql_query(UPDATE fans SET last_visited_time = $rm_time WHERE username =
	$rm_username);
	mysql_query(UPDATE fans SET last_visited_date = $rm_date WHERE username =
	$rm_username);

	//Update member's ip address
	$mysql_query(UPDATE fans SET last_ip = $rm_ip WHERE username = $rm_username);

	//Insert user into "online" table
	mysql_query(INSERT INTO fans_online (username) VALUES ('$rm_username');

	//Delete user out of "offline" table
	mysql_query(DELETE FROM fans_offline WHERE username = $rm_username);

	//Delete user from guest table (assuming their ip address hasn't changed)
	mysql_query(DELETE FROM fans_guests WHERE ip = $_SESSION["guest"]);

	//As we are done with all mysql queries, close the connection
	mysql_close();

	//Assign $_POST value of the username they typed into a new $_SESSION variable
	$_SESSION["member"] = $rm_username;

	//If they want to be remembered, create cookies that store their information for the number of days they specified.
	if (isset($rememberme_check)) {
		setcookie ("username", "$rm_username", $rememberme_seconds,
		".djsmiley.net");
		setcookie ("password", "$rm_password", $rememberme_seconds,
		".djsmiley.net");
	}
}		
}

?>

 

Can someone please provide feedback on this script? I've been working on it actively for a whole week. It's rather complicated and has developed quite a bit; it's really confusing to read and understand now.

 

I THINK it's doing what I want it to, but I'm not sure.

 

Criticism and help understanding is much appreciated!

Link to comment
Share on other sites

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

Join the conversation

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

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

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

×   Your previous content has been restored.   Clear editor

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

×
×
  • Create New...

Important Information

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