I've made a login, that sets a cookie with a value of the imputed email address, so in the global.php file, it stores an array of the users data using:
$email = $_COOKIE["PeopleHub"];
$getuserdata = mysqli_query($con, "SELECT * FROM Earth WHERE email='$email'");
$userdata = mysqli_fetch_array($getuserdata, MYSQLI_ASSOC);
The cookie isn't being set, I know this because I made a test file:
echo $_COOKIE["PeopleHub"];
It just made a blank page.
The login code (where the cookie is set):
<?php
include "global.php";
?>
<h2>Login</h2>
<?php
echo "We currently have <b>" . $usercount . "</b> members, <b>" . $onlinecount . "</b> of which are online. ";
?>
<br>
<br>
<?php
if(isset($_POST["email"])){
$email = $_POST["email"];
$password = sha1($_POST["password"]);
$check = mysqli_query($con, "SELECT * FROM Earth WHERE `email`='$email' AND `password`='$password'");
$check = mysqli_num_rows($check);
if($check == 1){
setcookie("PeopleHub", $email, 0, '/');
echo "We logged you in!";
}
else {
echo "We couldn't log you in!";
}
}
?>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
Email <input name="email" placeholder="Email Address" required="" type="text"><br>
Password <input name="password" placeholder="Password" required="" type="password"><br>
<input type="reset" value="Start Over">
<input type="submit" value="Login">
</form>
You have to set cookies before any headers are sent out.
From the manual:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
This means you will need to look into output buffering if you wish to use this code as is.
<?php
ob_start();
echo "Hello\n";
setcookie("cookiename", "cookiedata");
ob_end_flush();
?>
Depending on the contents of global.php, this might work for you. All I did was remove any output before setcookie() is called. If global.php contains any whitespace or HTML output in it this won't work:
<?php
include "global.php";
if(isset($_POST["email"])){
$email = $_POST["email"];
$password = sha1($_POST["password"]);
$check = mysqli_query($con, "SELECT * FROM Earth WHERE `email`='$email' AND `password`='$password'");
$check = mysqli_num_rows($check);
if($check == 1){
setcookie("PeopleHub", $email, 0, '/');
echo "We logged you in!";
}
else {
echo "We couldn't log you in!";
}
}
?>
<h2>Login</h2>
<?php
echo "We currently have <b>" . $usercount . "</b> members, <b>" . $onlinecount . "</b> of which are online. ";
?>
<br>
<br>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
Email <input name="email" placeholder="Email Address" required="" type="text"><br>
Password <input name="password" placeholder="Password" required="" type="password"><br>
<input type="reset" value="Start Over">
<input type="submit" value="Login">
</form>
Just wanted to point out, I had an issue with setcookie not working. When I investigated the file further it was encoded as UTF-8 with BOM. When I re-encoded it as UTF-8 without BOM setcookie worked fine, so the BOM was being written before my first php tag was encountered. I guess enabling buffering in my php.ini file probably would fix this too.
Someone may eventually find this information helpful.
I had the same problem and it turned out that it was caused because the domain I was passing to the function had a custom port (which is not allowed).
I had another problem with cookie update using setcookie function.
So I've set cookie string made from array using php serialize function. From now on I was not able to update that cookie - setcookie function was simply not working, wheather is was setting serialized string or any other simple string.
Then I've set another cookie with new cookie key, this time data was encoded with json_encode function. This time I was able to set the cookie and update it :-)
Mine was a slightly more exotic case: turns out my ad blocker (I use 1Blocker) kills cookies with certain names. In my case it was a cookie name ending with _login. I changed the name and it started working.
Just wanted to add that setcookie was not working for me when the user utilized my website with an url like this: https://mywebsite89898989.com. But when the website url was changed to https://www.mywebsite89898989.com setcookie worked correctly.
I am about as far from an expert as one can be so perhaps someone more knowledgeable can explain this behavior.
I just note this information to hopefully save someone some time debugging...
If you are using XAMPP you may find this helpful: Today I was trying to find the reason for a cookie bug. On my local XAMPP server setcookie() was working fine, but once I uploaded the project to my webhosting it simply stopped working, the cookie was not set. XAMPP uses PHP v8.1.10 and webhosting uses PHP v8.1.16, so version differences are not the cause of the bug.
It turned out my mistake was to output some text before setcookie() was called (so HTTP headers were already sent), but I have no idea why it was working on localhost/XAMPP. It really shouldn't be like that.
Related
I honestly don't know what's wrong. Every time I try to add an account to my xml database file, it doesn't get written in the file. I don't see anything wrong with my code.
When I click my submit button this page's content is displayed
Object Moved
This document may be found here
//This is me testing my code below
hey im in the if statement
hogwartsBoss
swag
hogwartsBoss#gmail.com
Harry
Potter
BabyMetal Head Bangya!!
Iron Madien Run to the Hills
japybunnyhijapygen#yahoo.com genesis Bejarano
HTML SIGN UP FILE
<!--This is the sign up section on the Home Website page -->
<form method="post" action="sign_up.php">
First Name:<input type= "text" name="first"/><br /><br />
Last Name:<input type= "text" name="last"/><br /><br />
Email:<input type= "text" name="email"/><br /><br />
Username:<input type= "text" name="username"/><br /><br />
Password:<input type= "password" name="password"/><br /><br />
<input type= "submit" name="submit" value="Sign up"/>
</form>
PHP SIGN UP FILE
$f = $l = $e= $user = $pass = null;
if(isset($_POST['username']) && !empty($_POST['username'])) {
echo "hey im in the if statement";
include 'xmlconnect.php';
$f=vaildName($_POST['first']);
$l=vaildName($_POST['last']);
$e=vaildEmail($_POST['email']);
$user= $_POST['username'];
$pass= $_POST['password'];
$credTag = $xml->addChild('credentials');
//user account info
$userTag = $credTag->addChild('username',$user);
$passTag = $credTag->addChild('password',$pass);
$emailTag = $credTag->addChild('email',$e);
$infoTag = $credTag->addChild('info');
$firstTag = $infoTag->addChild('first',$f);
$lastTag = $infoTag->addChild('last',$l);
file_put_contents('UserAccountDB.xml',$xml->asXML());
echo $xml->asXML();
// echo "updated database";
// printf($xml);
//redirects you to the homepage
session_start();
$_SESSION['userName'] = $user;
//$url = "http://cs3360.cs.utep.edu/gbejarano/WebStore/UserAccountDB.xml";
//$url = "http://cs3360.cs.utep.edu/gbejarano/WebStore/myLibrary.php";
//$url = 'http://localhost/Music_Webstore/myLibrary.php';
header('Location: '.$url);
}
There is a great misunderstanding here:
Object Moved
This document may be found here
is not an error message. It's your web-server's standard response body of a message in the Redirect 3xx group. Those do not denote errors, just standard redirects.
Those redirects are expected because you answer with a redirect:
header('Location: '.$url);
However using
echo $xml->asXML();
before the header command does not work at all. Please consult the PHP manual on how to do a proper redirect and related to other existing Q&A material here on site as well before you draw wild assumptions in a new question and label non-errors as errors and cause other confusion.
If certain words are not clear to you, ask about the words first.
If you have problem to decipher a message the computer gives to you, ask about the message first.
Do not post live code. Instead create a new example from scratch that contains as little code and data as necessary to reproduce your issue.
Sometimes the solution is simple:
It wasn't my code it was my school server security
So I finally decided to get an online server so I can share my website that I worked really hard on to the world. But there has been some growing pains. I have never been education on internet server management, so I thought that if it worked on my WAMP server then it would work on any server. So I chose ipage thinking that it would work, and it turned out to be a UNIX server.
There has been this trend on my website where use an AJAX/Jquery event to bring forth a form from another view and whenever I submit a it, and it will go to the original form page. It will execute the query and go through alright, but you have to hit the back button and that is just bad for the user experience. But on my local WAMP server, it works out perfectly.
Let me give you sort of a visual of the code:
The form:
<div id='addCard'>
<form action='<?php echo $_SERVER['PHP_SELF']?>' method='post'>
<label> Question </label><br><input type='text' name='question' size='30'>
<?php
if (isset($_POST['submitted'])) {
$valid = true;
if (empty($_POST['question'])) {
echo "<mark> You must have a question! </mark>";
$valid = false;
}
}
?>
<br>
<label> Answer </label><br><input type='text' name='answer' size='30'>
<br>
<label> Extra Information </label><br><input type='text' name='information' size='30' height='100'rows='80' cols='90'>
<br>
<?php
if (isset($_POST['submitted'])) {
if (empty($_POST['answer'])) {
echo "<mark> You must have an answer! </mark>";
$valid = false;
}
}
if (isset($_POST['submitted'])) {
if ($valid) {
require_once '../Models/classes.php';
$new_card = new Cards($_SESSION['user_id'], $_POST['question'], $_POST['answer'],
$_POST['information']);
$new_card->card_insert($_SESSION['user_id'], $_POST['question'], $_POST['answer'],
$_POST['information']);
}
}
?>
<input type="submit" name="submitted" value="Add Card">
<input type="reset" value="Reset Fields">
</form>
</div>
jQuery function used to call forth the form:
$('#addCard').click(function() {
$('.bar').empty();
$('.bar').load('add_card.php #addCard');
});
The actual function to put the card into the database:
public function card_insert($user_id, $question, $answer, $information){
$card_insert = sprintf("INSERT INTO Cards(user_id, question, answer, information) VALUES('%d', '%s', '%s', '%s');",
mysql_real_escape_string($user_id), mysql_real_escape_string($question),
mysql_real_escape_string($answer), mysql_real_escape_string($information));
$result = mysql_query($card_insert) or die(mysql_error());
if ($result) {
header("Location: my_cards.php");
}
}
What do you think needs to be changed? Is it a header function I need to add in? I'm using an absolute link and it still goes to that view.
If you wish to try it out for yourself, then try it at: http://www.wonderpenguin.com/Study_Penguin/index.php
If you want to see the folder structure, then check out my github page:
https://github.com/Lalien/Study_Penguin
Probably you have different output buffer sizes on the machines. Anyway, header can only be set as long as no output has been send to the client.
The function card_insert tries to set a location header but there's a lot of HTML code which has been implicitly printed to the client already. Try to change the order and have HTML code always after header(...)
PHP is OS independent and scripting language so it will not be problem where you have writen code either wamp or mac or hosted on Linux
Cross check php_self function ?
See example below
I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.
I want to enable form fields in php if only username is available otherwise the fields should remain disabled.
How can I do this ?
Pls take a look at the this page.
Can anyone help please.
Code:
<form action="" method="post" name="sampleform" id="form1">
<input name="uname" type="text" id="uname" class="uname" style="text-transform:lowercase;" />
<span class="req">*</span>
<input type="submit" name="chkuserid" value="Check User ID availability" id="chkuserid" class="btn" style="width:200px;" />
<?php
$con=mysql_connect("localhost","***","****")or die("Unable to connect");
mysql_select_db("****_salaam",$con)or die("Invalid");
if(isset($_POST['chkuserid']))
{
$nmu=$_POST['uname'];
$sql = mysql_query("SELECT * FROM member_reg where unm='$nmu'");
if(mysql_num_rows($sql)>0)
{
echo "Username already existing";
ob_flush();
}
else
{
echo "Username available";
}
}
?>
you gonna use ajax request and on the success of the request (username available) you need to change the default view state of the fields.
That's simple i guess, are you looking for code
Just run a if else condition in PHP, it will work.
if ($username == '$name')
{
your active form
}
else
{
your disabled form
}
for this you need to fetch the username / id or anything unique to recognize the user.
This is done using ajax.
When the user click the checkAvailabilty we send an ajax request to the server. The server will return json with either true or false.
Depending on that we can show that the username is avialble or not.
Similarly you will enable the other fields if the response json from the server is true.
This is a good tutorial. You can read this for more information
http://www.tizag.com/ajaxTutorial/
Please dont forget to add a server side validation when the user register's in your website.
Client side validation can't be trusted.
First you hit your request using ajax and get the information about username.
By default make inputs as
disabled="true"
If username is available then you and enable the other inputs. For Ex:
document.getElementById('uniqueId').disabled = false;
I would like create a script that is somewhat like a login. Before going to a certain page, they must answer a question correctly. If they get it right, then they proceed to the page. For example "What's your mom's name?" If the mom's name is Laurie, then they must enter this into a textbox and get it right to proceed.
Update
I used the script that oliver moran gave me to accomplish this. I added more questions so there is currently one question per page. After the final question has been answered, I have the page targeted to a place where they login, because I couldn't figure out how to do this simply based on the answer of the question. And I am fine with having the user login as a separate function. I have gotten the form to get them to login, and not let users that aren't logged in get to these pages. And the script works as long as they have kept the browser window open.
I have used the link that Oliver Moran gave on using sessions, and you can see in my code that I use sessions. But this does not solve the problem of keeping them logged in.
I would now like to know how to set a cookie once the user has logged in so they can leave the browser window and come back and still be logged in. I have searched this site for an answer, and couldn't find one that made sense. Here is my login code
<?php
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
if ($username&&$password) {
$connect = mysql_connect("127.0.0.1","root","") or die('Couldn\'t Connect to Database');
mysql_select_db ("login") or die('Couldn\'t find database');
$query = mysql_query("SELECT * FROM members WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0) {
while($rows = mysql_fetch_assoc($query)){
$dbusername = $rows['username'];
$dbpassword = $rows['password'];
}
if ($username==$dbusername&&$password==$dbpassword) {
echo "Login Successful. <a href='home.php'>Click here for the members area</a>";
$_SESSION['username'] = $dbusername;
}
else{
echo "Incorrect Password";
}
}
else{
die("Incorrect Username and Password");
}
}
else{
die("Please enter something in the boxes");
}
?>
Typically, a server-side language is used for this kind of thing. This is because, if you do password checking in JavaScript, anybody can see the correct password (since all the code is available by looking at the page's source code).
In order to do it securely, you'll need to submit the answer to a server and use a server-side language to check the answer. The server-side script then decides what response to give back to the user.
PHP is a very popular language for server side scripting. Here's the basics:
First we need a log in page (login.html) that has a HTML form in it, like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Login</title>
</head>
<body>
<form action="script.php" method="post">
<label>Enter your mom's name: <input type="text" name="mom" /></label>
<input type="submit" value="Submit" />
</form>
</body>
</html>
The important part here is the form. When the form is submitted, the data is sent to a PHP script called script.php.
That script looks like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Check login</title>
</head>
<body>
<?php
$mom = $_REQUEST['mom'];
$correct_answer = "Barbie";
if (!isset($mom) || $mom != $correct_answer) {
// nothing was submited or the name was incorrect
echo '<p>That\'s the wrong answer. Try again.</p>';
} else {
echo '<p>Welcome! That\'s the right answer.</p>';
}
?>
</body>
</html>
This is a fairly simple script. It checks what was submitted for 'mom'. If nothing was submitted or it was the wrong answer then a 'try again' message is shown. Otherwise, a 'welcome' message is shown.
The PHP logic (and so the correct answer) will not be visible in a web browser. Only the 'try again' or 'welcome' message will be sent down from the server.
This is the basics of working with HTML forms on the server side. I suggest you read up on using PHP. It's an easy and fun language (if inelegant, in my opinion). You can learn the basics here:
http://www.w3schools.com/php/default.asp
To test your code, you will need a web server. You can download and install a fully-fledged web server with PHP and MySQL (a database) from here:
http://www.wampserver.com/en/
With that, you can develop at test server-side code on your own machine. To test the above example, copy the code above into two files, called login.html and script.php, and put them into the www directory of WAMP.
Good luck!
This is what I managed to come up with. At the top of the page, insert this code before the <!DOCTYPE html>
<?php
//Check for existance of cookie from right answer
if(isset($_COOKIE['parents'])){
header("Location:q1.html");//Move on to next question
}
//Checks answer
if(array_key_exists("dad", $_POST) && array_key_exists('mom', $_POST)){
$dad = $_POST["dad"];
$mom = $_POST["mom"];
$dcorrect = array("Dad", "dad");
$mcorrect = array("Mom", "mom");
if(in_array($dad, $dcorrect) && in_array($mom, $mcorrect)){
setcookie('parents', '1' ,time()+60*60*24);
header("Location: index.html");
}else{
$wrong="<div class='error'>Wrong answer</div>";
}
}
?>
With this HTML
<form action="index.html" method="post">
<label>Enter your father's name:</label>
<input required autocomplete="off" type="text" name="dad" placeholder="Bill">
<label>Enter your mother's name:</label>
<input required autocomplete="off" type="text" name="mom" placeholder="Billette">
<input type="submit" value="Press me when you think you are right" />
<?php echo $wrong; ?>
</form>