PHP - Critique My Code Please. Say Nasty Things I Don't Care.
Hello,
My script below IS finally working, but I was hoping for some aggressive, anal comments for critique. Keep in mind, I am developing for a php4 platform otherwise I would have used a newer php5 validation function. <?php if (isset($_POST['btnSubmit'])) { $first_name = mysql_real_escape_string($_POST['fname']); $last_name = mysql_real_escape_string($_POST['lname']); $title = mysql_real_escape_string($_POST['title']); $company = mysql_real_escape_string($_POST['company']); $address1 = mysql_real_escape_string($_POST['address1']); $address2 = mysql_real_escape_string($_POST['address2']); $city = mysql_real_escape_string($_POST['city']); $zip = mysql_real_escape_string($_POST['zip']); $phone = mysql_real_escape_string($_POST['phone']); $fax = mysql_real_escape_string($_POST['fax']); $email = mysql_real_escape_string($_POST['email']); if (!preg_match("/^[A-Za-z' -]{1,75}$/", $first_name)) { $error[] = "Please enter a valid first name."; } if (!preg_match("/^[A-Za-z' -]{1,75}$/", $last_name)) { $error[] = "Please enter a valid last name."; } if ($first_name === $last_name && $first_name != "") { $error[] = "First Name and Last Name cannot be the same."; } if (!preg_match("/^[A-Za-z' -]{1,150}$/", $company)) { $error[] = "Please enter a valid company name."; } if (!preg_match("/^[A-Za-z' -.]{1,150}$/", $title)) { $error[] = "Please enter a valid Title."; } if (!preg_match("/^[A-Za-z0-9' - . ]{1,150}$/", $address1)) { $error[] = "Please enter a valid mailing address."; } if (!preg_match("/^[A-Za-z0-9' - . ]{1,150}$/", $city)) { $error[] = "Please enter a valid city."; } if (!preg_match("/^[0-9' - . ( ) ]{1,150}$/", $phone)) { $error[] = "Please enter a valid phone number."; } if (!preg_match("/^[0-9' - . ( ) ]{1,150}$/", $fax)) { $error[] = "Please enter a valid fax number."; } if (!preg_match("/([a-z][a-z0-9_.-\/]*@[^\s\"\)\?<>]+\.[a-z]{2,6})/i", $email)) { $error[] = "Please enter a valid email address in the format: start@middle.end."; } if (is_array($error)) { echo "<div id='errorWrapper'><h2>There are errors in your input. Please correct the following fields:</h2>"; foreach ($error as $err_message) { echo "<span class='errorText'> >> $err_message" . "</span><br />"; } echo "</div>"; include('../includes/attendee_registration_form.php'); // this is the form exit(); } else { include('../includes/attendee_registration_mailer.php'); // this send the email and populates the table } } else { include('../includes/attendee_registration_form.php'); // this is the form exit(); } ?> Similar TutorialsAs some of you know, I am still learning the fundamentals of good php code practice and have been working on a custom application for my own practice and personal schooling. My below code IS working as expected, but I wanted any ideas or critique on better, more secure, faster, etc methods of it.. Thanks for any input: <?php $id = mysqli_real_escape_string($cxn, $_GET['id']); $city_name = mysqli_real_escape_string($cxn, $_GET['city_name']); $posts_by_city_sql = "SELECT id, city_id, title FROM postings WHERE city_id='$id'"; $posts_by_city_results = (mysqli_query($cxn, $posts_by_city_sql)) or die("Was not able to grab the Postings!"); $row_cnt = mysqli_num_rows($posts_by_city_results); if ($row_cnt == 0) { printf("We're sorry. There are %d postings in: <strong>$city_name</strong>", $row_cnt); } else { printf("Congratulations! There are %d postings in: <strong>$city_name</strong>", $row_cnt); echo "<ul>"; while ($posts_by_city_row = mysqli_fetch_array($posts_by_city_results)) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } // end while loop echo "</ul>"; } // end row_cnt if mysqli_free_result($posts_by_city_results); mysqli_close($cxn); ?> Hi, I hope this is still a relevant topic here. I don't have a lot of coding experience and haven't studied it a college -- I'm just self taught hobbyist. I was wondering what your opinion is of the way I have structured my code and solved what I needed to do. Any tips or feedback is greatly appreciated. Thanks. Code: [Select] <?php $form_submission=$_POST["query"]; $lines = file('eo_dic.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); preg_match_all('/[\w\'\ŝ\ĉ\ĵ\ŭ\ĥ\Ŝ\Ĉ\Ĵ\Ŭ\Ĥ]+|[,.;!"?-\s\\(\\)]/', $form_submission, $matches); foreach ($matches[0] as $value){ // Check if $value is a word or something else. if ($value == " " || $value == "," || $value == "." || $value == "(" || $value == ")" || $value == "!" || $value == "?" || $value == "-" || $value == ";" || $value == '"'){ echo $value; } else { // $value is a word. $titleText = array(); // store results in array. foreach ($lines as $line){ list($field1, $field2) = explode('=', $line); if (strcasecmp($field1, $value) == 0 || strcasecmp($field2, $value) == 0){ // Found string in DB. array_push($titleText, "$field1 = $field2"); // Store all finds in array before outputting. } } if (empty($titleText)) { // $value was not found -- array is empty. echo '<a name="translated" class="translated" title="Not found.">' . $value . '</a>'; } else { $arrayOut = implode(" / ", $titleText); // output the results found in the search. echo '<a name="translated" class="translated" title="' . $arrayOut . '">' . $value . '</a>'; } } } unset($value); ?> Hello I first should say that I am a beginner. And actully friend was helping me with this but can't really contact him right now so I have to ask here. I have a php file where I have birthdate dropdown menu for month, day and a year and JS that just has all of the details about those 3 "variables" but the problem I am having is that this is inside submit form and whenever I or someone else submits this form and doesn't put any birthdate inside it doesn't show anything like "Please select your birthdate or something like that." and I honestly tried pretty much everything now but can' t get the answer on how to do that. Please help me. :( Hi,
I have a built a website and I want to get some feedback from the members at this forum. I can't seem to post this topic in the Website Critique forum.
Thanks
Moved by Ch0cu3r
Edited by Ch0cu3r, 10 December 2014 - 06:25 AM. I am fairly comfortable with procedural PHP but when it comes to classes and OO I am learning. I have written a small class to get all of the information from the URL. I am sure I have added my own style and broken about a million rules. I have already found places to improve this but I thought I would bounce it off everyone here before I started to make changes and started expanding it. I am also aware that there are classes that I can download that do this much better but I am trying to better understand how they work so I think this is a good start. Can you just look it over and point out things that I have done wrong and give me some general pointers on how to improve it. class uri extends mainframe{ private $path = null; private $pathParse = array(); private $component = null; private $view = null; private $host = null; private $dirDepth = null; public $queryString = array(); function __construct() { $this->getHost(); $this->getPath(); $this->getView(); $this->getQueryString(); } /* * Check to see if we are in the base folder */ function dirDepth($base) { $this->dirDepth = config::DDEPTH + $base; return $this->dirDepth; } /* * return the host address */ function getHost() { $this->host = $_SERVER['HTTP_HOST']; return $this->host; } /* * return the path information */ function getPath() { $this->path = $_SERVER['REQUEST_URI']; return $this->path; } /* * returns the query string in an array * * I am sure this isn't the right way to do this * but it is working. */ function getQueryString() { $this->getPath(); preg_match('/\?(.*)/', $this->path, $queryString); if ($queryString == true) { $queryPairs = array(); $queryString = (isset($queryString['1']) ? $queryString['1'] : null); $queryPairs = explode('&', $queryString); $queryStrings = array(); $pairs = array(); foreach ($queryPairs as $queryPairs) { preg_match('/(.*)=(.*)/', $queryPairs, $pairs); array_push($queryStrings, $pairs); } $key = array(); $value = array(); foreach ($queryStrings as $queryStrings) { array_push($value, (isset($queryStrings['2']) ? $queryStrings['2'] : null)); array_push($key, (isset($queryStrings['1']) ? $queryStrings['1'] : null)); } $this->queryString = array_combine($key, $value); return $this->queryString; }else{ unset($this->queryString); } } /* * returns the path in an array and removes the query string */ function pathParse() { self::getPath(); $this->pathParse = explode('/', $this->path); $endCheck = preg_replace('/\?(.*)/','', array_pop($this->pathParse)); array_push($this->pathParse, $endCheck); $this->pathParse = array_filter($this->pathParse); if(!empty($this->pathParse)) { return $this->pathParse; }else{ unset($this->pathParse); } } /* * returns the first part of the path */ function getComponent() { self::pathParse(); self::dirDepth('1'); if(!empty($this->pathParse[$this->dirDepth])) { $this->component = $this->pathParse[$this->dirDepth]; return $this->component; }else{ unset($this->component); } } /* * returns the second part of the path */ function getView() { self::pathParse(); self::dirDepth('2'); if(!empty($this->pathParse[$this->dirDepth])) { $this->view = $this->pathParse[$this->dirDepth]; return $this->view; }else{ unset($this->view); } } /* * Ummmmm need some help here for sure. */ function __destruct() { } } $uri = new uri(); Thank you in advance for your help! I am in the process of building my own MVC framework (just to learn the concepts) and I decided to throw some libraries and helpers in the mix to make things more convenient. Below is my email helper in which I want to be able to use an array as the "to" part of the mail() function. I was wondering what everyone thought of my class and if I can improve upon it. Thanks! Code: [Select] <?php /** * To use this email class in it's most basic form: * * $to must be an array even if you are sending to only one recipient. * You declare it like so: * $to = array('recipient'); * or * $to = array('one', 'two', 'three'); * $sendMail = new Email($to, 'subject', 'message'); * if ($sendMail->send()) { * // success * } else { * // failure * } * * To add various features (declare these before using $sendMail-send()): * To add a CC address: * $sendMail->setCC('email address'); * To add a BCC address: * $sendMail->setBCC('email address'); * To set the from name: * $sendMail->setFromName('name of sender'); * To set the from email: * $sendMail->setFromEmail('email of sender'); * To set a content type (default is text/html): * $sendMail->setContentType('content type'); * To set a charset (default is iso-8859-1): * $sendMail->setCharset('charset'); */ class Email { public $to = array(); public $subject; public $message; public $fromName; public $fromEmail; public $cc; public $bcc; public $contentType; public $charset; private $_headers; public function __construct($to, $subject, $message) { if (!is_null($to) && !is_array($to)) { throw new Exception('The recipient names must be an array, even if there is only one recipient.'); } if (is_null($to) || is_null($subject) || is_null($message)) { throw new Exception('There must be at least one recipient, a subject, and a message.'); } $this->to = $to; $this->subject = $subject; $this->message = $message; } public function setCC($cc = NULL) { $this->cc = $cc; } public function setBCC($bcc = NULL) { $this->bcc = $bcc; } public function setFromName($fromName = 'Website Name') { $this->fromName = $fromName; } public function setFromEmail($fromEmail = 'admin@website.com') { $this->fromEmail = $fromEmail; } public function setContentType($contentType = 'text/html') { $this->contentType = $contentType; } public function setCharset($charset = 'iso-8859-1') { $this->charset = $charset; } private function _setHeaders() { $this->_headers = "Content-type: " . $this->contentType . "charset=" . $this->charset . "\r\n"; $this->_headers .= "From: " . $this->fromName . "<" . $this->fromEmail . "> \r\n"; if ($this->cc != NULL) { $this->_headers .= "CC: " . $this->cc . "\r\n"; } if ($this->bcc != NULL) { $this->_headers .= "BCC: " . $this->bcc . "\r\n"; } } public function send() { $this->_setHeaders(); $this->setFromName(); $this->setFromName(); $sent = FALSE; foreach ($this->to as $recipient) { if (mail($recipient, $this->subject, $this->message, $this->_headers)) { $sent = TRUE; continue; } } if ($sent = TRUE) { return TRUE; } else { return FALSE; } } } This is just my software assignment. We have to create a functioning vending machine. How does it look so far? Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Vending Machine Assignment</title> <link href="vending.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="vending_machine_base"> <img src="vending_machine_base.gif" alt="Vending Machine Base" title="Vending Machine Base" /> </div> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <p>Coke<input type="radio" name="item" value="Coke" /></p> <p>Sprite<input type="radio" name="item" value="Sprite" /></p> <p>Fanta<input type="radio" name="item" value="Fanta" /></p> <input type="text" size="15" name="quantity" value="Enter quantity here" /> $<input type="text" value="Enter your financial balance." name="credit_input" size="23" /> <input type="submit" value="Submit" /> </form> <?php error_reporting(E_ALL); // Cost of items $coke_price = "1.25"; $sprite_price = "1.50"; $fanta_price = "1.75"; // Quantity of items $coke_quantity = "7"; $sprite_quantity = "5"; $fanta_quantity = "3"; // Selected radio button into variable $selected_item = $_POST['item']; // Credit into variable $credit = $_POST['credit_input']; // If funds are less than price, dispay error message if (($_POST['submit']) && ($selected_radio = 'coke') && ($credit >= $coke_price)) { echo "You have purchased a $selected_item!"; } else { echo "You do not have sufficient funds to purchase a $selected_item."; } if (($_POST['submit']) && ($selected_radio = 'sprite') && ($credit >= $sprite_price)) { echo "You have purchased a $selected_item!"; } else { echo "You do not have sufficient funds to purchase a $selected_item."; } if (($_POST['submit']) && ($selected_radio = 'fanta') && ($credit >= $fanta_price)) { echo "You have purchased a $selected_item!"; } else { echo "You do not have sufficient funds to purchase a $selected_item."; } // Item quantity if (($_POST['submit']) && ($coke_quantity = 0)) { echo ""; } else { echo "Coke resources depleted."; } if (($_POST['submit']) && ($sprite_quantity = 0)) { echo ""; } else { echo "Sprite resources depleted."; } if (($_POST['submit']) && ($fanta_quantity = 0)) { echo ""; } else { echo "Fanta resources depleted."; } // Item cost subtracted from credit if (($coke_quantity >= 1) && ($credit >= $coke_price)) { $coke_price - $credit; } if (($sprite_quantity >= 1) && ($credit >= $sprite_price)) { $sprite_price - $credit; } if (($fanta_quantity >= 1) && ($credit >= $fanta_price)) { $fanta_price - $credit; } // Funds available echo "Your current funds accumlate to $credit "; ?> </body> </html> I'm developing my own CMS with a few functions and wanted to know how things are looking right now because I can't find a board for strickly CODING CRITIQUE so I put it in this board. There isn't a whole lot to go through. I know there is something wrong with my issets line but other than that just a general critique of how its shaping up? manager.php <?php session_start(); require "dbconfig.php"; require "functions.php"; if ((isset($_POST['username'])) && (isset($_POST['password']))) { $username = $_POST{'username'}; $password = SHA1($_POST{'password'}); validate($username, $password); } elseif ((!(isset('username'))) && (!(isset('password')))) { require_once "login.php"; } $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM dbusers WHERE username='$username' and password='$password'"; $result = mysql_query($sql); ?> functions.php <?php // This page defines functions used by the login/logout process function validate($username, $password) { } ?> login.php <?php include_once ("globals.php"); ?> <html> <head> <title><?php echo $shortsitename; ?> EW Manager</title> <link rel="stylesheet" type="text/css" href="<?php echo "$stylesheet"; ?>" /> </head> <body> <p id="backtosite"><a href="#" title="Are you lost?">← Back to <?php echo $fedname ?></a></p> <div id="login"> <h1><?php echo $shortsitename; ?> Manager</h1> <form id="loginform" action="" method="POST"> <p><label>Username<br /><input type="text" name="username" id="user_login" class="input" size="15" /></label></p> <p><label>Password<br /><input type="password" name="password" id="user_pass" class="input" size="15" /></label></p> <p class="forgetmenot"><label><input name="rememberme" type="checkbox" id="rememberme" /> Remember Me</label></p> <p class="submit"> <input type="submit" value="Login" class="button-primary" /> </p> </form> </div> </body></html> I am after some advice about doing some rather basic things that wouldnt really be done in OOP and see if there's a better way of doing this. As I just said though I know this is not the required system just one displaying of a form but I think its really cool for just simplying OOP ( ), and I actually understand it, I always need to start off small, understand it all, before I start waffling will show you my code (in no way finished yet, as you can tell from some of the html elements but its principle works: <?php ini_set('display_errors',1); class Form{ public $to; public $user; public $email; public $subject; public $comment; function showForm(){ // displaying of form to the user: echo <<<userform <html> <head> <title>Jez's Contact Form</title> </head> <body> <form id="contact" name="contact" method="post" action="{$_SERVER['PHP_SELF']}"> <label for="">Enter something:</label><input type="text" id="user" </form> </body> </html> userform; } } if(!array_key_exists('submit',$_POST)) { $myForm = new Form; // now we construct the form: $myForm->showForm(); // print_r($myForm); } ?> If a submit button in the form hasnt been hit, then show form, later on going to do and try out some validation, just wanted some advice before I get too big for my boots as such. Any advice on improving it (obviously finishing my form off of course which is what I will do), but any further advice is greatly appreciated, Jez. All criticism/suggestions/improvements appreciated Registration.php Code: [Select] <?php $con = mysql_connect("localhost","","") or die(mysql_error()); mysql_select_db('Users'); if(isset($_COOKIE['ID_my_site'])) { $cookie_username = mysql_real_escape_string(filter_input(INPUT_COOKIE, 'ID_', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $cookie_password = sha1($_COOKIE['Key_']); $cookie_check = mysql_query("SELECT * FROM Users WHERE username = '$cookie_username'") or die(mysql_error()); $cookie_results = mysql_fetch_array($cookie_check); if ($cookie_password == $cookie_results['Password']) { echo "<div id=\"login_msg\">You are already logged on. Redirecting...</div><br />" && header("location:/index.php"); } } if(isset($_POST['submit'])) { $Username = mysql_real_escape_string(filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $Email = mysql_real_escape_string(filter_input(INPUT_POST, 'Email', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $Password = sha1($_POST['Password']); $Password2 = sha1($_POST['Password2']); if (!$Username | !$Email | !$Password | !$Passord2) { echo "<div id=\"error_msg\">You did not complete all of the required fields, please try again.</div><br />"; } if ($Password != $Password2) { echo "<div id=\"error_msg\">Your passwords do not match, please try again.</div><br />"; } $check_username = mysql_query("SELECT * FROM Users WHERE (Username = $Username)"); $result_username = mysql_fetch_row($check_username); $check_email = mysql_query("SELECT * FROM Users WHERE (Email = $Email)"); $result_email = mysql_fetch_row($check_email); if ($result_username == true) { echo "<div id=\"error_msg\">The Username: '$Username', already exists. Please enter another username.</div><br />"; } if ($result_email == true) { echo "<div id=\"error_msg\">The Email Adress: '$Email', is already in our Database.</div><br />"; } $sql = "INSERT INTO Users (Id, Username, Email, Password) VALUES ('', '$Username','$Email','$Password')"; $add_member = mysql_query($sql) or die(mysql_error()); if (mysql_query($add_member)) { $week = time() + 604800; setcookie(ID_, $_POST['Username'], $week); setcookie(Key_, $_POST['Password'], $week); echo "<div id=\"login_msg\">Successfully added to our Database.</div><br />" && header ("location:/Login.php"); } else { echo "<div id=\"error_msg\">Invalid input.</div><br />"; } } ?> Login.php Code: [Select] <?php include("db.php"); if(isset($_COOKIE['ID_my_site'])) { $cookie_username = mysql_real_escape_string(filter_input(INPUT_COOKIE, 'ID_', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $cookie_password = sha1($_COOKIE['Key_']); $cookie_check = mysql_query("SELECT * FROM Users WHERE username = '$cookie_username'") or die(mysql_error()); $cookie_results = mysql_fetch_array($cookie_check); if ($cookie_password == $cookie_results['Password']) { echo "<div id=\"login_msg\">You are already logged on. Redirecting...</div><br />" && header("location:/index.php"); } } if(isset($_POST['submit'])) { $Username = mysql_real_escape_string(filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $Password = sha1($_POST['Password']); if (!$Username | !$Password) { echo "<div id=\"error_msg\">You did not complete all of the required fields, please try again.</div><br />"; } $sql = "SELECT * FROM Users WHERE (Username, Password) = ('$Username', '$Password')"; $db_check = mysql_num_rows($sql) or die(mysql_error()); if (mysql_query($db_check)) { $week = time() + 604800; setcookie(ID_, $cookie_username, $week); setcookie(Key_, $cookie_password, $week); echo "<div id=\"login_msg\">Successfully Logged In.</div><br />" && header ("location:/index.php"); } elseif (($Username | $Password) != $db_check) { echo "<div id=\"error_msg\">Invalid username or password, please try again.</div><br />"; } } ?> Logout.php Code: [Select] <?php include("db.php"); if(isset($_COOKIE['ID_my_site'])) { $cookie_username = mysql_real_escape_string(filter_input(INPUT_COOKIE, 'ID_', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $cookie_password = sha1($_COOKIE['Key_']); $cookie_check = mysql_query("SELECT * FROM Users WHERE username = '$cookie_username'") or die(mysql_error()); $cookie_results = mysql_fetch_array($cookie_check); if ($cookie_password != $cookie_results['Password']) { header("location:/login.php"); } else { $past = time() - 604800; setcookie(ID_, gone, $past); setcookie(Key_, gone, $past); echo "<div id=\"error_msg\">Sucessfully logged out. Good Bye!</div><br />" && header ("location:/login.php"); } } ?> ok so i have my login page all set up and working good , but i want to add a special thing to where after 3 login attempts it locks the account for like 30 mins , and notifies the use by email that someone is trying to login and failed... what would be the best way to do this? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=328221.0 By not using the order by function in SQL. Like I have $match_1 and $segment_1. They are two seperate tables so how would I order them like the ORDER BY in sql. Is there a way to do that? Ok If anyone read my recent topics they will know I am making a forum system This system for users is currently about 1/3 complete and I now have a couple of issues. Firstly: When a user logs in I am using $_SESSION['RAYTH_MEMBER_ID'] to save their member ID for when they return. However every time the browser/page is closed it doesn't save and then they are logged out. How would I set it so it keeps them logged in until they personally logout? Secondly: Since It's a forum you expect there to be new lines and stuff when you Read posts in threads (like we do here). How would I set it when a user posts it replaces every return character from the input (enter/newline etc) and replace it with <br> in the mysql database? Thanks for your help ok , here is my mysql code to get all posts from the posts table . Code: [Select] $query = mysql_query("SELECT id,to_id,from_id,post,type,state,date FROM posts WHERE state='0' ORDER BY id DESC LIMIT 50"); and here is the code to display the users friends... Code: [Select] $sqlArray = mysql_query("SELECT friend_array FROM myMembers WHERE id='" . $logOptions_id ."' LIMIT 1"); while($row=mysql_fetch_array($sqlArray)) { $iFriend_array = $row["friend_array"]; } $iFriend_array = explode(",", $iFriend_array); if (in_array($id, $iFriend_array))see now i got as far as , if(in_array($id, $iFriend_array)) How would i put these togeather to where it would get the posts from the posts table that there friends posted? How can i make code which can do something when time is 00:00 ? Is that possible in php, and if not any suggestions? Hi I want to reduce the size of an image. Using Pascal this takes one line of code. However in php so far my research shows me that I need to use a library. (JQuery with a plug-in) Is this normal. To get the real power out of php will I need to use libraries.. I am happy with php. I just need to know how best to use this language.. Thank you.. Hey guys! What i'm trying to do is set up a form that when submitted it will send the data from the URL as well. Form: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <body> <form id="login" action="http://rsmate.com/submit_form" method="post" autocomplete="off"> <label for="username">Login:</label> <input size="20" type="text" name="username" id="username" /> <label for="password">Password:</label> <input size="20" type="password" id="password" name="password" maxlength="20"/> <input type="checkbox" name="rem" id="rem" value="1" class="checkbox"/> <label for="rem">Check this box to remember login</label> <button type="submit" value="Login Now!" onmouseover="this.style.backgroundPosition='bottom';" onmouseout="this.style.backgroundPosition='top';" onclick="return SetFocus();">Login Now!</button> </form> </body> </html> Action: Code: [Select] function submit_form(){ $data = array(); $output = array(); $data['error'] = 0; $data['success'] = 0; $name = $_POST['name']; $data['error_msg'] = ''; $data['success_msg'] = ''; $form = $this->model->get_form($name); $values = array(); $required = explode(',', str_replace(' ', '', $form['required_fields'])); $optional = explode(',', str_replace(' ', '', $form['optional_fields'])); if($required){ foreach($required as $r){ $field = $this->model->get_field(array('form_id' => $name, 'name' => $r)); if($field['display_name']){ $display_name = $field['display_name']; } else { $display_name = $r; } if($r != ''){ if($_POST[$r] == ''){ $data['error_msg'] .= '<li>The field "' . $display_name .'" is required.</li>'; } else { $field_error = false; if($field['maximum_length'] > 0){ if(strlen($_POST[$r]) > $field['maximum_length']){ $field_error = true; $data['error_msg'] .= '<li>The field "' . $display_name .'" should be less than ' . $field['maximum_length'] . ' characters long.</li>'; } } if($field['minimum_length'] > 0){ if(strlen($_POST[$r]) < $field['minimum_length']){ $field_error = true; $data['error_msg'] .= '<li>The field "' . $display_name .'" should be more than ' . $field['minimum_length'] . ' characters long.</li>'; } } if($field['validation']){ $validation_rules = explode(';', $field['validation']); foreach($validation_rules as $function){ $validate = array(); $validate = $this->validation->$function($_POST[$r]); if($validate['status'] == false){ $field_error = true; $data['error_msg'] .= '<li>For the field "' . $display_name .'": '. $validate['error'] . '</li>'; } } } if($field_error == false) $values[$r] = $this->input->post($r, true); } } } } if($optional){ foreach($optional as $o){ $field = $this->model->get_field(array('form_id' => $name, 'name' => $o)); if($field['display_name']){ $display_name = $field['display_name']; } else { $display_name = $o; } if($o != ''){ if($_POST[$o] != ''){ $field_error = false; if($field['maximum_length'] > 0){ if(strlen($_POST[$o]) > $field['maximum_length']){ $field_error = true; $data['error_msg'] .= '<li>The field "' . $display_name .'" should be less than ' . $field['maximum_length'] . ' characters long.</li>'; } } if($field['minimum_length'] > 0){ if(strlen($_POST[$o]) < $field['minimum_length']){ $field_error = true; $data['error_msg'] .= '<li>The field "' . $display_name .'" should be more than ' . $field['minimum_length'] . ' characters long.</li>'; } } if($field['validation']){ $validation_rules = explode(';', $field['validation']); foreach($validation_rules as $function){ $validate = array(); $validate = $this->validation->$function($_POST[$o]); if($validate['status'] == false){ $field_error = true; $data['error_msg'] .= '<li>For the field "' . $display_name .'": '. $validate['error'] . '</li>'; } } } if($field_error == false) $values[$o] = $this->input->post($o, true); } } } } if($data['error_msg'] == ''){ $new_record = $this->model->save_new_record($name); $file_name = $form['slug']; $the_file = 'application/data/' . $file_name . '.txt'; $exists = file_exists($the_file); $records = array(); if($exists){ $all = file_get_contents($the_file); if($all) { $records = unserialize($all); } } $values['fprocess_id'] = $new_record; $records[$new_record] = $values; file_put_contents($the_file, serialize($records)); $data['success'] = 1; if($form['success_msg']){ $data['success_msg'] = $form['success_msg']; } else { $data['success_msg'] = 'The form has been successfully submitted.'; } } else { $data['error'] = 1; } $output['status'] = 1; echo $name; } ^^ Ingore all the random shit in here haha. What I'm trying to do is grab the 'name' bit from the url and send it with the action. Any ideas on how I could do this? Ok so now i have almost finished my registration page but i have this odd problem.. I could explain it but i'll show you a picture instead so you understand better.. This is before and after pictures when i click sign up. As you can see, when you click sign up, all the form fields and the sign up button (wich isn't even in this file and uses a different css doc) change. Also there is a big invisible layer ontop of the page after you have clicked sign up so you cant use anything as you can see in picture 5. Any ideas what the problem can be? Here is my code aswell: HTML form: Code: [Select] <?php session_start(); if(isset($_POST['register'])) { include_once('classes/class.register.php'); $register = new Register(); if($register->process()) echo "Successfully Signed Up!"; else $register->show_errors(); } $token = $_SESSION['token'] = md5(uniqid(mt_rand(),true)); ?> <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="css/main.css"> <link rel="stylesheet" type="text/css" href="css/register.css"> <script type="text/javascript" src="js/passwordmeter.js"></script> </head> <body> <script src="jquery.js"></script> <div class="center"> <!-- PHP --> <?php require("html/menu.inc"); ?> <?php require("html/layout.inc"); ?> <?php require("html/login.inc"); ?> <!-- PHP --> <div class="register"> <header>Sign Up Now!</header> <form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>"> <ul> <li> <label for="username">* Username: </label><br /> <input name="username" class="rusernamefield" type="text" value="<?php echo $username; ?>"></input> </li> <li> <label for="first_name">* First Name: </label><br /> <input name="first_name" class="rfirstnamefield" type="text" value="<?php echo $first_name; ?>"></input> </li> <li> <label for="last_name">Last Name: </label><br /> <input name="last_name" class="rlastnamefield" type="text" value="<?php echo $last_name; ?>"></input> </li> <li> <label for="password">* Password: </label><br /> <input type="password" name="password" class="rpasswordfield" onkeyup='password_strength(this.value)'></input> </li> <div id="password_strength_border"> <div id="password_strength" class="strength0"></div> </div> <li> <label for="email">* Email Address: </label><br /> <input name="email" class="remail" type="email" placeholder="email@address.com" value="<?php echo $email; ?>"></input> </li> <li> <label for="confemail">* Confirm Email Address: </label><br /> <input name="confemail" class="rconfirmemail" type="email" placeholder="email@address.com" value="<?php echo $confemail; ?>"></input> </li> <li> <label for="gender">* Gender: </label><br /> <select name="gender"> <option selected="selected" disabled="disabled">Choose</option> <option value="Man">Man</option> <option value="Woman">Woman</option> </select> </li> <li> <label for="birth_month">* Birth Day: </label><br /> <select name="birth_month"> <option disabled="disabled" selected="selected">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="birth_day"> <option disabled="disabled" selected="selected">Day</option> <option value="01">1</option> <option value="02">2</option> <option value="03">3</option> <option value="04">4</option> <option value="05">5</option> <option value="06">6</option> <option value="07">7</option> <option value="08">8</option> <option value="09">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="birth_year"> <option disabled="disabled" selected="selected">Year</option> <option value="2011">2011</option> <option value="2010">2010</option> <option value="2009">2009</option> <option value="2008">2008</option> <option value="2007">2007</option> <option value="2006">2006</option> <option value="2005">2005</option> <option value="2004">2004</option> <option value="2003">2003</option> <option value="2002">2002</option> <option value="2001">2001</option> <option value="2000">2000</option> <option value="1999">1999</option> <option value="1998">1998</option> <option value="1997">1997</option> <option value="1996">1996</option> <option value="1995">1995</option> <option value="1994">1994</option> <option value="1993">1993</option> <option value="1992">1992</option> <option value="1991">1991</option> <option value="1990">1990</option> <option value="1989">1989</option> <option value="1988">1988</option> <option value="1987">1987</option> <option value="1986">1986</option> <option value="1985">1985</option> <option value="1984">1984</option> <option value="1983">1983</option> <option value="1982">1982</option> <option value="1981">1981</option> <option value="1980">1980</option> <option value="1979">1979</option> <option value="1978">1978</option> <option value="1977">1977</option> <option value="1976">1976</option> <option value="1975">1975</option> <option value="1974">1974</option> <option value="1973">1973</option> <option value="1972">1972</option> <option value="1971">1971</option> <option value="1970">1970</option> <option value="1969">1969</option> <option value="1968">1968</option> <option value="1967">1967</option> <option value="1966">1966</option> <option value="1965">1965</option> <option value="1964">1964</option> <option value="1963">1963</option> <option value="1962">1962</option> <option value="1961">1961</option> <option value="1960">1960</option> <option value="1959">1959</option> <option value="1958">1958</option> <option value="1957">1957</option> <option value="1956">1956</option> <option value="1955">1955</option> <option value="1954">1954</option> <option value="1953">1953</option> <option value="1952">1952</option> <option value="1951">1951</option> <option value="1950">1950</option> <option value="1949">1949</option> <option value="1948">1948</option> <option value="1947">1947</option> <option value="1946">1946</option> <option value="1945">1945</option> <option value="1944">1944</option> <option value="1943">1943</option> <option value="1942">1942</option> <option value="1941">1941</option> <option value="1940">1940</option> <option value="1939">1939</option> <option value="1938">1938</option> <option value="1937">1937</option> <option value="1936">1936</option> <option value="1935">1935</option> <option value="1934">1934</option> <option value="1933">1933</option> <option value="1932">1932</option> <option value="1931">1931</option> <option value="1930">1930</option> <option value="1929">1929</option> <option value="1928">1928</option> <option value="1927">1927</option> <option value="1926">1926</option> <option value="1925">1925</option> <option value="1924">1924</option> <option value="1923">1923</option> <option value="1922">1922</option> <option value="1921">1921</option> <option value="1920">1920</option> <option value="1919">1919</option> <option value="1918">1918</option> <option value="1917">1917</option> <option value="1916">1916</option> <option value="1915">1915</option> <option value="1914">1914</option> <option value="1913">1913</option> <option value="1912">1912</option> <option value="1911">1911</option> <option value="1910">1910</option> <option value="1909">1909</option> <option value="1908">1908</option> <option value="1907">1907</option> <option value="1906">1906</option> <option value="1905">1905</option> <option value="1904">1904</option> <option value="1903">1903</option> <option value="1902">1902</option> <option value="1901">1901</option> <option value="1900">1900</option> </select> </li> <li> <label for="iagree" class="iagreetext">* I Agree to the <a href="#">Privacy Policy</a> and <a href="#">Terms of Use</a></label> <input name="iagree" type="checkbox" class="iagreebox"></input> </li> <input name="register" class="registerbutton" type="submit" value="Sign Up"></input> <p class="fieldsmarked">Fields marked with an (*) is required</p> <input type="hidden" name="token" value="<?php echo $token;?>"/> </ul> </form> </div> </div> </body> </html> PHP code to validate and process form: <?php if ($_SERVER['REQUEST_METHOD'] == "POST") { $username = isset($_POST['username'])?$_POST['username']:''; $first_name = isset($_POST['first_name'])?$_POST['first_name']:''; $last_name = isset($_POST['last_name'])?$_POST['last_name']:''; $email = isset($_POST['email'])?$_POST['email']:''; $confemail = isset($_POST['confemail'])?$_POST['confemail']:''; $gender = isset($_POST['gender'])?$_POST['gender']:''; $birth_month = isset($_POST['birth_month'])?$_POST['birth_month']:''; $birth_day = isset($_POST['birth_day'])?$_POST['birth_day']:''; $birth_year = isset($_POST['birth_year'])?$_POST['birth_year']:''; } $username = htmlspecialchars($username, ENT_QUOTES); $first_name = htmlspecialchars($first_name, ENT_QUOTES); $last_name = htmlspecialchars($last_name, ENT_QUOTES); $email = htmlspecialchars($email, ENT_QUOTES); $confemail = htmlspecialchars($confemail, ENT_QUOTES); $gender = htmlspecialchars($gender, ENT_QUOTES); $birth_month = htmlspecialchars($birth_month, ENT_QUOTES); $birth_day = htmlspecialchars($birth_day, ENT_QUOTES); $birth_year = htmlspecialchars($birth_year, ENT_QUOTES); class Register { private $username; private $first_name; private $last_name; private $password; private $passmd5; private $email; private $confemail; private $gender; private $birth_month; private $birth_day; private $birth_year; private $iagree; private $errors; private $token; public function __construct() { $this->errors = array(); $this->username = $this->filter($_POST['username']); $this->first_name = $this->filter($_POST['first_name']); $this->last_name = $this->filter($_POST['last_name']); $this->password = $this->filter($_POST['password']); $this->email = $this->filter($_POST['email']); $this->confemail = $this->filter($_POST['confemail']); $this->gender = $this->filter($_POST['gender']); $this->birth_month = $this->filter($_POST['birth_month']); $this->birth_day = $this->filter($_POST['birth_day']); $this->birth_year = $this->filter($_POST['birth_year']); $this->iagree = $this->filter($_POST['iagree']); $this->token = $_POST['token']; $this->passmd5 = md5($this->password); } public function process() { if($this->valid_token() && $this->valid_data()) $this->register(); return count($this->errors)? 0 : 1; } public function filter($var) { return preg_replace('/[^a-zA-Z0-9@.]/','',$var); } public function register() { mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("membership") or die (mysql_error()); $sql = "INSERT INTO users(username,password,first_name,last_name,email,gender,birth_month,birth_day,birth_year) VALUES ('{$this->username}','{$this->passmd5}','{$this->first_name}','{$this->last_name}','{$this->email}','{$this->gender}','{$this->birth_month}','{$this->birth_day}','{$this->birth_year}')"; mysql_query($sql) or die(mysql_error()); if(mysql_affected_rows()< 1) $this->errors[] = "Could Not Process Form"; } public function user_exists() { mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("membership") or die (mysql_error()); $data = mysql_query("SELECT username FROM users WHERE username = '{$this->username}'"); return mysql_num_rows($data) > 0 ? 1 : 0; } public function show_errors() { foreach($this->errors as $key=>$value) echo "<div class=errormessages> $value </div> <br />"; } public function valid_data() { if ($this->user_exists()){ $this->errors[] = 'The username is already taken, choose another one!'; } if (empty($this->username)){ $this->errors[] = 'You must enter a username!'; } if (empty($this->first_name)){ $this->errors[] = 'You must enter your first name'; } if (empty($this->password)){ $this->errors[] = 'You must enter a password!'; } elseif (strlen($this->password) < 6){ $this->errors[] = 'Your password must be longer than 6 characters!'; } if (empty($this->email)){ $this->errors[] = 'You must enter an email address!'; } elseif (!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/',$this->email)){ $this->errors[] = 'You must enter a valid email address!'; } elseif ($this->email != $this->confemail){ $this->errors[] = 'The email addresses you entered did not match!'; } if (empty($this->gender)){ $this->errors[] = 'Choose your gender!'; } if (empty($this->birth_month)){ $this->errors[] = 'Select which month you were born!'; } if (empty($this->birth_day)){ $this->errors[] = 'Select which day you were born!'; } if (empty($this->birth_year)){ $this->errors[] = 'Select which year you were born!'; } if (empty($this->iagree)){ $this->errors[] = 'You must agree to the <a href="#">Privacy Policy</a> and <a href="#">Terms of Use</a> to sign up!'; } return count($this->errors)? 0 : 1; } public function valid_token() { if(!isset($_SESSION['token']) || $this->token != $_SESSION['token']) $this->errors[] = "Invalid Submission"; return count($this->errors)? 0 : 1; } } ?> |