Hello, folks.

I got another problem.

Basically, I wanna check if someone is old enough to watch a movie.

I got 2 sessions - one for the certificate( 12, 15, 18) and 1 for the year of birth.

My question is can i use somtehing similiar to this or? Cause now is not working...

<?php
session_start();


if  (!(isset($_SESSION["gatekeeper"]) && $_SESSION['gatekeeper'] !=''))
{
	header("Location:mainpage.php");
   echo "Not an user, leave";
}
else
		
{
		echo "<center><h3>You are logged in as " . $_SESSION['gatekeeper'] . "</h3></center>";


// Read the quantity from the query string on the searchresult.php
$old = 2012 - $_SESSION['agez'];

if ($old < $_SESSION['certificate'])
{

echo "<script type ='text/javascript'> window.alert('Sorry, you are not old enough')</script>";

exit;
}
else
{
// Echo the form, with hidden fields containing the quanti

echo "<form method='post' action='buyfilm2.php' >";
echo "The quantity of tickets you want to buy?: <input name='maxtickets' value='1' />";
echo "<input type='hidden' name='id' value='$_GET[filmID]' /> ";
echo "<input type='submit' value='Go!' />";
}
}

?>

Line 8 will never get executed, but that is not the problem anyway. The code seems OK. What actually is not working? Please describe (error messages, what is supposed to happen but it does not...).

I am aware of the 8th line, however the script works but it doesn't do what it has to do. For instance, it always load the page even if the user is not old enough.

Member Avatar for diafol

I'd use a DOB not an age, as you can be different ages in asingle year, depending when you have your birthday.

$MyDob = '10/10/1968'; ..this comes from a form etc (many formats allowed e.g. US / European)

$myDobF = strftime('%Y-%m-%d', strtotime($MyDob));
$dob = new DateTime($myDobF);
$current = new DateTime(date('Y-m-d'));
$interval = $dob->diff($current);
$age = $interval->format('%y');

Then check - but actually needs to exist

if($age < $_SESSION['certificate']){
  header(...);
  exit;
}else{
  ...
}

Still doesn't work, I can still see the page even if I am underaged. :(

Can I actually get from a form $dayofbirth, $yearofbirth, $monthofbirth from my database and put it into

$myDobF = strftime('%yearofbirth-%monthofbirth-%dayofbirth', strtotime($MyDob));
    $dob = new DateTime($myDobF);
    $current = new DateTime(date('Y-m-d'));
    $interval = $dob->diff($current);
    $age = $interval->format('%yearofbirth');

?
And can I also store $age in to a $_SESSION variable after that?

Member Avatar for diafol
$myDobF = strftime('%y-%m-%d', strtotime("$dayofbirth/$monthofbirth/$yearofbirth"));
//and
$age = $interval->format('%y');

you can store what you like in a session. Just remember to place session_start(); as the very first thing at the top of EVERY page. Then:

$_SESSION['age'] = $age;

I have no idea how to fix this, the code seems alright, I have no idea where the problem is. It is always displaying the page even if the user is 1 years old and there is a minimum age of 18....I will make it properly after I fix that bloody thing... :S

<?php
if(!isset($_SESSION))
{
session_start();
}  



	if  (!(isset($_SESSION["gatekeeper"]) && $_SESSION['gatekeeper'] !=''))
{
	echo "Not an user, leave";
	header("Location:mainpage.php");
	exit;
}
	else
{

	echo "It's displaying the age" . $_SESSION['old'] . "WTF";

	if ($_SESSION['certificate'] > $_SESSION['old'])
		{
	header("Location:mainpage.php");
	exit;
		}
	else
{

echo "<center><h3>You are logged in as " . $_SESSION['gatekeeper'] . "</h3></center>";


// Read the quantity from the query string on the searchresult.php



// Echo the form, with hidden fields containing the quanti

echo "<form method='post' action='buyfilm2.php' >";
echo "The quantity of tickets you want to buy?: <input name='maxtickets' value='1' />";
echo "<input type='hidden' name='id' value='$_GET[filmID]' /> ";
echo "<input type='submit' value='Go!' />";

}
}

?>

Ah need help here, got stuck. Anyway

Thisi s my form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php


include('functions.php');
write_head("Solent Login Page", "newCSS");

?>
<body>

<div id    ="body"    >
<div id    ='sidebar' > <form method='post' action='login.php'>
<label for = 'username'> Username:</label>
<input name='username' id='username'/><br/>  
<label for = 'password'>Password:</label>
<input name='password' id='password'/><br/>
<label for ='yearofbirth'> Year of Birth:</label>
<input name='yearofbirth' id='yearofbirth' /><br/>
<label for ='monthofbirth'> Month of Birth:</label>
<input name='monthofbirth' id='monthofbirth' /><br/>
<label for ='dayofbirth'> Day of Birth:</label>
<input name='dayofbirth' id='dayofbirth' /><br/>
<td>Admin?</td> 
<td>
<input type = "checkbox" name = "isadmin" value = "1" /> Yes
<input type = "checkbox" name = "isadmin" value = "0" /> No
</td>
</br>
<input type='submit'  value='Log in' /></form>
<!-- / end of login page -->
</div>

