i'm using php 5.4.3, I'm wondering if it's possible to use function session_start().

my idea is to have a login page, then use the username in all pages of the site, the problem is that the $username is not visible in the second page...

index.php

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Log in</title>
        <meta name="alex" content="sermail" />

<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#00814B ">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#339900 ">
<tr>
<td colspan="3"><strong>Log in </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="username" type="text" id="username"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="password" type="password" id="password"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

checklogin.php

<?php

// Connect to server and select databse.
 //conecção ao servidor
    $conn = mysql_connect("localhost", "root")or die("sem conecção ao servidor");
    $db = mysql_select_db("sermail")or die("Base de dados não foi encontrada");

// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM members WHERE username='$username' and password='$password'";
$result=mysql_query($sql);

// 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['username'] = '$username'; 
header("location:menu.html");

}
else {
echo "Wrong Username or Password";
}
?>

menu.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">

<head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Sermail</title>
        <meta name="author" content="Alex" />
        <link rel="stylesheet" type="text/css" href="styles/styles.css" />

            <style type="text/css" media="view">
            .printbutton {
            visibility: show;  
            } 

            </style>
             <script LANGUAGE="javascript">
    <!-- defines size of window -->
    function ScreenSize(w,h){
    window.resizeTo(w,h);

    }
</script>
           <script >
          myWindow=window.open('','','width=200,height=100')
          myWindow.document.write("<p>Benvindo <?php ?></p>")
          myWindow.focus()
          </script>


</head><body bgcolor="#00814B" onload= "javascript:void window.ScreenSize(250,640); ">
 <table><tr> <td><img src="imas/sermaillogo.png"></td></tr></table><br/>
   <div>

   <FORM>
<INPUT type="button"  style="color:#000; padding: 2px 5px;font-family: arial;font-size: 14px;height: 30px;display: block; width: 200px;"class="mybutton" value="   Ficha de entrada  " onClick="window.open('formulario.html')"><br/>
<INPUT type="button"  style="color:#000; padding: 2px 5px;font-family: arial;font-size: 14px;height: 30px;display: block; width: 200px;"class="mybutton" value="   Ficha de Palete   " onClick="window.open('palete.html')"><br/>
<INPUT type="button"  style="color:#000; padding: 2px 5px;font-family: arial;font-size: 14px;height: 30px;display: block; width: 200px;"class="mybutton" value="   Ordem de espera   " onClick="window.open('espera.html')"><br/>
<INPUT type="button"  style="color:#000; padding: 2px 5px;font-family: arial;font-size: 14px;height: 30px;display: block; width: 200px;"class="mybutton" value=" Pequisar N.º Ordem  " onClick="window.open('pesquisar.html')"><br/>
<INPUT type="button"  style="color:#000; padding: 2px 5px;font-family: arial;font-size: 14px;height: 30px;display: block; width: 200px;"class="mybutton" value=" Pequisar N.º Palete " onClick="window.open('pesquisarpaletes.html')"><br/>
<INPUT type="button"  style="color:#000; padding: 2px 5px;font-family: arial;font-size: 14px;height: 30px;display: block; width: 200px;"class="mybutton" value=" Pequisar Ordem de espera" onClick="window.open('pesquisacodprod.html')"><br/>
</FORM> 


     <br/><INPUT style="color:#000; padding: 2px 5px;font-family: arial;font-size: 14px;height: 30px;display: block; width: 200px;"type="button" value="Fechar" onClick="window.close()">
        <input type="text" size="10" name="data"                  value="<?php mysql_connect("localhost", "root")or die("sem conecção ao servidor"); 
mysql_select_db("sermail")or die("Base de dados não foi encontrada");$username=$_POST['username'];

$result1="SELECT username FROM members where username = '" . mysql_real_escape_string($username) . "'";
$o1=mysql_query($result1)or die(mysql_error());
if ($row = mysql_fetch_array($o1)) {
    echo $row['username'];
    }
    else {
    echo 'No record found';
    }  ?>"> 
</div>

 </body>
</html>

i can't get the $username in my menu.html page, why?
it's possible that i have one or more ginormouse errors in those pages.

in every html and php page? i supose so, but the problem is that wamp gaves me error's or notices every time i use session_start();...

Script, so PHP files. It must be called before any output is sent to the browser, that's why I said "at the top of every script".

ok!
anyway it's possilble to show in html pages the registred user?

If you include a bit of PHP:

<?php echo $_SESSION['username']; ?>

NOTE: If the extension of your file is .html it will not parse the above PHP command by default. You need to adjust your .htaccess to tell Apache to parse it. See this thread for more info.

how do i do that?

I just don't understand if i have to give the new file a specific name, and where to put it...except for this, great thread(as usual)!

Can you explain what you don't understand? It's not quite clear what the question is.

i have understanded that i need to create a new file with the .htaccess, but i don't know where o put it(USing wamp) and if this file needs to have a specific name.,

