Header, logic and database - php

I am having an issue with my header location. I am new to php and I am unable to redirect to my index page after this separate php file is run. In addition my function is unable to tell whether the contents of a text box is blank or equal to the default value of "<>".
Thank you
<?php
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
{
// the form was submitted
//remove hacker HTML
$email2=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email2'";
$result=mysql_query($sql2);
//Direct back to homepage
echo "heloooo";
header('location:/index.php');
}
else
{
header('location:/index.php');
}
}
else
{
header('Location:http://www.google.com');
`enter code here`}
?>
EDIT
After making the changes suggested my error log is as follows
Notice: Use of undefined constant db_selected - assumed 'db_selected' in /home/clubbtpk/public_html/connectionFile.php on line 15
Warning: Cannot modify header information - headers already sent by (output started at /home/clubbtpk/public_html/connectionFile.php:15) in /home/clubbtpk/public_html/addEmail.php on line 28
The code in the connection file is:
<?php
$host="localhost";
$username="username";
$password ="password";
// Create connection to mysql server
$con=mysql_connect("$host","$username","$password");
// Check connection
if (!$con)
{
die ("Failed to connect to MySQL: " . mysql_error());
}
// Select database
$db_selected = mysql_select_db("DB", $con);
if(!db_selected)
{
die ("Cannot connect : " . mysql_error());
}
?>
EDIT 2
Resolved first error by changing
if(!db_selected)
to
if(!$db_selected)
RESOLVED
Added the following line of code to my index.php file:
<?php
if(isset($_REQUEST["emailAdd"])){
include("addEmail.php");
}
?>
Then changed the action of the form to "" so that it reloads the current page:
<form name="emailAddr" method="post" action="">

You must not output anything before your redirect.
So this is not allowed:
echo "heloooo";
header('location:/index.php');
EDIT: You should definitely enable error_reporting on your script. I found another error in your query:
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
should be
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
Furthermore you should not use the mysql_* functions anymore but upgrade to mysqli_* functions. And always check the inputted data before inserting them into sql-queries.
EDIT2: Add this at the beginning of your script:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
EDIT3:
You have to change this line too:
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
Should be:
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>")
If you would turn error_reporting on you would see it yourself.

Related

php database connection/selection

I have a login.html in which the form is defined as follows:
<form method="post" action= "do_authorize.php" name="lform">
<span class="style1">First Initial Plus Last Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
My do_authorize is as follows:
<?php
session_start();
require('../databaseConnectionFileFolder/dbconnection.php');
$user = $_POST["user"];
var_dump($user);
$_SESSION['username']=$user;
var_dump($user);
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
var_dump($sql);
$result=#mysql_query($sql,$connection) or die("couldn't execute query");
$num=mysql_numrows($result);
if ($num != 0) {
/*$cookie_name="$user";
$cookie_value="ok";
$cookie_expire=time()+86400;
$cookie_domain=".columbia.edu";
setcookie($cookie_name, $cookie_value, $cookie_expire, "/", $cookie_domain, 0);
*/
print "<script>";
print "self.location='somethingelse.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
My dbconnection.php file is as follows:
<?php
$db_server = "localhost";
$db_name = "DailyExerciseDB";
$db_user = "abc5"; //the database username
//$db_password = "123"; // the database user pasword
$connection=#mysql_connect($db_server,$db_user) or die("Could Not Connect to the Database : ". mysql_error());
var_dump($connection);
$db=#mysql_select_db($db_name, $connection) or die("Could Not Select the Database". mysqli_connect_error());
//var_dump($db);
?>
My Questions:
1) I keep on getting Could Not Select the Database, why does the warning/error message corresponding to . mysqli_connect_error() doesn't get printed on the browser?
2) I have manually entered the user with username abc5 in the database and still it's not able to connect.Does anyone know why?
3) Even if I don't enter anything in the login.html and press login button, the following files gets executed, how can I take user entered into account while verifying with database? I believe since its hardcoded right now abc5, all files are getting executed.
4) var_dump($connection); prints resource(4, mysql link)
mysql_connect() has a third parameter which I'm not seeing you use: the password. Consider the following line:
mysql_connect($db_server, $db_username, $db_password);
Also, you should probably be using mysqli extension instead of the mysql extension (mysql is deprecated in PHP 5.5.0).
I also see you're mixing the mysql and mysqli functions in your code. This is the reason why mysqli_connect_error() shows nothing.