</body>
</html>

This is my PHP script

<?php
//prevent sql injesctions
session_start();
error_reporting (E_ALL ^ E_NOTICE);
// for error handling
ini_set('session.bug_compat_42',0);
ini_set('session.bug_compat_warn',0);

$uname 	= $_POST["username"];
$pword 	= $_POST["password"];
$ybirth = $_POST["yearofbirth"];
$ybirth = $_POST["monthofbirth"];
$ybirth = $_POST["dayofbirth"];
$admin  = $_POST["isadmin"];
$num_rows = 0;
$errorMessage = "";

$uname  = htmlspecialchars($uname);
$pword  = htmlspecialchars($pword);
$ybirth = htmlspecialchars($ybirth);
$mbirth = htmlspecialchars($mbirth);
$dbirth = htmlspecialchars($dbirth);
$admin  = htmlspecialchars($admin);


$myDobF = strftime('%y-%m-%d', strtotime("$dbirth/$mbirth/$ybirth"));
$dob = new DateTime($myDobF);
$current = new DateTime(date('Y-m-d'));
$interval = $dob->diff($current);
$age = $interval->format('%y');



if(!ctype_alnum($uname))
{
    echo "ERROR: Input contains characters other than letters and numbers.";
}



$conn = mysql_connect("localhost", "yvrachev", "Eer3num6") or die("cannot connect"); 
mysql_select_db("yvrachev") or die (mysql_error());




$sql = ("SELECT * FROM sc_users WHERE username = '$uname' and password = '$pword' and yearofbirth = '$ybirth' and monthofbirth='$mbirth' and dayofbirth='$dbirth' isadmin='$admin'");


$result = mysql_query ($sql);


 if ($result) 
{
}
else 
{
$errorMessage = "Error logging on";
}


 
 if(mysql_num_rows($result)==0)
{
    echo "ERROR - No mactching rows from the database!<br/>";
}
else
{
	$_SESSION['gatekeeper'] = $_POST["username"];
	$_SESSION['agez']       = $_POST["yearofbirth"];
	$_SESSION['admin'] 		= $_POST["isadmin"];
	$_SESSION['age'] 		= $age;




   
    // Redirect to the main menu
    header ("Location: mainpage.php");
	$errorMessage = "logged on";

}

?>

