Solved

Functions -n- Subs

Posted on 2002-03-13
12
247 Views
Last Modified: 2006-11-17
Hi..

i always used to write dynamic web pages with MS-ASP, i am now converting my work to PHP, i want to ask a coulpe of things here, ALL points are to go for the best, and easiest for me to understand answer !!

1- Easiest way to make a function that will send/get simple encrypted cookie cookies, something like
<? sendcookie("/","name","value","valid_for_x_days") ?>

2- Easiest way to deal with session variables, something like session("username") in ASP, how to get them, how to set them .

3- A Simple 2 functions to access MySQL database, something like
<? OpenMyDatabase ?>
<?
QUERY HERE
?>
<? CloseMyDatabase ?>

4- Easiest way to deal with querystrings and server_variables, in ASP it is like
request.querystring("NAME")


===========================
thanx in advance .
0
Comment
Question by:neostudio
  • 4
  • 3
  • 2
  • +2
12 Comments
 
LVL 5

Expert Comment

by:andriv
ID: 6863354
1) To set a cookie you use the setcookie function, the syntax is:

setcookie(name,value,expire,path,domain,secure)

The return value is true if the cookie is created and false if not. The expire, path, domain and secure arguments are optional. Name is the variable name, value is the value of the variable, expire sets a time when the cookie will automatically be deleted by the browser. The expire argument is in the form of seconds sine January 1,1970.

Cookies are headers and should be place before any content is sent to browser. Best to put at the top of the script.

example:
setcookie("lastVisit","yes",time()+86400);

The cookie above will contain the variable 'lastVisit' and have the value of 'yes'.

2) To create sessions you need to start sessions first with,

session_start();

To create a session variable you need to register it first:
session_register("first_name","last_name");

Then within your script you can give them values:

$first_name = "John";
$last_name = "Doe";

Again, sessions are headers so they must be place within the script before any content is sent to the browser.

3)  To work with mysql you must first connect to the database and you can do this with either mysql_connect or mysql_pconnect.  They both have the same arguments, the only difference is that mysql_connect will automatically close the connection after the script ends and mysql_pconnect the connection is persistent, in other words it will not automatically close when the script is finish. It will remain open until the server process finishes or you use the mysql_close() function.

To Query the database you use the mysql_db_query function

mysql_db_query(db_name,query,link);

Example:
//if no password is needed omit it in the argument
$link=mysql_connect("host","username","password");

$Query="Select * from tabl_name";

$result=mysql_db_query("dbname",$Query,$link);

mysql_close($link);

Now $result contains the information:

4) To get the information you need to loop through and pull it from $result:

while($row=mysql_fetch_array($result))
{
print("$row[0],$row[1],$row[2]<br>");
}

in the above code the while loop will loop the each record one at a time until no more records.
The $row=mysql_fetch_array($result) will take the current record and create an array called $row the fields are index with numbers starting from 0, so the first field is $row[0] the second is $row[1] and so on.  They are also index by the field name so you can also reference a field by the column name as follows:

$row[field_name];

Hope this was helpful.


0
 
LVL 2

Expert Comment

by:Marsman_
ID: 6863731
Do not use session_start(). There are a number of problems that may occur when you use this and sessions work perfectly without it.
To send a query I use mysql_query("query") but I guess mysql_db_query also works.
0
 
LVL 8

Expert Comment

by:us111
ID: 6863823
2.
To set the session:
if ($PHPSESSID)
   session_start($PHPSESSID);
else
   session_start();

$value="10";
session_register("value");
// session_unregister("value"); // to unset the var

Into the next page, to get the session
if ($PHPSESSID)
   session_start($PHPSESSID);
else
   session_start();
print $value;  // display 10

4.
just get the variable (POST or GET) with $your_variable. You don't need request.... like ASP
0
 
LVL 5

Expert Comment

by:andriv
ID: 6863859
Marsman,

Just curious, what problems do you have with the session_start().  I'm interested because I have been using it for a long time in all my scripts and if there is a problem I have fix my scripts. But as far as I know there isn't anything documented about a problem.

What session_start does is looks for an existing session, and if none
exists, it creates a new one.  What it also does is looks
for any session variables, and sets them globally on the page that start
got called from.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 6864044
Just a quicky, but when you use

if ($PHPSESSID)

should that not be

if (isset($PHPSESSID))

Richard Quadling.
0
 
LVL 8

Expert Comment

by:us111
ID: 6864102
both works
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 3

Author Comment

by:neostudio
ID: 6864110
Hi All..

Andriv>>
your answer is great, but it is most talking about the principles of how things are done, and as i already written pages in other languages, it seems i know all these principles, i need some dedicated examples for these tasks .

here is a mixed example for all tasks in one page...
lets say..
i have /test.php

when a user enteres, the script must get the username from the cookie, set it as a session variable, and get his email from a mysql_database, and set it also as a session variable .
if no username in the cookie, assume username is TEST, and do the same ( set it as a session variable and return in as a cookie ) !!


Regards,
</Ruslan>

0
 
LVL 2

Expert Comment

by:Marsman_
ID: 6865111
I just remember I tried using session_start and it didn't work. Than someone said to me: "don't use session_start" so I did and it worked perfectly. When I think about it, it must have had something to do with the fact that the code was in a file that was included often and session_start was executed a number of times or something. Now I see in the other comment that this can be solved with:

if ($PHPSESSID)
  session_start($PHPSESSID);
else
  session_start();

But you do not need this. If you read the manuals it sais sessions are started automatically when session_register is called and a session does not yet exists. So I always keep it simple and do not use it. session_register is al you'll ever need to use sessions (except for the SID in urls of course). I love php :)
0
 
LVL 5

Accepted Solution

by:
andriv earned 180 total points
ID: 6865311
If you do not use some form of session start you are a risk of another session being created which will then cause problems.  I too like the example that RQuadling used.

nuostudio, here is an example:

session_register("username","email");

//If  cookie get username
if(isset($username)
{

$username = $username;

$dbconnect = mysql_connect("localhost","user","password");

$Query = "Select email from table_name where ";
$Query .= "username = '$username'";

if(!($result=mysql_db_query("dbname",$Query,$dbconnect)))
{
print("mysql_errno: mysql_error");
exit;
}

$row = mysql_fetch_row($dbconnect);
$email = $row[1]; //assuming that first field is username and second is email

}
else
{
$username = "Test";
setcookie("username",$username,time()+86400);

}


The above code assumes that if there is a username that a record with email address will be found in the database. In either case a session is created, if no username "Test" is used by default and cookie is created.  If you have a default email address just add it to the else condition.

0
 
LVL 3

Author Comment

by:neostudio
ID: 6865438
Andriv thank you..
was so clear and helpful !!


Regards,
</Ruslan>
0
 
LVL 5

Expert Comment

by:andriv
ID: 6865516
No problem, If you need more help just let me know in this thread I will continue to do the best I can regarding this question.
0
 
LVL 3

Author Comment

by:neostudio
ID: 6867265
well,
i do not like to look stupid but..

here..
if(!($result=mysql_db_query("dbname",$Query,$dbconnect)))
{
print("mysql_errno: mysql_error");
exit;
}


what is this exclamation mark
if (!($result.......
what does it mean ?
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now