I want to redirect to a confirmation page after the person has registered, once they have entered the details they need it is sent to the database using the PHP script below which all works. Although when I try to add a redirect using header, it does not run the PHP script. Any ideas to what I am doing wrong?
PHP
if (isset($_POST['firstname'], $_POST['surname'], $_POST['email'], $_POST['username'], $_POST['password'], $_POST['interest'])){
$firstname = ($_POST['firstname']);
$surname = ($_POST['surname']);
$username = ($_POST['username']);
$password1 = ($_POST['password']);
$email = ($_POST['email']);
$interest = ($_POST['interest']);
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
}
You should use MySQLi or PDO with prepared statements as mysql_ functions have been deprecated. You should at least look into using something like mysql_real_escape_string as you may be open to sql injection attacks.
Otherwise, like others have said use:
header("Location: new_page.php");
exit();
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
header('Location: page.php');
Include at the beginning of the script:
<?php
ob_start();
?>
You can add header('Location:yourpage.php');
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
header('Location:yourpage.php');
exit();
You can add the #ob_start(); on top of the page.
This is an educated guess on what your problem might be:
You say the page is redirecting, but the php is not parsed. So... if the page just displays your php, it means is outside php reading directory... check that pls (see if it starts with localhost/your ip/domain, etc).
Related
When I run the following PHP code in my browser, I get an empty page in return. Why is this so?
<?php
require_once "conf.php";
function nuser()
{
$fname = $_POST['name'];
$uname = $_POST['user'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$query = "INSERT INTO websign(name,uname,email,pass)VALUES('$fname','$user','$email','$pass')";
$data = mysql_query($query)or die(mysql_error());
if ($data)
{
echo "your registration is completed";
}
}
function signup()
{
.......
.......
}
?>
Your code doesn't do anything.
You have defined two functions, but you never call either of them.
You need to add nuser() to the end of the script.
This assumes that the script executes at all. You said "when i run it on browser", but PHP doesn't run in browsers, it runs on servers. See this question on the subject.
Your program might also fail because you are using an obsolete database API that has been removed from PHP. You should select a modern replacement. You are vulnerable to SQL injection attacks that a modern API would make it easier to defend yourself from.
For some reason addslashes is NOT adding slashes when inserting data into database. I thought I was using this right, but clearly not... When I submit data that has single or double quotes, it is just sending the exact string right in. Any ideas on how to make this work?
The code
<?php
//include db connect
include ("db_con.php");
//start session
session_start();
//set variable names
$username = $_SESSION['username'];
$entry = addslashes($_POST['entry']);
$uri = $_SERVER['HTTP_REFERER'];
//send chat
$query = mysqli_query($con, "INSERT INTO chat (username, entry) VALUES
('".$username."', '".$entry."')");
if ($query) {
header('Location: '. $uri);
} else {
echo 'Chat entry failed for an unknown reason - Please go back and try again';
}
?>
addslashes() is for escaping the string. If you got code:
$lastname = "O'Bama";
$query = "SELECT name FROM users WHERE lastname='$lastname'";
The query will produce an error because Bama will be treated as SQL statement. To prevent this you can use addslashes() so
echo addslashes($lastname); // returns O\'Bama
Now you can execute your query without any errors because your database will see value as "O'Bama".
Using addslashes() when dealing with databases is very bad practice. Since you're using PHP's mysqli extension, you should escape your data with mysqli_real_escape_string(). The PHP manual page for addslashes() explains why.
I understand that this may be a duplicate post, although I am unsure how to use the posts answers in my context. I am trying to post the registered fields to the database, but if they are taken (only username and email), return to the form where the user can then edit the wrong information. Could anyone help?
I am aware that I am using deprecated tags, this is for a college project
if (isset($_POST['firstname'], $_POST['surname'], $_POST['email'], $_POST['username'], $_POST['password'], $_POST['interest'])){
$firstname = ($_POST['firstname']);
$surname = ($_POST['surname']);
$username = ($_POST['username']);
$password1 = ($_POST['password']);
$email = ($_POST['email']);
$interest = ($_POST['interest']);
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
}
if (isset($_POST['submit']))
{
?>
<script>window.location='redirect.html';</script>
<?php
}
?>
I did have something like this, but this does not work
$query2="SELECT * FROM user WHERE username='$username'";
$result2=mysql_query($query2);
$num=mysql_numrows($result2);
if ($num!=0)
{
echo "That username has already been taken, please try again<br>
<a href='register.php'>Register</a>";
exit();
}
The function is mysql_num_rows instead of mysql_numrows:
$num = mysql_num_rows($result2);
mysql_num_rows
As the page also tells you, from PHP 5.5.0, this method can not be used anymore. So suggest start using mysqli_* or PDO
I'm kinda new to the OOP(? If this IS OOP, I don't know) language, and I'm trying to make a simple login-proccess, with MySQLi. The problem are, that the code doesn't work. I can't login (and It's not showing me any errors) and I can't register an new account (same problem) - It's like the code are dead or something.
I'm not sure I've done it right, but this is my best, so far. 'cause I'm new to OOP(?).
Index.php:
<?php
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$userControl = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."'";
$userControlResult = $mysqli->query($userControl);
if($mysqli->num_rows($userControlResult) > 1) {
$userRow = $mysqli->fetch_assoc($userControlResult);
$dbid = $userRow['id'];
$dbuser = $userRow['username'];
$_SESSION['id'] = $dbid;
$_SESSION['username'] = $dbuser;
header("location: me.php");
die();
} else {
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
}
?>
I suppose that if I can solve the first error, I can solve the second too.
Thanks!
Many things I would recommend changing about your code:
Don't use mysql_real_escape_string() if you're using mysqli. You can't mix these APIs.
No need to escape a string returned by md5(), because it's guaranteed to contain only hexadecimal digits.
Don't use mysqli_real_escape_string() anyway -- use parameters instead.
Always check if prepare() or execute() return false; if they do, then report the errors and exit.
You can get a mysqli result from a prepared statement using mysqli_stmt_store_result().
Don't SELECT * if you don't need all the columns. In this case, you already have $username so all you really need to fetch is the id column.
No need to check the number of rows returned, just start a loop fetching the rows (if any). Since you exit inside the loop, your "else" error clause will be output only if the loop fetches zero rows.
Consider using a stronger password hashing function than MD5. Also, add a salt to the password before hashing. Read You're Probably Storing Passwords Incorrectly.
Example:
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$userControl = "SELECT id FROM users WHERE username=? AND password=?";
if (($userControlStmt = $mysqli->prepare($userControl)) === false) {
trigger_error($mysqli->error, E_USER_ERROR);
die();
}
$userControlStmt->bind_param("ss", $username, $password);
if ($userControlStmt->execute() === false) {
trigger_error($userControlStmt->error, E_USER_ERROR);
die();
}
$userControlResult = $userControlStmt->store_result();
while($userRow = $userControlResult->fetch_assoc()) {
$_SESSION['userid'] = $userRow["id"];
$_SESSION['username'] = $username;
header("location: me.php");
die();
}
// this line will be reached only if the while loops over zero rows
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
?>
A good command to enter at the top of the script (under the
ini_set('display_errors', 1);
This will display any errors on your script without needing to update the php.ini (in many cases). If you try this, and need more help, please post the error message here and I'll be able to help more.
Also, if you are using $_SESSION, you should have
session_start();
at the top of the script under the
Make sure your php is set to show errors in the php.ini file. You'll need to do some research on this on your own, but it's fairly easy to do. That way, you'll be able to see what the error is and go from there.
I'm adding a contact to my database with a form on the page add.php, the INSERT code for this form is on another page we'll call php.php page. In php.php I have a header function which I would like to have redirect the user to another page edit.php?ID=100, ID=100 being the contact that was just entered. How would I do this, do I need to do a fetch from the db before the header function and INSERT query?
<?php
if (isset($_POST['$fname'])) {
header("location: http://www.mydomain.com/contacts/edit/?ID=<? echo $row['ID]; ?>");
$connect = mysql_connect (...)
mysql_select_db ("mydb);
$ID = $_POST['ID'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sql = ("INSERT INTO contacts (fname, lname) VALUES ('$_POST[fname]', '$_POST[lname]')");
mysql_query($sql,$con) or die ("Error: ".mysql_error());
exit;
}
?>
I believe mysql_insert_id is the function you're looking for. It'll return the AUTO_INCREMENT ID of the field that was just inserted. You can then plug that into your header redirect. Just make sure to do the header redirect AFTER you insert the contact. It'll work just fine.
Code that should work:
<?php
if (isset($_POST['$fname'])) {
$connect = mysql_connect (...)
mysql_select_db ("mydb");
$ID = $_POST['ID'];
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$sql = "INSERT INTO contacts (fname, lname) VALUES ('$fname', '$lname')";
mysql_query($sql,$connection) or die ("Error: ".mysql_error());
header("location: http://www.mydomain.com/contacts/edit/?ID=".mysql_insert_id($connection));
exit;
}
?>
The code you posted was also susceptible to MySQL injections, so I mysql_real_escape_string'd your input to prevent that from happening. Always sanitize input before putting it into your query. I encourage you to look at the MySQLi functions that PHP has to offer.
You need to send the headers after the current script has done all that you want it to do. Sending headers doesn't necessarily immediately cancel the execution of that script; it can still persist for a bit, but you should do after you do your SQL calls.
The header doesn't terminate the run of the script.
If you use location redirect is a good practice to exit from the script, what you did correct.
Be aware one thing, do not put any output to the stdout before the header.
You can't embed php code in the header function (the <? echo $row['ID]; ?>). To achieve what you are trying to do, you should have the INSERT code before the header function. Then you should retrieve the ID of the contact you just entered and then call the header function, like so (assuming $id is the retrieved ID):
header("location: http://www.mydomain.com/contacts/edit/?ID=".$id);
To retrieve the ID of the last inserted row, you can use the mysql_insert_id function (reference), though it is recommended you use the mysqli version.