Trying to display some data from mysql DB = blank page

<?php
//error_reporting(E_ALL); ini_set('display_errors', '1');
$connection = mysql_connect("localhost", "root", "toor");
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('test');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
session_start();
if(!isset($_SESSION['username'])){
header("Location: main.php");
}
echo "<a href='logout.php'>Logout</a>";
/*if (isset($_GET['id']){
$id = $_GET['id'];
$query = "SELECT title FROM news WHERE id=$id";
$title = mysql_query($query) or die(mysql_error());
$query = "SELECT body FROM news WHERE id=$id";
$body = mysql_query($query) or die(mysql_error());
echo "$title\n\n\n";
echo "$body\n\n";
}*/
?>
<html>
<body>
<p>
Login OK
</body>
</html>
I need to display the content of the fields title and body, however I'm getting a blank page (not even the link to logout.php is displayed). There is no error reported by error_reporting(E_ALL); ini_set('display_errors', '1');.
If I comment the if block, both the link to logout.php and the message "Login OK" are displayed.
What might be failing?
In the login.php I call news.php with:
if (isset($_SESSION['username'])){
header("Location: news.php?id=1");
}
edit
I'm noticing the call to news.php?id=1 returns an error 500.
You are using it in the wrong way
$query = "SELECT title, body FROM news WHERE id=$id";
$results = mysql_query($query);
while ($news = mysql_fetch_assoc($results)) {
echo $news["title"];
echo $news["body"];
}
the instruction mysql_query will give you a result set.
Then from results sets you have to fetch the single rows
with mysql_fetch_assoc ( or fetch_row or fetch_array, see the manual for the differencies )
Then with single result pulled you display data.
In your code i cannot see any db connection logic, there is no connection parameter passed to mysql_query function.
Error 500 means php is doing some bad error and fails to execute, anyway i would go to check the logs, the error is clearly written there and will save you headaches. /var/log/httpd/error_log generally on linux.

Code not working while trying to pull user login data from form in php

