PHP - Login System And Adding Data Into A Database
So I have to add data into my database for Olympic records for a school project. I have the sql statements and everything, but it will only enter the athlete's name and country into the table. My code is Code: [Select]
<html> <head> <title> CSS </title> <style type="text/css"> p {font-family:arial; font-size:10pt;} body {margin: 0; padding: 0; text-align: center;} a:link {text-decoration: none} a:visited {text-decoration: overline; color:purple;} a:active {text-decoration: underline;} a:hover {text-decoration: line-through ; color:pink} input:hover {background: aqua; color:black} input:active { background: lime ; color: black; } input:focus { background: yellow; color: black; } .button {border: 1px dotted ; background:red; padding: 2px;} .button:hover {border: 2px dotted;background: url('submitbackground.jpg') no-repeat top left; } #main {margin: 0 auto; text-align: left; width: 800px;} #nav {clear: both; border: 1px solid; background-color:lightgreen; padding: 10px; width:auto; height: 8%;} #div1 {border: 1px solid; background-color:lightblue; padding: 10px; float: left; width:20%; height:92%;} #div2 {border: 1px solid; background-image: url('monkey.jpg'); background-repeat:no-repeat; background-position:center bottom ; padding: 10px; float:left; width:74.5%; height:92%;} </style> </head> <body> <?php session_start () ; print_r ($_REQUEST) ; if ($_SESSION['admin'] == 2) { echo " sorry" ; } else { echo $_SESSION['admin']; if(isset($_POST['athname'])){ $athname= $_POST['athname'] ; } if(isset($_POST['country'])){ $country = $_POST['country']; } if(isset($_POST['medal'])){ $medal= $_POST ['medal']; } if(isset($_POST['venueyear'])){ $venueyear= $_POST ['venueyear']; } if(isset($_POST['venuecity'])){ $venuecity= $_POST ['venuecity']; } if(isset($_POST['venuecountry'])){ $venuecountry= $_POST ['venuecountry']; } if(isset($_POST['event'])){ $event= $_POST ['event']; } if(isset($_POST['gender'])){ $gender= $_POST ['gender']; } echo "<div id='main'> " ; echo"<div id='nav'>"; echo"</div>" ; echo "<div id='div1'>" ; echo "<a href='index.php'>home</a><br/>" ; echo "<a href='search.php'>Search</a><br/>" ; echo "<a href='add-data.php'>Add Data</a><br/>" ; echo "<a href='DeleteData.php'>Delete Data</a>" ; echo "</div>" ; echo"<div id='div2'>" ; if (isset($_POST['search'])) { $connection = odbc_connect('Olympics', '', ''); if (!$connection) {exit("Conection Failed: " . $connection);} $enrID = null ; if ( $event == '100 meters' and $gender == 'M') { $enrID = 1 ; echo "$enrID" ; }elseif ($event == '200 meters' and $gender == 'M') { $enrID = 2 ; echo "$enrID" ; }elseif ($event == '400 meters'and $gender == 'M') { $enrID = 3 ; }elseif ($event == '800 meters' and $gender == 'M') { $enrID = 4 ; }elseif ($event == '1500 meters' and $gender == 'M') { $enrID = 5 ; }elseif ($event == 'Long Jump' and $gender == 'M') { $enrID = 6 ; }elseif ($event == 'High Jump' and $gender == 'M') { $enrID = 7 ; }elseif ($event == 'Shot put' and $gender == 'M') { $enrID = 8 ; }elseif ($event == 'basketball' and $gender == 'M') { $enrID = 13 ; }elseif ($event == 'rowing' and $gender == 'M') { $enrID = 14 ; }elseif ($event == 'volleyball(indoor)' and $gender == 'M') { $enrID = 15 ; }elseif ($event == 'volleyball(beach)' and $gender == 'M') { $enrID = 16 ; }elseif ($event == '100 meters' and $gender == 'F') { $enrID = 17 ; }elseif ($event == '200 meters' and $gender == 'F') { $enrID = 18 ; }elseif ($event == '400 meters'and $gender == 'F') { $enrID = 19 ; }elseif ($event == '800 meters' and $gender == 'F') { $enrID = 20 ; }elseif ($event == '1500 meters' and $gender == 'F') { $enrID = 21 ; }elseif ($event == 'Long Jump' and $gender == 'F') { $enrID = 22 ; }elseif ($event == 'High Jump' and $gender == 'F') { $enrID = 23 ; }elseif ($event == 'Shot put' and $gender == 'F') { $enrID = 24 ; }elseif ($event == 'basketball' and $gender == 'F') { $enrID = 25 ; }elseif ($event == 'rowing' and $gender == 'F') { $enrID =26 ; }elseif ($event == 'volleyball(indoor)' and $gender == 'F') { $enrID = 27 ; }elseif ($event == 'volleyball(beach)' and $gender == 'F') { $enrID = 28 ; } $EnrVenID = null ; if ($venueyear == '1984') { $EnrVenID = 1 ; echo "$EnrVenID" ; }elseif ($venueyear == '1988') { $EnrVenID = 2 ; }elseif ($venueyear == '1992') { $EnrVenID = 3 ; }elseif ($venueyear == '1996') { $EnrVenID = 4 ; }elseif ($venueyear == '2000') { $EnrVenID = 5 ; }elseif ($venueyear == '2004') { $EnrVenID = 6 ; }elseif ($venueyear == '2008') { $EnrVenID = 7 ; echo "$EnrVenID" ; }elseif ($venueyear == '2012') { $EnrVenID = 8 ; echo "$EnrVenID" ; } $sql="INSERT INTO Athletes (Athname, Athcountry) values ( '$athname', '$country') " ; $rs=odbc_exec($connection,$sql); $sql4="INSERT INTO Enrollments (EnrMedal, EnrYear, EnrEventID, EnrVenID) values ( '$medal', '$venueyear', '$enrID', '$EnrVenID') " ; $rs4=odbc_exec($connection,$sql4); } echo "<form method='post' action=''>\n"; echo"Please fill out all the fields with the data that you wish to be added: <br/>"; echo"Athelete Name:<input type ='text' Name='athname' > <br/> \n" ; echo"Athelete Country:<input type ='text' Name='country' > <br/> \n" ; echo "Medal: <select name='medal' value='medal'>\n"; echo "<option > </option>\n"; echo "<option $Gold> Gold </option>\n"; echo "<option $Silver> Silver </option>\n"; echo "<option $Bronze'> Bronze</option>\n"; echo "</select>\n" ; echo "Venue Year: <select name='venueyear' value= 'venueyear'>\n"; echo "<option ></option>\n"; echo "<option $1984> 1984 </option>\n"; echo "<option $1988> 1988 </option>\n"; echo "<option $1992>1992 </option>\n"; echo "<option $1996> 1996 </option>\n"; echo "<option $2000> 2000 </option>\n"; echo "<option $2004> 2004 </option>\n"; echo "<option $2008> 2008 </option>\n"; echo "<option $2012> 2012</option>\n"; echo "</select>\n" ; echo "Venue City: <select name='venuecity' value= 'venuecity'>\n"; echo "<option > </option>\n"; echo "<option $LA> Los Angeles </option>\n"; echo "<option $Seoul> Seoul </option>\n"; echo "<option $Barca> Barcelona </option>\n"; echo "<option $ATL> Atlanta</option>\n"; echo "<option $Syd> Sydney </option>\n"; echo "<option $Ath> Athens</option>\n"; echo "<option $Beij> Beijing </option>\n"; echo "<option $Lon> London</option>\n"; echo "</select>\n" ; echo "Venue City: <select name='venuecountry' value= 'venuecountry'>\n"; echo "<option > </option>\n"; echo "<option $USA> U.S.A. </option>\n"; echo "<option $SK> South Korea </option>\n"; echo "<option $Spain> Spain </option>\n"; echo "<option $Aus> Australia </option>\n"; echo "<option $Greece> Greece</option>\n"; echo "<option $Chin> China </option>\n"; echo "<option $UK> United Kingdom</option>\n"; echo "</select>\n" ; echo "Event: <select name='event' value='event>\n"; echo "<option value=''> </option>\n"; echo "<option > </option>\n"; echo "<option $100m> 100 meters</option>\n"; echo "<option $200m> 200 meters </option>\n"; echo "<option $400m>400 meters </option>\n"; echo "<option $800m> 800 meters </option>\n"; echo "<option $1500m> 1500 meters </option>\n"; echo "<option $LongJump> Long Jump</option>\n"; echo "<option $HighJump> High Jumo </option>\n"; echo "<option $Shotput> Shot put </option>\n"; echo "<option $Basketball> Basketball </option>\n"; echo "<option $Rowing> Rowing </option>\n"; echo "<option $Volleyball> Indoor Volleyball </option>\n"; echo "<option $Volley> Beach Volleyball</option>\n"; echo "</select>\n" ; echo "Gender: <select name='gender'>\n"; echo "<option value=''> </option>\n"; echo "<option $Male>M</option>\n"; echo "<option $Female>F</option>\n"; echo "</select>\n" ; echo "<input type='submit' name='search' value='Search' />\n"; echo "</form>\n"; echo "</div>" ; } ?> </body> </html> I have the really long IF statements in there so that it enters the correct EnrID and EnrVenID into the database, to make sure it fills out all fields. I am using Microsoft access for my database. The problem is that it will only fill in the athlete's name and country, and not his/her enrollment information (what medal they got, their enr ID, what year it was taken place, etc. The problem with my login system is that I want the user to login with a username and password if they wish to be an admin, but the login system doesn't work. the variables aren't passed through the system for some reason, even though it worked a week ago, but now it doesn't. The code is Code: [Select] if(isset($_POST['username'])){ $username= $_POST['username'] ; } if(isset($_POST['password'])){ $password= $_POST['password'] ; } $username = null ; $password = null ; Thanks for any help Similar TutorialsI currently have a MyBB forum and I'm going to attempt to create a top list for it, but I'd like users that have already registered on my forum to be able to log into the top list area and either add or edit their website on the top list. How would I go about creating a login script with an already existing MySQL database that contains my MyBB users? So i have an event page where it will show the next 3 events, then i need logged in users to click either of two buttons to say there attending or not attending. i have the below code showing events, and the <form> and the submit and both buttons, but if i submit 1 button on event ID: 1 it inserts data into the database but for event ID: 2, and if i click the button on event ID :2 it also puts it into database with eventid:2 so no matter which event i click it seems to submit data with the latest event ID shown on page, and not for "each" event seperatly. i have moved the submit query everywhere around and still same results or duplicate results if its in the loop. i assume its looping the submit and only submitting the latests event ID.
<?php if ($result = $con->query("SELECT * FROM events ORDER BY id ASC LIMIT 3")) { if ($result->num_rows > 0) { while ($row = $result->fetch_object()) { $event_id = $row->id; // set up table and echo data! echo "<table border='1' cellpadding='2' width='50%'>"; echo "<tr><td>"; echo "<p><img src='images/raid_banners/" . $row->bannerimg . "'>" . $row->name . " (iLvl: " . $row->itemlevel . ")</p>"; echo "<p>Event Starts: " . $row->datestart . " - " . $row->timestart . "</p>"; echo "<p>Event Ends: " . $row->dateend . " - " . $row->timeend . "</p>"; echo "<p>Raid Lead: " . $row->raidlead . "</p>"; echo "<form action='' name='$event_id' method='post'>"; // Process and populate SELECT form element echo "<select name=\"charname\">"; $sql = mysqli_query($con, "SELECT * FROM characters WHERE userid = $userid"); while ($row = $sql->fetch_assoc()){ echo "<option value=\"{$row['id']}\">{$row['charname']}</option>"; } echo "</select>"; echo "<input type='hidden' name='raidid' value ='$event_id'>"; echo "<input type='hidden' name='action' value='submit' />"; echo "<input type=\"submit\" name=\"submit\" value=\"going\">"; echo "<input type=\"submit\" name=\"submit\" value=\"notgoing\">"; echo "</form></td></tr></table><br><br>"; } if(isset($_POST['action'])){ $charid = $_POST['charname']; $submit = $_POST['submit']; // Submit the data from dropdown in the form mysqli_query($con,"INSERT INTO eventsignup (eventid, charid, userid, status) VALUES ('$event_id', '$charid', '$userid', '$submit')"); } } else { echo "No results to display!"; } } else { echo "Error: " . $con->error; } $con->close(); ?> any help would be awesome. im tearing my hair out here. Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> Hi guys. What I want to create is really complicated. Well I have a login system that works with post on an external website. I have my own website, but they do not give me access to the database for security reasons, therefore I have to use their login system to verify my users. What their website does is that it has a post, with username and password. The POST website is lets say "https://www.example.com/login". If login is achieved (i.e. username and password are correct), it will redirect me to "https://www.example.com/login/success" else it will redirect me to "https://www.example.com/login/retry". So I want a PHP script that will do that post, and then according to the redirected website address it will return me TRUE for success, FALSE for not successful login. Any idea?? Thanks hello everyone, I am about to start coding my pages to display results from a database but before i do i want to know information about the following : Is it best to upload images to a database?and display them accordingly? or is it best to use images from a directory? What is most commonly used and or more reliable? Another topic i have trouble finding information on is actually positioning the output from you mysql database, is this practice done with tables?fields and rows? What is this method called? And is there more then one way to go about controlling result layout on your page? Sorry about the 1001 questions , but i am unable to find a clear answer on the topic ..especially question two . Thanks in advance. I've abandoned my old script and switched to this one: http://www.evolt.org/node/60384 I got it working on my site just fine (djsmiley.net/members/register - you can test it out if u want). i just want to know how i can put all of the code into the pages i created using my template. It doesn't specify how this can be done in the tutorial, which is why im confused. I've tried everything but keep getting errors. Help? Hi could you help me get this login page working?
I made a form which posts to login.php the "user" and "pass".
Then this is my code for login.php: <?php include("mysql_connect.inc.php"); ?> <?php $user = $_POST['user']; $pass = $_POST['pass']; session_start(); $query = mysqli_query("SELECT * FROM users WHERE username='$user'"); $results = mysqli_query($con, $query) or die(mysqli_error($con)); $resultsarray = mysql_fetch_array($userresults); if (isset($_POST['user']) && $_POST['user'] == $query && isset($_POST['pass']) && $_POST['pass'] == $query) { $_SESSION['username'] = $_POST['user']; echo "<p>Login success. You are logged in as: " . $_SESSION['username'] . "</p>Return to mainpage, click <a href='index.php'>here</a>!"; } else { echo "<p>Wrong username or password.</p>"; } mysqli_close($con); ?> Hi, im getting alot of errors like so Deprecated: Function session_is_registered() is deprecated time to update some files, can you guys pls help im rubbish with PHP guess thats why I waited so long to update. here is the code I need to change checklogin.php // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:index.php"); } index.php <? session_start(); /*if(!session_is_registered(myusername)){ header("location:main_login.php"); }*/ ?> index.php (display username stuff) <?php if(session_is_registered(myusername)){ ?> Welcome: <?= $_SESSION['myusername'] ?><?php } ?> index.php (edit content stuff) <?php $file = file_get_contents('content/menu_header_a.txt', 'r'); if(session_is_registered(myusername)){ ?><a href="javascript:open4()"><?php echo $file ?></a><?php } else { echo $file; }?> Many thanks for any and all your help with this one. if you could keep it simple please like ( replace this with this ) . thanks Hi All!
This is my first post here, so if there are some things I miss or something more I need to do please let me know.
I tried searching the forum for the answer first but could not find anything.
So here is the thing; I followed a tutorial I found about building a login system for my website. The tutorial worked perfectly, except I needed it to redirect to a user specific page instead of a static page on login. I made the necessary changes to the script, and now it redirects to the user specific page, but does not recognize that I am logged in so it will not show me the content.
In the interest of full disclosure, I am not very good at PHP and lack a fundamental understanding of it. I am enrolled in some Udemy courses to try to rectify that, but I needed the login system ASAP, so copy and paste programming was my only option. I know, I know. I am a terrible human being and should be thrown into the sun. I agree. I am in counseling to try to deal with it.
The tutorial I used can be found he http://www.wikihow.c...n-PHP-and-MySQL.
Here is the relevant code:
process_login.php:
<?php include_once 'db_connect.php'; include_once 'functions.php'; sec_session_start(); // Our custom secure way of starting a PHP session. if (isset($_POST['email'], $_POST['p'])) { $email = $_POST['email']; $password = $_POST['p']; // The hashed password. $page = login($email, $password, $mysqli); if ($page == true) { // Login success header('Location: '. $page); exit(); } else { // Login failed header('Location: ../error.php?error=1'); } } else { // The correct POST variables were not sent to this page. echo 'Invalid Request'; } First of all hello as I am new to this forum. Ok so, I am have been trying for the past few days to create a login system in PHP for a website I am creating, and I am having serious problems. I have tryed so many tutorials and they all are not working, my conclusion is they are outdated or not fully understandable. So what I want to create - Registration Forgot password Login page Email activation Member page My hosting has the latest php and mysql as far as I know so could someone please give me an up to date simple tutorial on creating this. Lastly the program I am using is Dreamweaver CS5 Thankyou. I'm trying to build a login system and alot of the code is similar to what i used to make my news cms. basically all i wanna accomplish right now is to get the user input inserted into my database. I've already tested it out, and I get no errors, but like with the cms, the database isn't getting queryed. Here's the code: (process.php) Code: [Select] <?php $first_name=$_POST['first_name']; $last_name=$_POST['last_name']; $age=$_POST['age']; $city=$_POST['city']; $state=$_POST['state']; $country=$_POST['country']; $zip=$_POST['zip']; $birthdate=$_POST['birthdate']; $gender=$_POST['gender']; $sexuality=$_POST['sexuality']; $race=$_POST['race']; $religion=$_POST['religion']; $status=$_POST['status']; $about=$_POST['about']; $website=$_POST['website']; $user_name=$_POST['user_name']; $password=$_POST['password']; $email=$_POST['email']; mysql_connect("your hostname", "your database name", "your password") or die(mysql_error()); mysql_select_db("your database name") or die(mysql_error()); $sql = sprintf("INSERT INTO Users (first_name, last_name, age, city, state, country, zip, birthdate, gender, sexuality, race, religion, status, about, website, user_name, password, email) VALUES ('%s', '%s', '%s', '%s', '%s')", mysql_real_escape_string($first_name), mysql_real_escape_string($last_name), mysql_real_escape_string($age), mysql_real_escape_string($city), mysql_real_escape_string($state), mysql_real_escape_string($country), mysql_real_escape_string($zip), mysql_real_escape_string($birthdate), mysql_real_escape_string($gender), mysql_real_escape_string($sexuality), mysql_real_escape_string($race), mysql_real_escape_string($religion), mysql_real_escape_string($status), mysql_real_escape_string($about), mysql_real_escape_string($website), mysql_real_escape_string($user_name), mysql_real_escape_string($password), mysql_real_escape_string($email)); $result = mysql_query($sql); Print "Congratulations! You are now a registered member on yourwebsite.com!"; ?> (register/index.php) Code: [Select] <script language = "Javascript"> function Validate() { if (document.register.first_name.value == '') { alert('You have not specified your first name!'); return false; } if (document.register.last_name.value == '') { alert('You have not specified your last name!'); return false; } if (document.register.age.value == '') { alert('You have not specified your age!'); return false; } if (document.register.country.value == '') { alert('You have not entered a country!'); return false; } if (document.register.birthdate.value == '') { alert('You have not entered your date of birth!'); return false; } if (document.register.gender.value == '') { alert('You have not specified your gender!'); return false; } if (document.register.user_name.value == '') { alert('You have not entered a username!'); return false; } if (document.register.email.value == '') { alert('You have not entered an email!'); return false; } if (document.register.password.value == '') { alert('You have not entered a password!'); return false; } return true; } </script> <form name="register" method="post" action="http://www.djsmiley.net/register/process.php" onsubmit="return Validate();"> <table width="100%" border="0"> <tr> <td>First Name:</td> <td><label> <input type="text" name="first_name" id="first_name" /> </label></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" name="last_name" id="last_name" /></td> </tr> <tr> <td>Age:</td> <td><input type="text" name="age" id="age" /></td> </tr> <tr> <td>City:</td> <td><input type="text" name="city" id="city" /></td> </tr> <tr> <td>State:</td> <td><input type="text" name="state" id="state" /></td> </tr> <tr> <td>Country:</td> <td><input type="text" name="country" id="country" /></td> </tr> <tr> <td>Zip:</td> <td><input type="text" name="zip" id="zip" /></td> </tr> <tr> <td>Birthdate:</td> <td><input type="text" name="birthdate" id="birthdate" /></td> </tr> <tr> <td>Gender:</td> <td><input type="text" name="gender" id="gender" /></td> </tr> <tr> <td>Sexuality:</td> <td><input type="text" name="sexuality" id="sexuality" /></td> </tr> <tr> <td>Race:</td> <td><input type="text" name="race" id="race" /></td> </tr> <tr> <td>Religion:</td> <td><input type="text" name="religion" id="religion" /></td> </tr> <tr> <td>Marital Status:</td> <td><input type="text" name="status" id="status" /></td> </tr> <tr> <td>About You:</td> <td><label> <textarea name="about" id="about" cols="45" rows="5"></textarea> </label></td> </tr> <tr> <td>Website:</td> <td><input type="text" name="website" id="website" /></td> </tr> <tr> <td width="13%">Username: </td> <td width="87%"><input type="text" name="user_name" id="user_name" /></td> </tr> <tr> <td>Email: </td> <td><input type="text" name="email" id="email" /></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="password" id="password" /></td> </tr> <tr> <td> </td> <td><input name="Register Button" type="submit" class="Button1" id="Register Button" value="Register" /> <input name="Reset Button" type="reset" class="Button1" id="Reset Button" value="Clear" /></td> </tr> </table> <label></label> </form> ok i need directing to a tutorial, an easyish one that can help me do a secure login and registration system. Something that uses sessions and mysql. something with sql injection and other security. i need it very secure. hope you can help. Hi Everyone, Just a quick question before I take on this project. Basically the client has a secure server set up with folders for different clients. So they can store excel files, PDFs etc, What the client use to do was send the client an email with the http address of that clients particular folder to be able to login. What my job is to create a login system that redirects each client to their particular area on the secure system. Is this going to be difficult, What I was thinking of doing was when the administator is setting up the client details there would be an extra field saying address: they paste the address of the folder on the server. Then it will redirect them to their folder. Is this the correct way to do this. Any help or advice would be great. I am using a login system in php and mySQL but only one page is potected. pages i am using: 1. login.php // inputing details (user name, password) 2. checkloginDetails.php // connect to db and check login details 3. logged_in.php // successfully login ...i need more than the one page protected for example; once the user has logged in there will be the main logged in page with other links, remove topics, add, user, remove user all these pages i want protecting but with out the user inputing his details again. Has anyone got an idear onhow i ould achive this? here is my part of the code which i am stuck on <?php $form = "<form action='login.php' method='post'> <center> <table> <tr> <td><input type='text' id='usernamebox' name='Username' value='Username' tabindex='1' class='textbox' onFocus='usernamebox_focus();' onBlur='usernamebox_blur();'></td> <td><a href='register.php'>Register</span></a></td> </tr> <tr> <td><input type='password' id='passwordbox' name='Password' value='Password' tabindex='2' class='textbox' onFocus='passwordbox_focus();' onBlur='passwordbox_blur();'></td> <td><input type='submit' name='loginbutton' value='Login'></td> </tr> </table> </center> </form>"; ******(on the website the rest under thiss is missing)******** if ($_POST['loginbutton']){ $user = $_POST['username']; $password = $_POST['password']; if ($user && $password && $user != 'Username'){ require("Scripts/connect.php"); $password = md5($password); $query = mysql_query("SELECT * FROM users WHERE username='$user' AND password='$password'"); $numrows = mysql_num_rows($query); if ($numrows = 1){ $rows = mysql_fetch_assoc($query); $dbuser = $rows['username']; $_SESSION['user'] = $dbuser; $_SESSION['id'] = $dbid; echo "<a href='index.php'> You are now loged in Click here to go to our Homepage</a>"; } else echo '<center>You did not submit a correct username and/or password!</center>'; echo '$form'; } else echo '<center>You did not submit a correct username and/or password!</center>'; echo '$form'; } else{ echo '$form'; } ?> hi, I'm coding a website, after being away from php for a while, and there's this simple thing that's driving me crazy. I made a simple login system to test, and I have to refresh the page twice so it becomes active, and I can't figure out why. what's wrong with this code? (keep in mind that it's just a test, I plan to get username from database, send encrypted info to cookies, and all that, but after I get this working) Code: [Select] <?php if (isset($_POST['submitlogin'])) { if ((($_POST['username'])&&($_POST['password']))=="admin") { setcookie("user", "Administrator", time()+3600); } else { $loginerror="1"; } } if (isset($_GET['logout'])) { setcookie("user", "", time()-3600); } ?> <html> <head> </head> <body> <?php if (isset($_COOKIE['user'])) { echo "Hello, ".$_COOKIE['user']; ?> <br /><a href="?logout=yes">Logout</a> <?php }else{?> <form action="" method="post"> <input name="username" type="text" /><br /> <input name="password" type="password" /><br /> <input name="submitlogin" type="submit" value="Login" /> </form> <?php }?> </body> </html> thanks for any help! Since it appears my login system is broken i have been trying to fix it. The problem is that it isnt loggin people in. This is what im doing: The user visits login.php they enter their details and click login the posted data gets sent to login_process.php via jQuery login_process.php checks to see if the details are correct if they are it sets a cookie called uid with their user id if they clicked the remember me box then this cookie is set for a year if not then it is set as a session cookie login_process echos a success back to the jQuery in login.php when jQuery gets this success status it redirects to login_success.php the user should now be logged in. to show a logged in user i echo their username by running a query on the cookie uid but somewhere along the lines cookie uid isnt being set so the user is never logged in. here is the code:(shortened) $username = $_POST['user_name']; $password = asf_hash($_POST['password']); $remember_me = $_POST['remember_me']; //check the values with a query then: if($remember_me == 'yes' && !isset($_COOKIE['uid'])) { setcookie('uid', $_SESSION['uid'], time()+(((60*60)*24)*365)); } elseif($remember_me == 'no' && !isset($_COOKIE['uid'])) { setcookie('uid', $_SESSION['uid'], 0); } else { setcookie('uid', '', time()-3600); } login_success just contains a like to go back to the page they were originally viewing. and in my init script which is run when a page loads: $user = new user; $user->setup($_COOKIE['uid']); // this basically sets info like the username and such from a query run on the cookie. so why isnt the cookie being set? any ideas? also any ideas on making this more secure if it isnt? Thanks This is my one page log in system. Using this on the header so guests can log in on ANY page. Let me know what you think needs improving for security. I'm also wondering if putting the include "disconnect.php"; where I have is correct. Thanks! Code: [Select] <?php session_start(); $message = ""; //error message needs to be blank $loginstatus = ""; //error message needs to be blank //if $_POST "username" and "password" exist, check for consistency. if (isset($_POST['username'])&&($_POST['password'])) { include 'connect.php'; //connect $username = mysql_real_escape_string($_POST['username']); //set variables from session $password = mysql_real_escape_string($_POST['password']); //set variables from session //remove slashes and HTML $username = stripslashes($username); $password = stripslashes($password); $username = strip_tags($username); $password = strip_tags($password); $password = md5($password); //md5 encryption $query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'"); //checking if row exists that has $username and $password together. $num = mysql_num_rows($query); //number of rows. if not equal to one login will fail. if($num==1) { $_SESSION['username'] = $username; //store session data $message = "$username, you are logged in!"; include "disconnect.php"; } else { $message = "<font color='red'>Wrong Username or Password. Please try again.</font>"; } } //if $_SESSION "username" and "password" exist, check for consistency. if (isset($_SESSION['username'])) { $username = $_SESSION['username']; $loginstatus = " <table cellspacing='0' cellpadding='0'> <tr> <td align='right'><b>$message</b> <a href='logout.php'>[logout]</a></td> </tr> </table> "; } else { $loginstatus = " <b>$message</b> <table cellspacing='0' cellpadding='0'> <form action='index.php' method='post'> <tr> <td><b>Username: </td> <td><input type='text' name='username' class='inputbox'></td> <td> <b>Password: </td> <td><input type='password' name='password' class='inputbox'></td> <td> <input type='submit' value='Log In' class='submitbutton'></td> </tr> </table> </form> "; } echo $loginstatus; ?> Hello: I am using this tutorial to make a secure login system (if there is a "better" way, please let me know): http://tinsology.net/2009/06/creating-a-secure-login-system-the-right-way/ I am having a problem with the login form - it keeps moving to the "a_Home.php" page (the one that is suppose to be password protected) without any login information being entered. This is the mmLogin.php page: Code: [Select] <?php include('../include/myConn.php'); include('include/myAdminCodeLib.php'); session_start(); $username = $_POST['username']; $password = $_POST['password']; $username = mysql_real_escape_string($username); $query = "SELECT password, salt FROM users WHERE username = '$username';"; $result = mysql_query($query); if(mysql_num_rows($result) < 1) { header('Location: mmLogin.php'); die(); } $userData = mysql_fetch_array($result, MYSQL_ASSOC); $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) ); if($hash != $userData['password']) { header('Location: mmLogin.php'); die(); } else { validateUser(); header('Location: a_Home.php'); } ?> <html> <head></head> <body> <form name="login" action="mmLogin.php" method="post"> Username: <input type="text" name="username" /> Password: <input type="password" name="password" /> <input type="submit" value="Login" /> </form> </body> </html> This is the a_Home.php page: Code: [Select] <?php include('include/myAdminCodeLib.php'); include('include/myCheckLogin.php'); ?> <html> <head></head> <body> <a href="mmLogin.php">Log Off</a> </body> </html> This is the myCheckLogin.php page: Code: [Select] <?php session_start(); if(!isLoggedIn()) { header('Location: mmLogin.php'); die(); } ?> This is the myAdminCodeLib.php page: Code: [Select] <?php function validateUser() { session_regenerate_id (); $_SESSION['valid'] = 1; $_SESSION['userid'] = $userid; } function isLoggedIn() { if(isset($_SESSION['valid']) && $_SESSION['valid']) return true; return false; } function logout() { $_SESSION = array(); session_destroy(); } ?> Can anyone tell me why this is not working? And, am I calling the functions properly? Thanks. |