I am getting Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/yvrachev/public_html/project/login.php on line 63 ERROR - No mactching rows from the database! and it is not working :( :s

Usually that happens when MySQL returns an empty record set and you try to minipulate it. Place your mysql_num_rows() function into the if statement before it or add an or die to your mysql_query

$result = mysql_query ($sql);

if ($result)
{
  if(mysql_num_rows($result)==0)
  {
    echo "ERROR - No mactching rows from the database!<br/>";
  }else{
    $_SESSION['gatekeeper'] = $_POST["username"];
    $_SESSION['agez']       = $_POST["yearofbirth"];
    $_SESSION['admin'] 	 = $_POST["isadmin"];
    $_SESSION['age'] 	= $age;

    // Redirect to the main menu
    header ("Location: mainpage.php");
    $errorMessage = "logged on";
  }

}
else
{
  $errorMessage = "Error logging on";
}

put this in, my guess is $_SESSION isn't what you expect or even just a string

var_dump($old);
var_dump($_SESSION['certificate']);
if ($old < $_SESSION['certificate'])
{

int(7) string(16) "row[certificate]" This is what i get....

<?php
if(!isset($_SESSION))
{
session_start();
}  


$certificate = $_GET["certificate"];
$old = 2012 - $_SESSION['agez'];

var_dump($old);
 
var_dump($certificate);
   


   

	if  (!(isset($_SESSION["gatekeeper"]) && $_SESSION['gatekeeper'] !=''))
{
	echo "Not an user, leave";
	header("Location:mainpage.php");
	exit; 
}
	else
{

	

if ($old < $certificate)
{
	header("Location:mainpage.php");
	exit;
}
	else
{

echo "<center><h3>You are logged in as " . $_SESSION['gatekeeper'] . "</h3></center>";


// Read the quantity from the query string on the searchresult.php



// Echo the form, with hidden fields containing the quanti

echo "<form method='post' action='buyfilm2.php' >";
echo "The quantity of tickets you want to buy?: <input name='maxtickets' value='1' />";
echo "<input type='hidden' name='id' value='$_GET[filmID]' /> ";
echo "<input type='submit' value='Go!' />";

}
}

?>

that var isn't done correctly

string(16) "row[certificate]"

it sounds like you've put in

echo "<form action='formprocess.php?certificate=row[certificate]>";

instead of

echo "<form action='formprocess.php?certificate=$row[certificate]>";

oh and also when values are passed through post and get vars they are returned as strings

Such as $_GET might equal string(2) "18".

php will usually evaluate it fine but remember for comparisons it isn't an integer and will fail is_int($_GET).

you can convert by using intval()

$certificate = inval($_GET['certificate']);

It's always best whatever function you have to make sure the right type of values are being passed to it and to error/correct if they arn't, can save many headaches trying to trace it back later on.

if(isset($_GET['certificate']) && (ctype_digit($_GET['certificate']) || is_int($_GET['certificate']))){
	$certificate = intval($_GET['certificate']);
}else{
	$certificate = 21;//Don't know, worst case?
}

Now certificate is always an integer, if its set wrong it guesses worst case 21

if(!isset($_SESSION))
{
session_start();
}  

#var_dump($old);
#var_dump($certificate);
   
  
$certificate = $_GET["certificate"];
$old = date("Y") - $_SESSION['agez'];




   

	if  (!(isset($_SESSION["gatekeeper"]) && $_SESSION['gatekeeper'] !=''))
{
	echo "Not an user, leave";
	header("Location:mainpage.php");
	exit; 
}
	else
{

	

if ($old < $certificate)
{
	header("Location:mainpage.php");
	exit;
}
	else
{
}

Works now, I changed the form as well. Thanks. I do have another question tho. So when I enter my Login and Password, how can I create a session from the SQL query about my Date of birth, month of birth, year of birth and then use it to check if the user is old enough to see a movie
Login.php

<?php
//prevent sql injesctions
session_start();
error_reporting (E_ALL ^ E_NOTICE);
// for error handling
ini_set('session.bug_compat_42',0);
ini_set('session.bug_compat_warn',0);

$uname 	= $_POST["username"];
$pword 	= $_POST["password"];
$num_rows = 0;
$errorMessage = "";
$uname  = htmlspecialchars($uname);
$pword  = htmlspecialchars($pword);




if(!ctype_alnum($uname))
{
    echo "ERROR: Input contains characters other than letters and numbers.";
}



$conn = mysql_connect("localhost", "yvrachev", "Eer3num6") or die("cannot connect"); 
mysql_select_db("yvrachev") or die (mysql_error());





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



if($result) 
{
}
else 
{
$errorMessage = "Error logging on";
}



 
 if(mysql_num_rows($result)==0)
{
    echo "ERROR - No mactching rows from the database!<br/>";
}
else
{
	$sql_check = "SELECT * FROM sc_users WHERE (username = '$uname' and password='$pword' AND isadmin= 1)";
	$sql_result = mysql_query($sql_check) or die(mysql_error());
	
	if(mysql_num_rows($sql_result)==0)
	{	
		$_SESSION['gatekeeper'] = $_POST["username"];
		$_SESSION['agez'] = $_GET["yearofbirth"];
		header("Location: mainpage.php");
	}
	else
	{
	$_SESSION['gatekeeper'] = $_POST["username"];
	$_SESSION['admin']      = $_POST["username"];
	$_SESSION['agez'] = $_GET["yearofbirth"];
		header("Location: newfilm.php");
	}
	

   
    // Redirect to the main menu
    
	$errorMessage = "logged on";
	
}


?>

how i do logins is i keep it all in a database eg,

userid,username,hash,salt,token,access_level,active,dob
1,bim,3Fsd4sdf32dsfsd54r,4sdf34,sdfrgsgfgfsgergsdfgrtgdfgfg,10,1,1998-03-06

then on every page of the project i include a function that checks the session token and pull the users logged in data

app.php

<?
//connect db
$Q = "select `username`,`access_level`,`active`,`dob` from `users` where `token` = '{$_SESSION['token']} LIMIT 1";
$R = mysqli_query($con,$Q);
if($R !== false){
$A = mysql_fetch_assoc($R);
$A['loggedin'] = true;
}else{
//header('Location: login.php');
}
<?
require('app.php');
//$A['dob'] == users dob in mysql datetime format
//user is 14 years old, cant view anything cert 15 or above
//rest of somepage.php...
?>

The problem is probably in line 50

$result = mysql_query($sql);

. Function mysql_query returns either a resource if everything is OK or FALSE if there is an error. In your case it returned FALSE as the error message says

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given...

Probably it could not read data from the database. Check whether your query is OK. Put this on line 48 so you get the query displayed and check it in phpMyAdmin (or mysql client).

die($sql);

thank you ardav its really great and use full reply, hope that it will also solve my problem, keep it up

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.