I created a registration form that works fine in php for a project I am undertaking. I attempt to use another form, a login form in which to pull the username and password data from the user to verify it against the database. However I am getting parsing errors and other errors. I haven't started validation yet as I haven't got the basics in this ready.
I don't think I'm going about this the right way or if it's just a silly mistake.
<EDIT Remove Important Info>
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
if (isset($_SESSION['logged'])){ //already logged in
//$url= 'X'; // any page
exit(); //ends script if user already logged in
} else { //not logged in or submitted
}
$user_name = mysqli_real_escape_string($con,$_POST['username']);
$pass = mysqli_real_escape_string($con,$_POST['password']);
$notify="";
if(isset($_POST['notify_box'])){ $notify = $_POST['notify_box'];
$query=mysqli_query($con,"SELECT * FROM `websiteusers` WHERE username ='$user_name' AND password ='$pass'");
$count = $mysqli_num_rows($query); //checks db
$row = mysqli_fetch_array($query);
if($count==0){ //db empty
echo "Sorry, password and username not in db. Click here to try again.";
}
else{ // pw and un match, user login success
$_SESSION['logged']=1; //start session
$_Session['username']=$user_name; //session data
}
// } // opening brace for this was not found
mysqli_close($con);
exit();
} // opening brace for this was not found
?>
And here is a jsFiddle of my HTML form
Edit
I found this in your form
<input name="user_name" type="varchar" >
which should be
<input name="user_name" type="text">
Also, use this
$pass = mysqli_real_escape_string($con,$_POST['pass']);
instead of
$pass = mysqli_real_escape_string($con,$_POST['password']);
yet I'm unsure about the password line, since you were using md5 and now just plain text.
You may have to set it back to:
$pass=md5($_POST['pass']);
There are a few issues with your code.
You have a missing quote at the end of '$user_name
WHERE username ='$user_name
Which needs to be changed to:
WHERE username ='$user_name'
as well as a missing semi-colon at the end of your query. $query=mysqli_query("SELECT....
And this (for one thing) $username=form($_POST['user_name']); is invalid, since form would be considered a function.
Use $username=$_POST['user_name']; or better yet:
$username=mysqli_real_escape_string($con,$_POST['user_name']);
A missing semi-colon at the end of $password=md5($_POST['pass'])
A missing $con at the beginning of the query.
Which is included in the complete rewrite below.
Line rewrite:
$query=mysqli_query($con, "SELECT * FROM `websiteusers` WHERE username ='$user_name' AND password ='$pass'" );
Plus, I noticed you're storing passwords using md5. It's no longer recommended to use this. Do look into using PHP's password function
Complete rewrite:
N.B.: The $url variable has not been defined anywhere else, so I'm unsure of its functionality. Plus there were two unused ending braces } at the end of your code, so I commented those out, along with the exit();
You may also be closing your DB connection prematurely with the placement of mysqli_close($con); should you be faced with another error message. I left it in place, but commented out and then moved at the end of the script.
Please give this a try, hoping things will fall into place as they should.
<?php
// Create connection
$con=mysqli_connect("X","X","X","X");
session_start(); //starts users session
// Check connection
if (!$con) {
die('Connect Error: ' . mysqli_connect_errno());
}
//echo "1 record added";
if (isset($_SESSION['logged'])){ //already logged in
$url= 'http://danu6.it.nuigalway.ie/sm4business/browse.html'; // any page
exit(); //ends script if user already logged in
} else { //not logged in or submitted
$username=mysqli_real_escape_string($con,$_POST['user_name']);
$pass=md5($_POST['pass']);
} // mysqli_close($con); // may be being closed prematurely.
$query=mysqli_query($con,"SELECT * FROM `websiteusers` WHERE username ='$user_name' AND password ='$pass'");
$r = $mysqli_num_rows($query); //checks db
$row = mysqli_fetch_array($query);
if($r==0){ //db empty
echo "Sorry, password and username not in db. Click here to try again.";
}
else{ // pw and un match, user login success
$_SESSION['logged']=1; //start session
$_Session['username']=$user_name; //session data
}
// } // opening brace for this was not found
// exit();
// } // opening brace for this was not found
mysqli_close($con); // moved here
?>
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
make it this as
//Check connection
if (mysqli_connect_errno()) { echo "Failed to
connect to MySQL: " . mysqli_connect_error(); }
Parsing errors are typically a simple mistype. If you put a ; in the wrong place, or don't put it at all... etc.
Try using the edits made by Grant Palin in your code, and see if this fixes your issue.

Problem with PHP Page connecting to DB

<?php
$dbserver="localhost";
$username="root";
$pass="root";
$link=mysql_connect("$dbserver","$username","$pass");
if(!$link){die('DB Connection Failed'.mysql_error()); }
echo('connected');
$Name=$_POST["namei"];
$ID=$_POST["pid"];
$Address=$_POST["address"];
$Phone=$_POST["phone"];
$query="INSERT INTO contact(Name,ID,Address,Phone) VALUES('".$Name."',".$ID.",'".$Address."',".$Phone.");";
echo($query);
?>
The code above is used by me to connect to a mysql db, i'm posting the contents to this page from an html page. As i checked there is no problem with POST. but on click of submit it gives me an error '500 Internal Server Error'.
I'm using Apache 2.2 Server, and mysql 5.5.
Can any one tell what is my mistake?
Thank you
First please run
<?php
echo 'phpversion: ', phpversion(), "<br />\n";
if ( !extension_loaded('mysql') ) {
die('mysql module not available');
}
echo 'mysql_get_client_info: ', mysql_get_client_info(), "<br />\n";
die;
to check whether a) you can run any php script and b) the mysql_* functions are available.
Then try
<?php
echo "start<br />\n";
error_reporting(E_ALL);
ini_set('display_errors', true);
flush();
$dbserver="localhost";
$username="root";
$pass="root";
$link=mysql_connect($dbserver, $username, $pass);
if(!$link) {
die('DB Connection Failed '.mysql_error());
}
echo "connected<br />\n";
if ( !mysql_select_db('dbname here', $link) ) {
die('DB selection failed. '.mysql_error($link));
}
echo "db selected<br />\n";
$Name = mysql_real_escape_string($_POST['namei'], $link);
$ID = mysql_real_escape_string($_POST['pid'], $link);
$Address = mysql_real_escape_string($_POST['address'], $link);
$Phone = mysql_real_escape_string($_POST['phone'], $link);
$query = "
INSERT INTO
contact
(Name,ID,Address,Phone)
VALUES
('$Name', '$ID','$Address','$Phone')
";
echo '<pre>Debug: query=', htmlentities($query), "</pre>\n";
It prints something in any case (echo/flush) and sets error_reporting + display_errors so that error messages are sent to the client (you don't want that in production, don't forget to remove those lines).
I also added the necessary calls to mysql_select_db() and mysql_real_escape_string() (needed as soon as the script really sends the query to the mysql server).
K,
You should add
ini_set('display_errors', 1);
error_reporting(E_ALL);
To the beginning of your script. This will stop the 500 errors and give you the proper error message so you have a better idea of what is going wrong.
It might be the echo($query); line, you only need echo $query; without the parentheses.