.htaccess is it's name. You can put it in the web root folder (c:\wamp\www).

so easy, and i didn't see it, anyway the line i put does not work, have to try other code.

my idea, and i really don't know if it's possible or how to do it, is, create a login field, and guive a user and password to every user,(done) when a user insert some data in the database, i can see who have made that. i´dont need to see which user is logged in in every page.

Just change your code/database, so when you use a query to insert data, you also insert the current username into the record.

is dificult for me to explain myself in english... but i'll try.

how can i tell the php file hich user is logged in? as long as i know(and is not much) it wil only read the vars of the last file, unless.... (that's the code i dont know).

i know how to make the query, but i don't know how to reach a var that a used much earlyer.

That would be the reason for using $_SESSION['username']. The session stores information across scripts.

Perhaps this information will help.

so, i have to use

session_start();
$_session[usermane];

in every php file.

am I wright? (Really hope so...)

By the way, thank you again!

thanks..
i really have a ginormous error..

( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Use of undefined constant username - assumed 'username' in C:\wamp\www\sermail db\entrada.php on line 3
Call Stack

Time Memory Function Location

1 0.0005 170280 {main}( ) ..\entrada.php:0

( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Undefined index: username in C:\wamp\www\sermail db\entrada.php on line 3
Call Stack

Time Memory Function Location

1 0.0005 170280 {main}( ) ..\entrada.php:0

( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Undefined index: username in C:\wamp\www\sermail db\entrada.php on line 17
Call Stack

Time Memory Function Location

1 0.0005 170280 {main}( ) ..\entrada.php:0

 <?php
session_start();
$_SESSION[username];
    //conecção ao servidor
    $conn = mysql_connect("localhost", "root")or die("sem conecção ao servidor");
    $db = mysql_select_db("sermail")or die("Base de dados não foi encontrada");
    // VAr
    //table ordem
    $data = date("dmY");
    $nordem = $_POST['nordem'];
    $guian = $_POST['guian'];
    $ncliente = $_POST['ncliente'];
    $cliente = $_POST['cliente'];
    $fornecedor = $_POST['fornecedor'];
    $nordem_n = $_POST['nordem'];
    $obs= $_POST['obs'];
    $username= $_POST['username'];

   //$query= "select nordem from ordem where nordem='".$nordem."'"; 
  //  $query1=mysql_query($query);
//    if ($_POST['nordem'] == $query1) include("common.php");
  //      $msg = "Nº. ordem já inserido!";
    //    confirm($msg);;


     $sql="INSERT INTO ordem(data, nordem, fornecedor, guian, ncliente, cliente, obs, username)
    VALUES( '".$data."', '".$nordem."', '".$fornecedor."', '".$guian."', '".$ncliente."', '".$cliente."', '".$obs."', '".$username."')";
    echo "</br>";
    mysql_query ($sql) or die(mysql_error());

    $sql2a = 'INSERT INTO entrada ( nordem_n, lote, val, designacao,filtro, familiamarca, quantguia, quantconf, atado, posicao, codprod) VALUES';
    for ($i=0; $i<count($_POST['check']); $i++) {
     if ($_POST['check'][$i] == 0) continue;
     $sql2a .= '('.$nordem.',\'' . $_POST['lote'][$i] . '\', \'' . $_POST['val'][$i] . '\', \'' . $_POST['designacao'][$i] . '\', \'' . $_POST['filtro'][$i] . '\', \'' . $_POST['familiamarca'][$i] . '\', \'' . $_POST['quantguia'][$i] . '\', \'' . $_POST['quantconf'][$i] . '\', \'' . $_POST['atado'][$i] . '\', \'' . $_POST['posicao'][$i] . '\', \'' . $_POST['codprod'][$i] . '\')';
    if ($i<count($_POST['check']) - 1) {
    $sql2a .= ',';
    } 
    } 

    mysql_query($sql2a) or die(mysql_error());
    // pagina inicial, Furmolario.html
    Echo "<a href='formulario.html'>Nova ficha de entrada</a>";

    ?>
    <?php
    mysql_close();

    ?>

is the code correct? anyway, I will read the code until find the error....

No, it's not. You just copied what I mentioned blindly into your code. It was not for use as is, it was just to direct you in the right direction. I suggest you first read the manual.

actualy, i've read it earlyer, but i have a lot of doubts about it, so much i cannot understand..

Just a small and brief session 101:

  1. In every script you want to use session, put session_start() at the top, before any output is sent to the browser.

  2. After your user is correctly logged in store it in the session like this: $_SESSION['username'] = $username;

  3. In any other script, where you want to output the session user: echo $_SESSION['username']; or put it back into a variable with: $username = $_SESSION['username'];

The code you put in the above snippet is missing the single/double quotes around usernames, that's why you got the undefined constant notice.

That's it for this thread (for me).

Thanks, it's much easyer for me (as a noob) to understand this that way.
still get some errors but eventualy, i'll find a way to do it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.