I feel like I've gotten past beginner coding (see the bottom of this post for some of my scripts) and would like to move to "better" coding. By better I mean:
- Slightly more challenging.
- A broader knowledge of functions and how they work.
- Something that ensures my sites will be secure.
BBCode script (not full script, only a fragment of it)
Code: Select all
$bbcodes_start = array (
'[b]',
'[/b]',
'[i]',
'[/i]',
'[img]',
'[/img]',
':)',
':(',
':D',
'D:'
);
$bbcodes_end = array (
'<strong>',
'</strong>',
'<i>',
'</i>',
'<img src="',
'" />',
'<img src="smile.gif" />',
'<img src="sad.gif" />',
'<img src="happy.gif" />',
'<img src="shocked.gif" />'
);
$text = $_POST['text'];
$replaced = str_replace($bbcodes_start, $bbcodes_end, $text);
echo $replaced;
exit();
}Code: Select all
if($_SESSION['loggedin'] != 1) { //If the session variable loggedin is not equal to one
if(isset($_POST['login'])) { //Check if the log in form has been submitted
if(empty($_POST['password'])) {
die('You left the password field empty.'); //Exit the script with this message if the field was left empty
}
if($_POST['password'] != $password) {
die('Incorrect password.'); //Exit the script with this message if the password was incorrect
}
elseif($_POST['password'] === $password) { //If the password was correct
$_SESSION['loggedin'] = 1; //Set the session variable loggedin to 1
echo "You have been logged in successfully."; //Echo the message
header('Location: index.php'); //Redirect to the home page
exit();
}
}Code: Select all
function loginUser() {
session_start();
if($_SESSION['loggedin'] != "set") {
if(isset($_POST['login'])) {
if(empty($_POST['username']) || empty($_POST['password'])) {
die('You have left a required field empty. Please go back and try again.');
}
else {
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = sprintf("SELECT * FROM users WHERE username='%s' AND password='%s'",
mysql_real_escape_string($username),
mysql_real_escape_string($password));
$query = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($query) or die(mysql_error());
if($num === 1 || $num != 0 || $num > 0) {
$_SESSION['loggedin'] = "set";
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
echo "You have been logged in successfully. Now redirected you to the homepage.";
header('Location-type: index.php');
}
elseif($num != 1 || $num === 0 || $num < 1) {
die('Either your username or password did not match up. Please try again.');
}
}
}
elseif(!isset($_POST['login'])) {
require("loginform.html");
}
}
elseif($_SESSION['loggedin'] === "set") {
die('You are already logged in.');
}
}