Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Okay so I am running into an issue with my code since no matter what I change it to, it stays on the index page?
Here is my code
<?php
// Maintenance mode
$system = (mysql_query("SELECT * FROM system"));
if($system['maintenance'] == 1)
{
header('Location: /maintenance');
exit;
}
?>
I want it so if maintenance = 1 it would send you to the maintenance.php page but it doesn't can anyone help me with this? I tried,
if(!$system['maintenance'] == 1)
which works but I have this code in my maintenance.php page
<?php
$system = (mysql_query("SELECT * FROM `system`"));
if(!$system['maintenance'] == 0)
{
header('Location: /index');
exit;
}
?>
What I thought would send me back to the index page once that in the database it shows it is a 0 or that's what I want it to do. Can anyone please explain why my code isn't working?
I am a beginner php, mysql, and C++ coder / programmer so please try to explain it the easiest way possible.
I fixed it thanks to #Script47.
New code and works
<?php
$system = mysql_query("SELECT * FROM system");
$results = mysql_fetch_array($system);
if($results['maintenance'] == 1)
{
header('Location: /maintenance');
exit;
}
?>
The reason I do not need an extension for maintenance is because I have it set in .htaccess to ignore them, but for everyone to know it's a php file.
You need to actually fetch your results from the database. Look in to the link I provided. I will update my post with code.
<?php
$system = mysql_query("SELECT * FROM system");
$results = mysql_fetch_row($system);
if($results[yourColumnKey] == 1)
{
header('Location: /maintenance.php');
exit;
}
?>
http://php.net/manual/en/function.mysql-fetch-row.php
Edit 1
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Edit 2
You don't seem to be specifying a file extension on your header();.
header('Location: /maintenance');
--^
What is maintenance? A PHP file? A HTML file? You need to specify an extension too.
As you are a self-described beginner, it's probably best to learn how to do this using mysqli instead of using old deprecated code.
Below does essentially the same thing, but will last past the current version of php. It's a good habit to get into. (note if you are going to use any variables in your query, you will want to look up Prepared Statements
$conn = new mysqli($host, $username, $password, $dbname);
$system = $conn->query("SELECT maintenance FROM `system`");
while ($row = $system->fetch_assoc()) {
if($row['maintenance'] == 1) {
header('Location: /maintenance');
exit();
}
else {
header('Location: /index');
exit();
}
}
Related
This is the code for my log in forum. The problem with it is that it only accepts as correct credentials the first username and password (basically only the first row) any ideas as to how i could change it ?!
<?php
session_start();
include_once("connect.php");
$token = "";
if($con->connect_error){
die("Connection failed: ".$con->connect_error);
}
$sql = "SELECT * FROM authme";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
if(isset($_POST['realname']))
$username = $_POST['realname'];
if($result->num_rows>1){
if(mysqli_num_rows($result)>1){
$_SESSION['uid'] = $row['id'];
$_SESSION['realname'] = $row['realname'];
}
$password = '$SHA$'.substr($row['password'],5,16).'$'.hash('sha256', hash('sha256',$_POST['password']).substr($row['password'],5,16));
if($password == $row['password'] ){
header("Location: index.php");
exit();
}
else {
echo "INVALID INFORMATION, PLEASE RETURN!";
// header("location: index.php");
session_destroy();
exit();
}
}
}
}
?>
?
I decided to try to make a log in forum that uses a database which encrypts the passwords it receives through a register form. This code only takes as correct the first username and password i give in and its not enough, as you could imagine.
Welcome to programming with PHP. I'm going to try to share a few principles that may help you solve your problem.
1.) One of the best features in PHP is the print_r() function. Using this function you can output almost anything to text in the browser. So in this case you may want to insert a print_r($result) immediately following this line "$result = mysqli_query($con, $sql) or die(mysqli_error($con));". This will output the results of the query that PHP is receiving. This can be used to help you troubleshoot and determine why your code isn't working. Once you're done troubleshooting delete that line.
2.) You seem to have multiple checks for the number of rows inside the while loop. I'm not sure why you have thoose there, but you may want to check if those are causing your trouble by using echo or print to display to values in the browser for troubleshooting. Once you're done troubleshooting delete that line.
3.) Another overall concept for the data you are querying. It is inefficient to send a query that gets the entire table and returns it to the program, that then loops through every row looking for the data. Instead you should write an SQL query to return only the row of data the you want. Make sure you do use prepared statements.
4.) Your coding standards could use some improvement, if you clearly tabbed your statements it would be easier to read. Consider reading PSR-2. For example this code seems to be missing {}'s.
if(isset($_POST['realname']))
$username = $_POST['realname'];
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to restrict unpaid but loged in users to view view_profile.php page after login. Only paid users can visit that page. After login both users session will start but only paid users can see view_profile.php page. Unpaid users will be redirected to other page. My login.php file code is.
<?php
$username= mysql_real_escape_string($_POST['email']);
$password= mysql_real_escape_string($_POST['pass']);
$login= mysql_real_escape_string($_POST['login_user']);
if(isset($login)){
$mysqli = new mysqli("localhost","username","password","database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT * FROM users where email='$username' and password='$password'");
$row = $res->fetch_assoc();
$name = $row['first_name'];
$user = $row['email'];
$pass = $row['password'];
$type = $row['status'];
if($user==$username && $pass=$password){
session_start();
if($type=="Paid"){
$_SESSION['mysesi']=$name;
$_SESSION['mytype']=$type;
echo "<script>alert('Loged in successfully !')</script>";
echo "<script>window.location.assign('view_profile.php')</script>";
} else if($type=="Unpaid"){
$_SESSION['mysesi']=$name;
$_SESSION['mytype']=$type;
echo "<script>window.location.assign('index.php')</script>";
}
else{
echo "<script>alert('Wrong username or password')</script>";
echo "<script>window.open('login.php?not_admin=Check%20your%20Email%20and%20Password%20otherwise %20You%20are%20not%20an%20Registred%20User%20!','_self')</script>";
}
}
}
?>
view_profile.php page top code is..only paid users can see this page.. unpaid user even if he loged in but he will not see view_profile.php page..
<?php
//connect database
$con = mysqli_connect ("localhost","username","password","database");
//database connect error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_errno();
}
session_start(); // Use session variable on this page. This function must put on the top of page.
if (!isset($_SESSION['mysesi']) && !isset($_SESSION['mytype'])=='Paid')
{
echo "<script>window.location.assign('login.php')</script>";
}
?>
index.php page code is......
<?php
//connect database
$con = mysqli_connect ("localhost","username","password","database");
//database connect error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_errno();
}
session_start(); // Use session variable on this page. This function must put on the top of page.
if (!isset($_SESSION['mysesi']) && !isset($_SESSION['mytype'])=='Unpaid')
{
echo "<script>window.location.assign('login.php')</script>";
}
?>
This answer is to outline the syntax errors you are doing and is too long for a comment. You will need to do some of the work yourself in order for you to learn and to debug code.
"Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime."
Firstly, you're using mysql_real_escape_string() being an MySQL_ function which does not mix with MySQLi_ in your present code.
Therefore, you need to use its MySQLi_ equivalent being mysqli_real_escape_string() and it requires that the first parameter be a database connection.
I.e.:
$username= mysqli_real_escape_string($mysqli, $_POST['email']);
Consult the manual on the function:
http://php.net/manual/en/mysqli.real-escape-string.php
and do the same for the other ones and placing those either after you made the connection to your database, or place your database connection at the top of your code without its present conditional statement.
Then you are doing an assignment = rather than a comparison == for:
if($user==$username && $pass=$password)
^ there
Where it should read as $pass==$password with two equal signs.
Now in the first file, you should place session_start(); at the top of the login.php file. If your database connection fails, it will throw you an error and will be considered as outputting before header.
More on this: How to fix "Headers already sent" error in PHP
You also did not post the HTML form for this and is unknown if you are using the same name attributes for the inputs for the POST arrays, and if a POST method is used for the form.
I.e.:
<form method="post" action="your_handler_file.php">
Email:
<input type="text" name="email">
etc.
</form>
Then for your conditional statement for the session arrays in the view_profile.php file, is giving you a false positive.
if (!isset($_SESSION['mysesi']) && !isset($_SESSION['mytype'])=='Paid')
That is interpreted as:
if session mysesi array is NOT set AND is NOT set equals to Paid
Rather than the intended:
if (!isset($_SESSION['mysesi']) && $_SESSION['mytype']=='Paid')
which would be interpreted as:
if session mysesi array is NOT set AND session array equals to Paid
and the same thing applies for the one inside the index.php file:
if (!isset($_SESSION['mysesi']) && !isset($_SESSION['mytype'])=='Unpaid')
which is interpreted the same way and should read as:
if (!isset($_SESSION['mysesi']) && $_SESSION['mytype']=='Unpaid')
NOTA: You need to keep in mind that the words Paid and Unpaid are case-sensitive. Therefore, if those words in the database are paid and unpaid being lowercase letters, then that will fail.
It is important that those match.
The same thing applies to both if($type=="Paid") and else if($type=="Unpaid").
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
and check for errors against your queries using mysqli_error(). However, that function requires a database connection as the parameter.
I.e.: mysqli_error($mysqli).
Additional tools you can use are:
var_dump(); - http://php.net/manual/en/function.var-dump.php
print_r(); - http://php.net/manual/en/function.print-r.php
And of course viewing your HTML source.
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Prepared statement:
You should use a prepared statement in MySQLi_, or PDO with a prepared statement.
Footnotes:
This $_POST['login_user'] is unknown and if it is related to a submit button. If it is, you don't need to escape it, but rather to use a conditional statement like this:
if(isset($_POST['login_user'])){...} rather than if(isset($login)){...}.
The rest is up to you to get your code working.
Error checking links to consult:
http://php.net/manual/en/mysqli.error.php (For your query)
http://php.net/manual/en/function.error-reporting.php (For PHP)
And use the method of redirection as outlined in comments.
I am attempting to create new tables every time I post to this method, but for some reason I can not figure out why it dies.
<?php
$host = "127.0.0.1";
$username = 'cotten3128';
$pwd = 'pwd';
$database = "student_cotten3128";
$pin = $_REQUEST['pinSent'];
$words = $_REQUEST['resultSent'];
$tableName = $pin;
$db = new mysqli($host, $username, $pwd, $database);
if ($sql = $db->prepare("CREATE TABLE $pin (id INT(11) AUTO_INCREMENT);")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die('Could not create table');
}
for($i=0;$i<count($words);$i++){
if($sql = $db->prepare("INSERT INTO ".$pin.$words[$i].";")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die("Could not add data to table");
}
}
mysqli_close();
?>
Any help or insight would be greatly appreciated.
The intention of my post is to help you finding the issue by yourself. As you did not added much information I assume my post is helpful for you.
Based on the code you have shared I guess you mean one of your called die() functions is executed.
Wrong function call
As Jay Blancherd mentioned mysql_close is the wrong function. You rather have to use mysqli_close as you created a mysqli instance.
Beside of that mysql_* is deprecated and should not be used anymore.
Debugging Steps
Not only for this case but in general you should ask yourself:
Is there an error message available? (Frontend output, error log file, ...)
YES:
What's the message about?
Is it an error you can search for? E.g. via a search engine or the corresponding documentation?
Look up in the bug tracker (if available), by the software developer of the software you are using, and if it has not been reported yet report the issue.
NO: (if none error message available OR you cannot search for it as it is a custom error message)
Search in the files of the software you are using for the error message and start a core-debugging.
STILL NO SOLUTION?:
Ask on stackoverflow.com e.g. and tell your issue and the steps you have performed to find and fix the bug. Post only as much code as necessary plus use a proper format.
Debugging in your case:
In order to narrow down the scope. Which of the die() is executed? Depending on that echo the query to execute just before it actually is executed. Then copy the SQL query to an SQL editor and look at it syntax. After that you probably know the problem already.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
This query was working on mij older login script, But now that i have this new login script, my code had to change a litlle, Wich i cant seem to pull off. Im think the troubles are in the end where the if user is online is checked...
This is my code
<?php
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
function pay_credits() {
mysqli_query("UPDATE `tbl_users` SET `credits`=`credits`-'1' WHERE `watching`='1' AND `credits`>'0' AND userID=:uid");
}
?>
<?php
pay_credits();
?>
The top script is working fine, But the function pay_credits doesnt work, Ive tried changing mysql to mysqli as i hear alot over that it has deprecated and stuff, But still no result, Ive also been reading about pdo but i have no knowledge of this. Any help is welcome, I also like to learn so maybe you can explain what you`ve done a litlle. Thnx :)
First: if you read mysqli_query manual, you'll see that mysqli_query takes two arguments. First is link and second is a query string.
Do you see a link in your pay_credits function? Nope.
Second: I noticed that you use PDO::FETCH_ASSOC and then suddenly switch to mysqli.
PDO and mysqli are totally different APIs and you should choose which one you use.
You use pay_credits() without settings, your function mysqli_query need a params for db connection.
I can't figure out why I'm getting the Commands out of sync; you can't run this command now error. I can't seem to find a way to fix this.
As you can probably see from the code, I need to execute TWO SQL statements. One to check if the password is correct, and the other, which runs only if the previous one returns true, to store all user data in session variables.
Here is my code:
$check_pw_query = $conn->query("CALL checkPassword('{$username}', '{$password}')");
$check_pw_fetched = $check_pw_query->fetch_assoc();
$check_pw_query->close();
if($check_pw_fetched['password_correct']) {
unset($check_pw_fetched);
if(!$get_user_data = $conn->query("CALL getUserData('{$username}')")/*->fetch_assoc()*/) {
echo $conn->error;
}
$_SESSION["user_username"] = $username;
$_SESSION["user_id"] = $get_user_data["id"];
$_SESSION["user_name"] = $get_user_data["name"];
$_SESSION["user_email"] = $get_user_data["email"];
$_SESSION["user_type"] = $get_user_data["type"];
$conn->close();
unset($conn);
send_home(false);
}
Help is much appreciated.
Thank you
Ok, as there were no real helpfully answers, I'll answer it myself, to hopefully help someone else with the same problem.
The problem is that, whenever you call a stored procedure, it will output one more result that defined anywhere. So if your procedure returns 1 value, php will get 2. The last one is only there to tell you that there are no more values. BUT you have to deal with that one as well to free the connection ($conn in my example).
So, that you do is, simply, add this to your code, right after the $check_pw_query->close(); :
$conn->next_result();
And there you have it. It will now work perfectly fine.