1) "My variables are empty" OR "My script won't work"
"$somevar is blank"
"I copied this script & it won't work"
"I changed hosts/servers & now my script doesn't work"
In recent releases of PHP, the php.ini directive "register_globals" is set to "Off" by default; so the recommended/preferred method of coding variables has changed. Many tutorials and texts/books were written prior to this change, so "I copied this from a book, perfectly" may not have any effect on your situation. You now must call variables from the "SUPERGLOBAL" arrays. Use $_POST['var'] for a POSTED form; $_GET['var'] to obtain a value from a URL. Cookies are $_COOKIE['var'], Session variables are now $_SESSION['var'], etc.
EXAMPLE:
Script one: form.php---
PHP Code:
echo "<form action=\"handle.php\" method=post>";
echo "What's your first name? <input type=text name=FName>";
echo "<br><input type=submit name=submit value=submit>";
Script two: handle.php---
PHP Code:
echo $name; //THIS WON'T WORK!
echo $_POST['FName']; //This returns the value entered in Script One
dalecosp
Remember that $_POST, $_GET, $_SERVER, $_FILES, $_REQUEST, etc., are only valid if your PHP version is > 4.0 --- otherwise use $HTTP_POST_VARS, $HTTP_GET_VARS, $HTTP_SERVER_VARS, $HTTP_POST_FILES, etc.
3) MYSQL/database: "How do I..."
"Getting info from a database..."
"?Select * from ?, huh?"
Using MySQL and formatting its data
MySQL and PHP are pretty much a package deal; together with the Apache Server, they are often referred to as "AMP" - "Apache/Mysql/PHP". Yes, Tux lovers, if you run them on Linux, it's "LAMP" --- pretty !
MySQL is a Structured Query Language, much like MSSQL, and one of the best RDBMS' (Relational DataBase Management Systems). Before moving on check out PHP/MySQL functions at http://www.php.net/manual/en/ref.mysql.php
4 main functions are always used with MySQL and fetching data.
PHP Code:
mysql_connect(); or mysql_pconnect(); //Connect to a MySQL database.
// mysql_pconnect() maintains a permanent connection to the db server; mysql_connect() doesn't.
mysql_select_db('mydbase') // Selects a database named "mydbase" after connection is made.
mysql_query() // Creates a query to select data from a table or tables.
mysql_fetch_array(); or mysql_fetch_object(); // Both do exactly the same thing; extract data from a query.
// The difference is mysql_fetch_aray is done like this:
$var['index']
// and mysql_fetch_object is like this:
$var->index.
To select more than one row of data you will require a loop. The most common loops are while() or foreach(). For this example, we use while();
Assume we have a table named "news" in a database "mysite". We need to extract all the rows from "news" and display them in an HTML table for each article. There are 4 fields (or "columns") in this db table: id, title, date, and message.
PHP Code:
$con = mysql_connect("localhost","usernamehere","passwordhere");
// "localhost" is used if the db server is on the
//same computer the web server is on....
$selectdb = mysql_select_db("mysite",$con);
$query = mysql_query("SELECT * FROM news");
// Creates an array of items with keys corresponding to table columns...
while($row = mysql_fetch_array($query)){
//Create the HTML table
echo "<table><tr><td>NewsID: ".$row[id]." Title:".$row[title].";
echo "</td></tr><tr><td>Date: ".$row[date]."<br />".$row[message]."</td></tr></table><br />";
}
There you go... simple, isn't it? Though you can do it a differently with a foreach() statement. There are other functions, but these will take you a long way....
planetsim
4) Sessions and Cookies
Sessions and cookies are argued about all over the Board - which is better? Let's see why people are arguing.
Sessions:http://www.php.net/manual/en/ref.session.php Before a session can exist it first must be started ( session_start(); ) and then the session registered ( session_register(); ). Although you can bypass the session_register by using the $_SESSION or $HTTP_SESSION_VARS superglobal arrays.
Here is a simple session code:
PHP Code:
<?php
if (!session_is_registered('count')) {
session_register('count');
$count = 1;
}
else {
$count++;
}
?> Hello, Visitor! You have seen this page <?php echo $count; ?> times....<p>
To continue, <A HREF="nextpage.php?<?php echo strip_tags (SID)?>">click here</A>
This just counts how many times a visitor has visited that page. Sessions need to be registered but can also be unregistered using... session_unregister().
So, when to use sessions? Most of the time you should use a session in an admin or to keep track of a user on the site. Let's create a simple Session which stores a username, then gets validated on each page.
#check if account exists
$qstring="SELECT * FROM users WHERE username = '";
$qstring.=$_POST['user']."' AND password = '".$_POST['pass']."'");
$qry = mysql_query($qstring);
$numrows = mysql_num_rows($qry);
if($numrows < 1){ // If no return fr. database, the account doesn't exist....
}else{
session_start(); // start the session...
$_SESSION['user'] = $_POST['user']; // Registers the session user. If the POSTed username was "badman",
// then $_SESSION['user']=="badman"
}
//End of Validating
//The Check log
function checkLog(){
global $_SESSION;
if(session_is_registered("user")){
#add code to validate the user in the db
}else{
session_unregister("user"); // unregister the session
header("location: index.php"); // send them to the "home page"....
}
}
That example probably doesn't work; But you get the idea. What I haven't explained is that sessions only last as long as the browser is open, or until the session expires. About 5 minutes if browser inactive.
Cookies are simpler than Sessions; Site Administration scripts shouldn't use them, but they're great for forums, etc.
Creating a Cookie
PHP Code:
setcookie(); // Will create the Cookie
$_COOKIE['somename']; //Will get the cookie name and validate it when necessary.
O.K. --- the basics of setcookie();
setcookie ( name , value , expire , path , domain , secure);
name - name of the cookie. value - value of the cookie. This value is stored on the clients computer; do not store sensitive information. expire - time the cookie expires. This is a unix timestamp (number of seconds since the epoch) In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). path - The path on the server in which the cookie will be available on. domain - The domain that the cookie is available secure - Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0.
5) Security
This isnt just PHP Related. For any person developing Server Side Web Applications should follow simple steps to stop people bypassing into areas they shouldnt be etc.
PHP - Make sure the register_globals = off. This will mean that you'll need $_POST etc.
The reason for this. Imagine you have an include include($page); in a querystring. What would happen if the user created a file on another server, and made it copy Database data, Passwords etc on your server by simply doing this index.php?page=http://website.com/deadlyscript.php
By using $_GET or $HTTP_GET_VARS, you limit only to querystrings.
Then by validating the data by using either a switch statement or if/else statement to make sure the data that is being entered from the querystring is correct.
Forms are a big problem. People can put clever yet annoying Javascript Functions in your script simply by entering in the Javascript code into a form.
You should always make sure you use strip_tags(); and use the htmlentities etc. Before using any information from a form. Some simple things like bin which gets inserted into your database can be fatal.
Never use cookies as a way to access your Site Admin, use sessions, this will make sure you always have to login via a form, before accessing the admin.
With Admins and accounts, make sure passwords are encrypted by using md5();. When needing to check the password just use md5() to see if its exact.
If you ever have forms that require Javascript to validate. Make sure you have some sort of php function that checks the same material that the Javascript is validating. Reason for this is Javascript could be off, Javascript isnt always accurate.
Just following these simple steps can stop many fatal errors occuring, and keep your Web Site Secure.
If anyone else has things they think should be added to the list, please go right ahead.
As you can see there are 3sub arrays in the array $fruits.
When to use two-dimensional arrays?
I liked an example when i first learnt arrays, was a person, and we had got all his details. Eg, Name, Age, Location.
From there we can make sub arrays
name => array("Firstname","Surname");
age => "40";
location array("Address" => "7 Goodwill Ln",
"PostCode" => "2234";
);
Thats just an example.
PHP Code:
$person = array("Name" => array("Andrew","Gibson"),
"Address" => array("Street" => "7 Goodwill Ln","PostCode" => "2234", "State" => "QLD", "Country" => "Australia"),
"Age" => "40"
);
//Getting the information from an array wont be as easier as previous version
Use is_numeric() to help validate data that is expected to be numeric.
It is also possible to treat the data as a string and use regex to check that all characters are valid.
Use htmlspecialchars() or htmlentities() when writing output that you arent certain of.
This takes care of insertion of html or malicious clientside scripting.
Use strip_tags() if you dont want any of these tags at all.
Remember to escape strings entered into databases.
You might want to use addslashes() if the data is not already escaped.
However, different database systems may require other ways to escape characters that could potentially allow SQL injection.
Storing md5() hashes as passwords doesnt necessarily add more security, but it does make it more difficult to obtain the user's original password if this password is intercepted.
Cookies are an acceptable means of authentication if you dont need much security, but be warned: they can be spoofed easily.
Using sessions can be better, but again these methods arent foolproof.
If you need something stronger, you'll have to use encryption, SSL, https etc
When i was a plain blank A4 paper, i wish something could be written on the paper, later I discovered that i don't really like ink. How i wish i could return to the blank white sheet.
alone in the dark rough wave middle ocean pacific. How tiny i am.
Dont believe it.. forgot to acknowledge the real begginers..
Ok
For those with no idea in PHP.. Heres the basics
PHP means PHP Hypertext Processor.. Before that it was more well known as Personal Home Page.. thus the PHP..
Before we can go on and just create php we need a webserver.
The best solution would be Apache i suggest people download the 1.3.x version. As its the most stable.
There are a couple of ways to download it..
As a MSI. Get this if your Windows,
Zip - Dont sugget anyone reading this thread to get it.
I assume most of you are Windows Users, so download the MSI version of it.. Approx 2-3mb
remember to test if it installed correctly by going to. http://localhost once you have started the apache server.
From there you'll need to install PHP once again you can goto the site i suggested it has how you install it, the tutorial is quite old yet shouldnt be any different in installation.
If you dont want the tutorial.. goto http://php.net and download the PHP Installer. exe file about 900kb if i remember correctly.
Follow the prompts. When you get to which server you want to install.. Select apache, you should recieve an error saying something like, Couldnt get to requested server or something a long those lines.
That will mean you'll have to do this in the httpd.conf file.. Located in the Apache/Conf Directory.
Before coding, designing graphics and creating your database/flat file system. You should plan your site.
Many of you more experinced programmers if your reading would know what its like when not planning a site, and in the middle of creating it, you want more features in it, eventually you keep adding them, and you have no idea when your project will finish, because as your adding your new features, your fixing code that wont work with the original design.
Ok so why Plan?
If you read the paragraph above you'd see what kinda mess you could become of not planning. Planning is a crucial step in creating your website.
So what do i plan?
Before we start planning. Brainstorm ideas, you should have some idea on what the site is about and title.
Get ideas on:
What you want in the site
How you want data to be displayed
What language you want to use.
How long each step should take (Not really important but can give you some sort of timeframe of the project)
What things require a database
Planning
After brainstorming you should now plan your ideas.
First id plan your database design or flatfile system. Which ever method you'll be using.
When designing, make sure you do it on paper, so you know if your gonna have relationships between tables. (This is a must it can make those queries a lot easier)
After designing the database its graphics time. Im not graphic designer, but a good way of creating your main design is to create the page and how its gonna look, then cut it up(I use Photoshop) not sure on what other people have but most have the feature of cutting the image.
Once you have graphics, design the site in html. This way you have the Graphics and HTML done, its only the php. Most newbies love having html code with there php code, eventually most grow out of it (yay).
Then its all php code the rest of the way.
Now once you have planned your site, dont add features until the project is finished. This way you can go back on the plan and add it. Check if theres relationshipts / extra tables needed and/or graphics needed.
Then you can code it.
The smart programmers do this, its why they can finish that project fast and things work smoothly. You can see when a programmer isnt smart its when they have errors, 6times out of 10 its when a programmer has added a new feature.
I'd just worry about this example regarding sessions:
PHP Code:
function checkLog(){
global $_SESSION;
if(session_is_registered("user")){
#Validate the user in the db
}else{
#Unregister the session
session_unregister("user");
header("location: index.php");
}
}
Since $_SESSION is always available, it doesn't need to be declared global.
Also, as the manual strongly notes, it's not a good idea to go mixing $_SESSION with session_register(), session_is_registered() and session_unregister();. They don't do anything that can't be done with the $_SESSION array:
PHP Code:
function checkLog(){
if(isset($_SESSION['user'])){
#Validate the user in the db
}else{
#Unregister the session
$_SESSION['user']=null;
header("location: index.php");
}
}
Actually, since PHP 4.3, I think unset($_SESSION['user']) will work - in PHP4.1 and 4.2 it wouldn't 'cos of a PHP bug.
The 2nd comment I made (in the first section) says "THIS WILL RETURN THE VALUE". It should say "PRINT" instead of "RETURN". AFAIK, echo() will only return boolean(?) T/F.
Also, there are at least 3 lines in the code examples that should be broken up for easier reading; the worst offender is in the "Let's assume I have a database called news" example.
Hey, Planetsim; I spent some time putting together the version with bold titles and attributions; if you get some time can you edit the post and insert that version instead?
Please don't think I'm being an*l here --- jus' figured if people are going to read it, might as well be the best it can....
Last edited by dalecosp; 07-03-2003 at 10:55 PM.
/!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade!/!!!\ ereg() is deprecated --- don't use it!
dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket
Warning: session_start(): open(/tmp\sess_30a5cf085c97b8062247eb482e99715b, O_RDWR) failed: No such file or directory (2) in C:\program files\Apache2\htdocs\whatever\foo.php on line 2
If you're using Windows, you have to specify the temporary directory in php.ini - "session.save_path" if I recall. "/tmp" is the default for Un*x systems.
Bookmarks