Jump to content

new to php


shadowayex

Recommended Posts

Ok, I've used PHP once and that was to make a page for a site of mine that showed the outcome of two things mixed together for a game. But now I want to build a website totally out of pHP and there's a lot of things I don't get. I read through the tutorials, and like 90% of the other tutorials I've read, I didn't get much of it. About the only thing I retained was that you use HTML in the page as the display stuff. I've pretty much mastered HTML and CSS so I'm good there. I just didn't retain a thing about php. So like, the home page to the site basically just talks about what you can do with the site and has two major links, Login and Signup. I know kinda how to do quarries to the MySQL server to get information and all that. But can someone give me an example of what each PHP code and form would basically look like and kinda teach me what each part odes. The tutorials are ok, but I learn better if someone teaches me how to do what I wanna do, not general sutff then leave me to figure out what goes where for what I'm doing. Sorry if I'm being an annoyance. Hope someone replies soon. Thanks.

Link to comment
Share on other sites

  • Replies 53
  • Created
  • Last Reply

About the only thing you've got about PHP is not exactly correct, which is why you don't get the rest.You don't "use HTML in the page as the display stuff". What you do is automatically generate it with PHP.Try to make something more simpler first. For example, create a PHP file with the following contents:

<?phpif (isset($_GET['myVariable']) {echo $_GET['myVariable'];}else {echo 'In the URL, add "?myVariable=" + something else you want. Whatever you write after the "=" will be written on the screen instead of this message';}?>

This sample code demonstrates quite a few general things in very few lines. First, when you open the page, you should see the message on the second "echo" statement. If you look at the page source at that moment (i.e. in the web browser, right click and select "View Source"), you'll see ONLY that text. No other text, nothing. This is because PHP is first processed and returns whatever you have created with it. The user never sees the PHP code, it sees whatever was generated, and the generated thing may be ANYTHING, not always HTML.If you follow those instructions, you'll see whatever you have written in the URL, or you'll see an empty page if you don't write anything after the "=", since PHP won't have anything to "echo".Read W3Schools' tutorial on $_GET variables to understand better how they work. The only thing I'm trying to say here is that HTML and PHP have nothing to do with each other "directly" as in "they don't interact". PHP just generates the HTML code your browser sees, and may be used to generate anything else.[edit]Opps. I missed a ")" on the "if" line before the "{". Still, I see you've got my point... well... at least I think you did.[/edit]

Link to comment
Share on other sites

Ok, I tried what you said, but it said "Parse error: parse error, unexpected '{' in /home/www/dw2.freehostia.com/blah.php on line 2", but I think I get what's supposed to go on. If I understand right it's just supposed to display "In the URL, add "?myVariable=" + something else you want. Whatever you write after the "=" will be written on the screen instead of this message" and if i added "?myVariable=RandomText" it would say "RandomText" on the screen, right? I hope that's right. But I'm more interested in the $_POST since from what I understand that's the better one to use for sign in and sign up things. $_GET displays stuff in the URL and $_POST doesn't, right? Ok lets say I'm making the registration form for my site. The basic HTML would look like this (without all the CSS formating):

 <!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" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>Register</title></head><body><form action="signup.php" method="post"><div>Desired Username: <input type="text" name="username" value="" /><br />Desired Password: <input type="password" name="password" value="" /><br /><input type="submit" name="submit" value="Sign Up!" /></div></form></body></html>

Now I'm just gonna wing it and try to type the PHP for it:

<?php$link = mysql_connect('mysql4.freehostia.com', 'Name, 'Database Password')    or die('Could not connect: ' . mysql_error());mysql_select_db('Database Name') or die('Could not select database');mysql_query("INSERT INTO users (Username, Password) VALUES ('$username', '$password')");mysql_close($link);?>

Is that anything close to right at all? If it is all probably have a heart attack. I just used the same principle from the other one I did except this is a INSERT not a SELECT, so I honestly basically winged it with the mysql_query part.

Link to comment
Share on other sites

That's pretty much it, but you don't do any validation. You should use a SELECT statement to check if the username already exists, check to make sure the username and password aren't empty or if you want to exclude certain characters, or make them a minimum length, or whatever. But yeah, that will get the username and password from post and add them to the table. Whenever you get anything from $_GET, $_POST, or $_COOKIE and use it directly in a SQL statement you also need to escape it to prevent SQL attacks. Oh, and you also need to get the variables from $_POST, it's not enough to just use the same variable name in the PHP script.

...$username = mysql_real_escape_string($_POST['username']);$password = mysql_real_escape_string($_POST['password']);mysql_query("INSERT INTO users (Username, Password) VALUES ('$username', '$password')");...

Link to comment
Share on other sites

Ok, I'm not sure what the validation is, I just kind of looked up stuff and put it together from what you taught me last time. Now if I wanted to do the code including the escape thing, it would look like this:

<?php$link = mysql_connect('mysql4.freehostia.com', 'Name, 'Database Password')    or die('Could not connect: ' . mysql_error());mysql_select_db('Database Name') or die('Could not select database');$username = mysql_real_escape_string($_POST['username']);$password = mysql_real_escape_string($_POST['password']);mysql_query("INSERT INTO users (Username, Password) VALUES ('$username', '$password')");mysql_close($link);?>

Minus whatever the validation thing is you said I don't need. And the select thing... would I add something like

$check = mysql_query("SELECT * FROM users WHERE Username='$username'")

And then I hit a block. I'm pretty sure right there I need an if statement that says "If the username exists, don't insert and display 'Username taken'...Else continue with the insert" but I'm not too sure on how to state that.Am I right at all about that?

Link to comment
Share on other sites

The line of code you posted will get a result set from the database. If there were rows that matched the query, or if there were users that matched the username, then there will be at least one row in the result. If not, there won't be any rows. You can use the mysql_num_rows function to find out how many rows are in the result. So it could be set up like this:

<?php$link = mysql_connect('mysql4.freehostia.com', 'Name, 'Database Password')	or die('Could not connect: ' . mysql_error());mysql_select_db('Database Name') or die('Could not select database');$username = mysql_real_escape_string($_POST['username']);$password = mysql_real_escape_string($_POST['password']);$check = mysql_query("SELECT * FROM users WHERE Username='$username'");if (mysql_num_rows($check) == 0){  mysql_query("INSERT INTO users (Username, Password) VALUES ('$username', '$password')");}else{  echo "already taken";}mysql_close($link);?>

Link to comment
Share on other sites

If its a registration system code your after i can help you out there.

<?php$link = mysql_connect('mysql4.freehostia.com', 'Name, 'Database Password')	or die('Could not connect: ' . mysql_error());mysql_select_db('Database Name') or die('Could not select database');$username = mysql_real_escape_string($_POST['username']);$password = mysql_real_escape_string($_POST['password']);/*encrypted password*/$password_hash = md5($password);$check = mysql_query("SELECT * FROM users WHERE Username='$username'");if (mysql_num_rows($check) == 0){  mysql_query("INSERT INTO users (Username, Password) VALUES ('$username', '$password_hash')");}else{  echo "already taken";}/*security procedure*/mysql_free_result($check);mysql_close($link);?>

I changed the script to encryprt the password and insert the encrypted password to the database. For the hashing i used md5(), you might want to read up about that. I also added a bit of code to help prevent SQL injections.

Link to comment
Share on other sites

Ok, so I've got everything up until the hash thing and the freeing thing. What are those? Well, I understand that the hash thing encrypts passwords, but like... is that what I should use? Is there any other sercurity things I need? I've got everything but security covered I think.Also, lets say I wanted to limit what ages use the site and all that. I don't think I will but in the future I'll probably need the skill.

Link to comment
Share on other sites

Well, i think the hashing of the password is a neccersary feature. This will encrypte the passwords in your database. It is very easy to use. On your login script you could do this:

<?php/*Notice here you are defining the passwordinputed by the user > encrypting it and usingthe encrypted password as a variable too. */																																																																																				username = $_POST['Username'];$password = $_POST['Password'];/* Hash the password for security */$pass_hash= md5('$password');/*Then you can do your query'ng heremake sure to select with the $pass_hashas this is what is saved in your table */?>

You might want to add the mysql real escape string to the above also the mysql_free_result read here For the date of birth you could do this -you can read more here.

/* create a form */Please enter your year of birth -<form action="agechecker.php" method="post"><input type="text" id="id" name"age"></form>/* Lets say the age limit is 20ie 20 years back from now in 1987.The user must enter 1987 or below to gainaccess. */$user_year = $_POST['age'];$default = 1987;if ($user_year > $default) {	echo "You are too young to use this website";} elseif ($user_year <= $default) {	echo "Age allowed <a href="www.yourwebsite.com/registrationform.html> click here to continue </a>;} else {	echo "Error - please input your year of brith, <a href="www.yourwebsite.com/ageform.html> back </a>"";}/* This will take into account the yearonly and not the month or day. */

Good Luck! with your new website.

Link to comment
Share on other sites

Ok, so I've got everything up until the hash thing and the freeing thing. What are those?
Hashing is one-way encryption, it can't be decrypted. There are several hashing algorithms in use, MD5 is one of the older ones and is going out of use now, it's quicker to break MD5 these days then it used to be. MD5 uses a 32-byte hash, for greater security you can use SHA-1 which uses a 40-byte hash, or another SHA variant like SHA-256 or SHA-512. I still use SHA-1 for most of my day-to-day things. The way password hashing works is you hash the password that they enter, store the hash in the database, and then when someone logs in you hash the password they entered and compare the hashed password against the hash in the database. If the hashes match then (presumably) they entered the right password. For SHA-1, the chance that they enter a word that is different then the original password but has the same hash is 1 in 1.461501*1048, for MD5 the chance is 1 in 3.402823*1038. Even if the passwords are hashed if someone gets ahold of your database they can run a dictionary attack against it to try and determine people's passwords based on the hashes. To prevent that, you can add a salt to your hash (sounds tasty). Do a Google search for salting a password to read about that.You call mysql_free_result if you want to free the memory from a MySQL result set. It's always a good practice to free memory when you're done using it, but not necessary, as all memory will get freed when the script ends. The server might run faster if you keep freeing up memory but it doesn't help anything else like security. If your server is limiting how much memory PHP can use, you might need to free memory periodically if your script is memory-intensive. There are ways to free the memory being used by any variable, you use mysql_free_result if that variable is a MySQL result resource. You can use the memory_get_usage function to see how much memory PHP has allocated to it.
$result = mysql_query("SELECT * FROM table");echo memory_get_usage() . " bytes used<br>";mysql_free_result($result);echo memory_get_usage() . " bytes used<br>";

Link to comment
Share on other sites

Ok, I think I have all the information I need with the registration. I'm going to play with stuff for a bit and just see how the stuff works. Now, the next task at hand is the login stuff. Now, once again for variables I know to use $_POST because $_GET puts it in the URL (if I remember right). I could probably make the simple PHP to make the login occur. What I'll need help with is keeping the people logged in and basically how to use the PHP to manipulate the page from before login (where basically your options are look at ads, sign in, or sign up) to display all the user controls so they can make/edit their homepage (my site is a site where you can create a fully personalized custopm homepage with whatever you want on it, within reason of course). I pay attention to the links on PHP sites before and after login and from what i see...it seems everything is all the same page, just added bits of things that change the page almost completely sometimes. I'm not all that sure how all that works, but I'm hoping that messing with my website and getting help in the forums will help. Like I said, the tutorials didn't help me too much. It's kind of more helpful to have people explain it because you can ask people questions. YOu can't ask the site anything.

Link to comment
Share on other sites

You can use PHP's sessions to keep the user logged in, but be careful as sessions can be a major security hole if not handled properly (like for example, if the session UID was present in the URL). With them, you're really opening a can of worms.

Link to comment
Share on other sites

Is there a method that is more secure? You see, I'm running off of a hosting service, and I'm not too sure exactly what security measures they take, but I don't want my site to end up screwed before it gets all that popular. I'm not worried about complexity, I can learn. I just need a safe way to do it.

Link to comment
Share on other sites

Is there a method that is more secure? You see, I'm running off of a hosting service, and I'm not too sure exactly what security measures they take, but I don't want my site to end up screwed before it gets all that popular. I'm not worried about complexity, I can learn. I just need a safe way to do it.
The only more secure method is HTTP authentication, or if you really need more security - HTTPS authentications.Neither however offer the ability to remember credentials thruout windows, or if a user closes a window and returns at the next second. If the user clicks the back button or deletes the cache or... basically anything... they have to enter their username and password yet again.So it's a tradeoff - either security for you and your users but with loss of usability, or ease of use and higher security risk for you and your users + some more complexity for you.
Link to comment
Share on other sites

Sessions aren't really that much of a security risk, just make sure that the server is set up to only use cookies with the sessions, not append the session ID onto URLs. That is a PHP option that you can set in php.ini. There are several other session cookie options you can set like requiring a secure channel for the session cookie. Most sites use sessions, including the forum we're currently on.

Link to comment
Share on other sites

Ok, so sessions = not such a bad thing then. So I'll need to read the sessions tutorial thouroghly then probably come back with a whole bunch of new questions. Prepare to explain what the heck I'll need to do lol.

Link to comment
Share on other sites

Ok, so sessions = not such a bad thing then.
I never meant to say they are "bad". Sorry if I gave you that impression.
So I'll need to read the sessions tutorial thouroghly then probably come back with a whole bunch of new questions. Prepare to explain what the heck I'll need to do lol.
THAT is what I meant. That it is difficult, especially if you don't get it right, and you WILL have h#ll a lot of questions no doubt, some of which may not be answered without a concrete example of your own.
Link to comment
Share on other sites

Well...all the forum told me was a syntax... but I'm gonna try and pull this out of my butt and say that this:

<?phpsession_start();// store session data$_SESSION['views'] =1;?><html><body><?php//retrieve session dataecho "Pageviews=". $_SESSION['views'];?></body></html>

can be edited to look something like this:

<?phpsession_start();// store session data$_SESSION['login']=*whatever goes here instead of 1*;?><html><body><?php//retrieve session data*some fancy code that makes the user stay logged in*. $_SESSION['login'];?></body></html>

Am I right?

Link to comment
Share on other sites

That's how you set a session variable. You don't have to do anything special to make the session stay active, the server will keep the session active for 24 minutes after the last activity by the user. All you need to do is use session_start on any page where you want to read or write session variables.

Link to comment
Share on other sites

  • 3 weeks later...
It makes the session available to PHP. You still need to check if $_SESSION['logged_in'] or whatever you named it is set to say that they are logged in.
Ok, so I start off with the session_start and then... lets see....do i do something like this:
<?phpsession_start();$_SESSION['logged_in'] =*something that makes them stay logged in for a certain ammount of time*;?><html><body>*login form code*<?php$_SESSION['logged_in'];?></body></html>

And then make the submit button activate the session, or am I just retarded and thinking way to into this? Sorry it's been a while since I've posted. Been busy with school.

Link to comment
Share on other sites

You can have a form that requests certain details (i.e. username and password), then use PHP to check that. If it is wrong, don't assign anything to $_SESSION['logged_in'] ! If it is right, you assign a value (anything really can go for your system) to the session variable which is checked at the start of all pages with content only for logged-in users.

<?php	session_start();	if (isset($_SESSION['logged_in'])) {		//Show content for logged in users	} else {		header('location: login.php'); //Redirect them to the login page	}?>

Link to comment
Share on other sites

Ok so that goes in every page. I understand. Now, I know 'logged_in' is a variable. But where's it come from? Do I need to do anything special to make it work? Or is that one of those things that you shove in there just because the server wants it? (i.e. a DIV or similar tag in a Form when you are trying to validate in XHTML Strict)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.


×
×
  • Create New...