headers not working PHP - php

Page 1 abc.html.. on submit it will jump to this PHP page .
This is page PHP1.php here i am trying to validate user input if name and id in in data he will be forwarded to fill out second part of registration if not it will just give error.
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = mysql_connect("localhost", "user", "password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("mydbName");
if(isset($_POST['team_name'],$_POST['id'])){
$team_name = mysql_real_escape_string($_POST['team_name']);
$id = mysql_real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result= mysql_query("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$team_result = mysql_fetch_row($result);
if ($team_result[0] == '0') { //if does not exist print failed.
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}} } ?>
RegisterPART2.php is where i am checking my session exist or not (the one i started in last file). if not i want to redirect back to form one and fill that first then come to registration part 2
`<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page1.html'); //take back to stage 1 coz user did not fill first part.
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>

If you're using the new MySQL version (MySQLi), so the first page will become:
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = new mysqli("localhost", "user", "password", "mydbName");
if (!$con) {
die('Could not connect: ' . $con->error());
};
if (isset($_POST['team_name'],$_POST['id'])) {
$team_name = $con->real_escape_string($_POST['team_name']);
$id = $con->real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result = $con->prepare("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$result->execute();
$result->bind_result($one,$two,$three,$etc);
$result->fetch();
if (empty($one) and empty($two) and empty($three) and empty(etc)) { // may be and/or (pick one)
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}
}
}
?>

You may use the following alternative to header.
prinf('<script>window.location = "URL HERE"</script>');
It should do the same thing as header does.

Related

How to detect whether users have accepted terms?

Basically I am writing a PHP and MYSQL script that will check whether a user has accepted the terms and conditions or not. In the databse every current user that has signed up is set to "unaccepted". When they log in the first page that they are directed to should have a scirpt on it that detects whether or not the status of the tos column in the users table is set to "accepted" or "unaccepted". If it is accepted they can continue, and if it is not they they will be forced to go to a page and accept them before they can continue to use the rest of my site. This is the code so far but it doesn't seem to be working. Any suggestions help.
<?php
$username=$_SESSION['username'];
$connect = mysql_connect('**', '**', '**', '**');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('**'))
{
die('Could not select database: ' . mysql_error());
}
$toschecker = mysql_query("SELECT `tos` FROM `users` WHERE `username` = '$username'");
if (!$toschecker)
{
die('Could not query:' . mysql_error());
}
mysql_close($connect);
$unaccepted='unaccepted';
if ($toschecker === $unaccepted)
{
header('Location: accepttos.php');
}
?>
For some reason this isn't directing them to the accepttos.php page. Thanks in advance.
Change MySQL to MySQLi. Explanations are in the comments.
<?php
$username = $_SESSION['username'];
$connect = mysqli_connect('Host', 'Username', 'Password', 'Database');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$toschecker = mysqli_query($connect,"SELECT `tos` FROM `users` WHERE `username` = '$username'"); /* SELECT TOS COLUMN */
while ($row = mysqli_fetch_array($toschecker))
{
$tos = $row['tos']; /* STORE TO A VARIABLE THE FETCHED TOS */
}
$unaccepted = 'unaccepted';
if ($tos == $unaccepted) /* COMPARE THE TOS VARIABLE IF UNACCEPTED */
{
header('Location: accepttos.php');
}
else {
header('Location: acceptedTOS.php'); /* IF TOS IS ACCEPTED. CHANGE THE LOCATION */
}
mysqli_close($connect);
?>
$toschecker is a resource , try the following under the mysql_query line to see the result of your query, which you can use to redirect accepttos.php etc..
if( $row = mysql_fetch_assoc($toschecker)) {
var_export($row['tos']);
}
You need to access the information in the fields of your database. Here is an example.
$toschecker = mysql_query($sql);
$row = mysql_fetch_array($toschecker);
$tos = $row['tos'];
if($tos == 'accepted'){
// go to regular page
}else {
// go to accept terms page
}

PHP show records from mysql

Im blocked at following part of code...
i have config.php page, with following code inside:
<?php
// Start the session (pretty important!)
session_start();
// Establish a link to the database
$dbLink = mysql_connect('localhost', 'USER', 'PASS');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());
$dbSelected = mysql_select_db('DATABASE', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());
$isUserLoggedIn = false;
$query = 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';
$userResult = mysql_query($query);
if(mysql_num_rows($userResult) == 1){
$_SESSION['user'] = mysql_fetch_assoc($userResult);
$isUserLoggedIn = true;
}else{
if(basename($_SERVER['PHP_SELF']) != 'index.php'){
header('Location: index.php');
exit;
}
}
?>
Now i have another page, with following code inside:
<?php include_once('config.php'); ?>
<?php foreach($_SESSION['user'] as $key => $value){ ?>
<li><?php echo $key; ?> <strong><?php echo $value; ?></strong></li>
<?php } ?>
That code show me all informations stored in database, one by one..
I want to show informations, individualy in my page, something like:
<?php echo $email; ?>
etcetera..
Can someone explain me how to do that?
Thank you
You should output it like
<?php echo $_SESSION['user']['email'] ?>
assuming that 'email' is the column name in the users table.
Just address the relevant field in the associative array:
<?php echo $value['email';?>
Use this in the config file:
$_SESSION['user']['email'] = mysql_fetch_assoc($userResult);
instead of this
$_SESSION['user'] = mysql_fetch_assoc($userResult);
in your code. You can pass as many columns you want to pass from your table.
And in another page use
foreach($_SESSION['user']['email'] as $key => $value)
instead of
foreach($_SESSION['user'] as $key => $value)
in your code.
Remember number of columns you pass in config file, all those columns should be called in this page.

Take data from one php page and echo it onto another page

I need to simply take data from one page, upon a condition, and echo it on another page. Here is my code and my other attempts which do not work.
<?php
session_start;
/* connect to database */
$db = mysql_connect("localhost", "root", "root");
if (!$db)
die('could not connect');
mysql_select_db('androidp2p')
or die("could not select database");
/* variables */
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
/* conditional code */
if ($_POST['to'])
{
/* user wants to send a message */
$query = "INSERT INTO messages (fromuser, touser, message) VALUES ('$from', '$to', '$message')";
mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
echo "ok. Messages have been saved.";
}
else
{
/* user wants to retrieve his messages*/
$query = "SELECT * FROM messages WHERE touser='$from'";
/* echo1 */
echo $query;
$result = mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
$mailbox = array();
while($row = mysql_fetch_assoc($result)){
$mailbox[] = $row;
}
/* echo2 */
echo "{ \"mailbox\":".json_encode($mailbox)." }";
$name = "{ \"mailbox\":".json_encode($mailbox)." }";
/* echo3 */
echo $name;
$_SESSION['myValue']=$name;
}
?>
And on the next php page, called test.php:
<?php
session_start;
echo $_SESSION['myValue'];
?>
My logcat shows that I am getting data in all three echos, but still nothing is being displayed on test.php(i.e. page2).
I also tried:
Attempt 1:
In page 1:
session_start();
$_SESSION['myValue']=$name;
And in page2 used:
session_start();
echo $_SESSION['myValue'];
Attempt 2:
In page 1:
session_start();
$_SESSION['name'] = $name ;
And in page2 used:
session_start();
$name = $_SESSION['name'];
Attempt 3:
In page 1:
header("Location: test.php?name=".$name);
And in page2 used:
$name = $_GET['name'] ;
But nothing is being displayed on test.php(In this last attempt3 I got a bunch of warnings and maybe errors). What am I doing wrong?
This is my logCat:
04-13 14:46:22.564: I/RESPONSE(4591): SELECT * FROM messages WHERE touser='r'
04-13 14:46:22.564: I/RESPONSE(4591): { "mailbox":[{"id":"117","fromuser":"qw","touser":"r","message":"zx","timestamp":"2013-04-13 01:30:59"}] }
Now above I want you to see that touser is r. This entry into the db is what I want, i.e. all entries where the field "touser" contains the value "r".
Now, this is my test.php page:
{ "mailbox":[{"id":"123","fromuser":"r","touser":"","message":"","timestamp":"2013-04-13 13:41:23"},{"id":"122","fromuser":"r","touser":"","message":"","timestamp":"2013-04-13 13:30:53"}] }
As you would see, it returned all entries where the fromuser was r. Why do the two contradict each other??
Not entirely sure what you are asking, but perhaps this will help.
In the beginning of your /* conditional code */
Use an isset condition....
<?php
session_start();
/* connect to database */
$db = mysql_connect("localhost", "root", "root");
if (!$db)
die('could not connect');
mysql_select_db('androidp2p')
or die("could not select database");
/* variables */
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
/* conditional code */
if (isset ($_POST['to']))
{
/* user wants to send a message */
$query = "INSERT INTO messages (fromuser, touser, message) VALUES ('$from', '$to', '$message')";
mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
echo "ok. Messages have been saved.";
}
else
{
/* user wants to retrieve his messages*/
$query = "SELECT * FROM messages WHERE touser='$from'";
/* echo1 */
echo $query;
$result = mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
$mailbox = array();
while($row = mysql_fetch_assoc($result)){
$mailbox[] = $row;
}
/* echo2 */
echo "{ \"mailbox\":".json_encode($mailbox)." }";
$name = "{ \"mailbox\":".json_encode($mailbox)." }";
/* echo3 */
//echo $name; no need to echo
$_SESSION['myValue']=$name;
}
?>

If else statement that redirects to another page

I'm terrible with PHP/SQL, so any help would be appreciated.
Basically I have a form that posts the values 'firstname' & 'surname' to another page. What I want that page to do, is check to see if the user's name is already on the table 'Members'. If it is I want it to continue loading this page, but if they aren't on the database, I want the viewer to be re-directed to an existing sign up page.
Here is the code I've been working on, I'm not sure if I'm heading in the right direction or not.
<?php
$con = mysql_connect("localhost","site","xxxxxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("site", $con);
$query = "SELECT * FROM Members WHERE firstname='$_POST[firstname]' and surname='$_POST[surname]'";
$result = mysql_query($query);
if ($result==$something)
{
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
?>
This will do the trick:
<?php
$con = mysql_connect( "localhost", "site", "xxxxxxxx" );
if ( !$con ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("site", $con);
1st, remove the sql injection part at least like this:
$firstname = strip_tags( $_POST[ 'firstname' ] );
$surname = strip_tags( $_POST[ 'surname' ] );
2nd, I didn't change it, but you need to remove the * and enter only specific values you want to load. Even if those are all the values, still write them manually.
$query = "SELECT * FROM Members WHERE firstname='" . $firstname . "' and surname=' " . $surname. "'";
$result = mysql_query( $query );
3rd, you can check for row count, if you got some value, there is an entry with those variables
if ( mysql_num_rows($result) >= 1 ) {
// the page you want
} else {
// redirect user to another page
header( "Location: signup.php" ); die;
}
?>
Edit:
Think adding some unique requests to your query. What will happen if two users have identical names and surnames or if a new one wants to join, but the name and lastname is already in the db ...
if (mysql_num_rows($result) == 1)
{
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
Also, you're query is prone to SQL injection big time
$rows = mysql_num_rows($results);
if ($rows == 1)
{
echo "login successful"; //user continues loading page
}
else
{
header ('location: signup.php'); //user is redirected to sign up page
}
You can simply put a header( "Location: host/site.php" ) function call in your else branch followed by a die()
if(mysql_num_rows($result) > 0){
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
use this

Refresh PHP page once only when called

I have a php which would check for certain value if it exists in a mysql database. If the value does not exists, it would simply add the value and refresh the page once to load the page again and now it has a value in the database, would go ahead to add other values. How do I refresh page just once when it is called ?
<?php
$sname = "W3 schools C# tutorials";//$_POST["sitename"];
$stype = "C#";//$_POST["sitetype"];
$saddy = "www.w3schools.com";//$_POST["siteaddress"];
$scomm = "W3 schools C# tutorials";//$_POST["sitecomment"];
$conn = mysql_connect("localhost","root","password");
if(!$conn){
die("Could not connect: ".mysql_error());
} else {
mysql_select_db("bookmarks",$conn);
$rs = mysql_query("select TypeId from bookmarktypes where TypeName = '$stype'");
$row = mysql_fetch_array($rs);
if($row > 0 ){
//Data found, continue to add...
} else {
//No data... insert a valid one
$rs = mysql_query("insert into bookmarktypes (TypeName) values ('$stype')");
if (!$rs){
die('Error: ' . mysql_error());
} else {
//echo "inserted new type data...";
}
//echo "</html>";
}
}
mysql_close($conn);
//Refresh page once
?>
There's the comment to refresh page below after mysql close command.
Refresh it right after insert with
header('Location: url here');
exit;
Btw, read a little about sql injections
Also - mysql_close() is pointless there.
if(check=1)
{
echo "\"<meta http-equiv=\"refresh\" content=\"2;url=http://yourwebsite.com/\">\"\n";
}
if you need to print the data that you just have entered try this
header('Location: YourShowDataPage.php?id='.$_POST['id_dataEntered'])
mi apologizes if is wrong , im a begginer

Categories