PHP error when using mysql related functions

I have another script that I can't figure out what is wrong with it. I attempted to use the
error_reporting(E_ALL);
to report the errors, but it doesn't report anything. Anyway, here is the code I'm having trouble with.
<?php
error_reporting(E_ALL);
$username = $_POST['user'];
$email = $_POST['email'];
$password = md5($_POST['pass']);
$currname = $_COOKIE['ZBrownTechnologyCorporationBeta'];
$con = mysql_connect("HOST", "USER", "PASS");
if (!$con) {
die('Unable to connect: '.mysql_error());
}
mysql_select_database("zach_blogin", $con);
if(empty($password)) {
$nothing = "nothing";
} else {
mysql_query("UPDATE members SET password = '$password' WHERE username = '$currname'");
}
mysql_query("UPDATE members SET Email = '$email' WHERE username = '$currname'");
if($username==$currname) {
$nothing = "nothing";
} else {
$query = ("SELECT username from members WHERE username = '$username'");
$result = mysql_query($query);
if (!$result) {
header("Location: " . $_SERVER['HTTP_HOST'] . "/public_html/Beta/account.php?invalid");
exit;
}
}
mysql_query("UPDATE members SET username = '$username' WHERE username = '$currname'");
header("Location: ". $_SERVER['HTTP_HOST'] . "/public_html/Beta/main_login.php?update");
?>
I have looked over this code for a while now. Can't seem to get the error reporting to work, so here I am again. Thanks to everyone who has helped, and who will help!
By Request of #Klinky:
When attempting to use this page (named myinfo.php ) in Opera, it displays the default message indicating that it is not able to find the page and/or the server. In Internet Explorer 8, it displays a 500 Internal Server Error.
Here are the server specs:
OS: Linux
HTTP: Apache v2.0.63
PHP: 5.3.3
MySQL: 5.0.91-community
I looked in the logs, and this is the error message:
[Sat Sep 25 21:34:08 2010] [error] [client 68.52.52.190] PHP Fatal error: Call to undefined function mysql_select_database() in /home/zach/public_html/Beta/myinfo.php on line 12, referer: http://zbrowntechnology.com/Beta/account.php
The only thing is, the database I tried to select does exist!
All your UPDATE queries are missing table name:
UPDATE TABLE_NAME SET .....
^^^^^
missing
I would suggest, every time you call mysql_query() check its return value. If its false, the query execution failed and you can get the cause of failure by calling mysql_error()
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
More errors:
You need to enclose strings in single quotes in a query:
mysql_query("UPDATE members SET password = '$password'....
^ ^
missing
Do it everywhere you are using a string in the query.
There is no builtin function name mysql_select_database. I guess you meant mysql_select_db
Change
mysql_select_database("zach_blogin", $con);
to
mysql_select_db("zach_blogin", $con);
Try setting the full URL for snippet:
header("Location: account.php?invalid");
HTTP spec says you should use the full url when doing a redirect. Though many browsers support a relative path. Try:
header('Location: ' . $_SERVER['HTTP_HOST'] . '/project-path/account.php?invalid');
REPLACE /project-path/ with the full path to where your .php files are.

Categories