UPDATE: Not sure why the answer was removed. But i did receive a solution and for future views I am leaving the original code below. But to make this work we simply needed to change:
if (site_active == 0)
TO:
if ($row['site_active'] == 0)
We also removed the "else exit;" code so if the site was active the page would continue to load like normal. Thank you to whoever posted this answer. Not sure why you deleted it because it worked.
Original Question:
Ok, I am using MYSQL as a database and then php for my script. I am wanting to make a script that checks whether a user's site is "active" or "disabled" this code will be placed at the beginning of each webpage. If the users website is "active" then the website will continue to load normally. If the users website is "disabled" then the website will redirect to an error page that states so.
If my client does not pay the monthly hosting fee then I will set the site to "disabled" in the database and the site will not be accessible until the payment is made. which then I will return it to an "active" state and it will be accessible again. I have came up with the following code so far (I am new to php so if it's stupid don't judge please!) When this code is executed it redirects to the page I have set no matter what rather than displaying the regular site. Any help or suggestions to make this work would be greatly appreciated!
<?php
$con=mysqli_connect("CONNECTION INFO REMOVED FOR SECURITY REASONS");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mypanda_clients
WHERE id='34'");
while($row = mysqli_fetch_array($result))
{
if (site_active == 0)
{
header('Location: http://www.green-panda.com/');
}
else
{
exit;
}
}
?>
<html>
<h2>Congratulations, your site is active!</h2>
</html>
Give this a try,
if ($row['site_active'] == 0)
{
.....
}
Related
My boss purchased some web-based software (PC Repair Tracker...it's amazing), and put me in charge of installing it on our domain, configuring the database, the pricing, the look and feel (html/css). the ticketing system, etc. It's basically a template that you purchase and fully customize to meet your needs.
Configuring it wasn't too bad, even considering I am still a novice with PHP MySQL, etc. My boss requested I "make it logout after a certain time" because it contains sensitive info, and repairs are tracked by employee to know who to go to when information is needed on a device that's at our store.
What he means is that I need to write a timeout function.
The problem is not just creating the timeout function, but knowing where to put it? There are probably close to 100 files the website folder, each one of them a .php file (except for css stuff and images). Do I use the intuitive approach and start with login.php?
And how do I know what to call my variables?
The interface begins at the landing page with a login form. I don't think I would want to start at login.php, because they need to at least be logged in.
I installed FirePHP for Firefox and I noticed a function being called: It says:
GET ajaxhelpers.php?func=refreshnotifications
It pops up every minute or so. When I find that .php file, it's very short, and says:
if (array_key_exists('func',$_REQUEST)) {
$func = $_REQUEST['func'];
} else {
$func = "";
}
function nothing() {
}
function refreshnotifications() {
require("deps.php");
require_once("common.php");
echo pcrtnotify();
}
switch($func) {
default:
nothing();
break;
case "refreshnotifications":
refreshnotifications();
break;
}
?>
I also found a "validate.php" that sends a user to the login page. Could I put a function there?
<?php
include("deps.php");
$validated = false;
//Use $_COOKIE to get the cookie data . same usage as $_POST
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])) {
$user = $_COOKIE["username"];
$pass = $_COOKIE["password"];
//Begin validation code
if(isset($passwords[$user])) if($passwords[$user]== $pass) $validated = true;
//End validation code
}
if($validated) {
//Ok; don.t need to do anything
} else {
//Make user go to login page
die("please login");
exit;
}
?>
Is this a good start? Sorry for the lengthy question. I'm not asking for homework advice or anything. I'm just trying to learn php in a crash course fashion because he's going to want results yesterday. Lol.
It seems like I could put a condition in there that says,
if($validated && idle_time > time_allowed) {
go to logout.php
}
But then again, I'm a php noob.
Search for session_start() and before that line add the following
session_set_cookie_params(3600,"/");
The number is in seconds. So 3600 represents one hour.
Alright. I did some more digging, and I discovered a validate2.php, and logout.php file. Well, I already knew logout.php existed, I just looked closer at the code.
Inside, it contains conditional logic for a variable, $cookiedomain, and it also contained values for when a cookie expired for the user. If I'm saying all of this wrong, forgive me. I'm still learning php. Just trying to apply fundamental logic to all this.
So, what the validate.php file eventually does is check if the boolean $validated is true. If it's true, it continues and give you the ability to refresh. If it is not validated, you are presented with a tiny button on the screen that says "Please login".
1) This was incredibly sloppy and hard to find.
2) The time was set to 10 hours.
So, for testing purposes, I set the numbers to 20 in validate.php and logout.php, like so (I'm using the new value - 120 - in my code because I changed it since 20 seconds was too short obviously):
login.php
if(isset($cookiedomain)) {
setcookie("username", $user, time()+120, "/","$cookiedomain");
setcookie("password", $pass, time()+120, "/","$cookiedomain");
} else {
setcookie("username", $user, time()+120, "/");
setcookie("password", $pass, time()+120, "/");
}
logout.php
if(isset($cookiedomain)) {
setcookie("username", $user, time()-120, "/","$cookiedomain");
setcookie("password", $pass, time()-120, "/","$cookiedomain");
} else {
setcookie("username", $user, time()-120, "/");
setcookie("password", $pass, time()-120, "/");
}
validate2.php
if($validated) {
//Ok. don't need to do anything
} else {
//Make user go to login page
echo '<script type ="text/javascript">alert("Sorry, ' . $user . ', but you have been logged out due to inactivity.");</script>';
exit;
}
It's still not printing the user name, just a ' ', so I still need to work on that. The ugly button is gone, and it gives the user a nice, obvious notification that they've been logged out.
I would like to make the button redirect, so now on to working that part out.
I've been developing a news letter system locally and everything works fine . The mystery begun when I uploaded the whole content to my server , I could see the index page but when I enter the username / Password to log in (in the index page), I get redirected to "authenticate.php " where the Post data are processed this way :
<?php include("includes/initialize.php");
if(!isset($_POST['username']) OR !isset($_POST['password']))
{
// no data were given
redirect_to("error.php");
}
elseif(!$user = User::authenticate($_POST['username'],$_POST['password']))
{
// user not found in the database
redirect_to("error.php");
}
else {
$session->login($user);
redirect_to("enewsletter.php");
}
?>
On this page I get stuck (not on localhost ) , the server is rendering a blank page . after some tests , I tell you what happens : If I fall in the if situation i get redirected to error.php , but when I enter some credentials , It's doing nothing :/
So I added an echo statement to keep trace of the code :
and I had this remark, every time the script meets to a line containing a method that looks in the database (OOP approach) the server is always rendering blank pages , I tried it on many pages and it's always the same . I changed the database connection type from PDO to mysqli (because I thought the server is not supporting PDO) but no change !!
Does any one has a clue , what could be the reason?
well ,
it was just a " Self instead of self " problem ...
Thank you all for your help ;)
I am having an issue with my adding a new member page,, also having an issue with my login page which is similar in code. Both worked fine, tested multiple times and ways and then I switched hosting companies. The rest of the database driven site works fine still except this part. Have no idea why and possibly just need fresh eyes on it. I am fairly new to php and mysql to begin with,,, then attempting to learn the newer versions to keep my code upgraded has me at this point unable to figure out why the code is no longer working. Any help would be much appreciated. Thanks.
The page will run up to this point,, I have confirmed that using echo, then it fails. The page itself, does not load, justs stays completely blank and the little loading wheel in the tab corner just spins and spins.
$sql="SELECT * FROM table WHERE field LIKE'$username'";
$rs=$db->query($sql);
$arr = $rs->fetch_all(MYSQLI_ASSOC);
// test to make sure there was not an issue loading the db
if($rs != true) { // start second if in nested section
// if any errors in reading the db redirect to a general db is down error page
//close db connection
mysqli_close($db);
// redirect header goes here, removed for this post
} else { // else to go with second if
// get number of rows returned in this case should be 0 or 1
$rows_returned = $rs->num_rows;
echo "num of rows are $rows_returned";
} // end second if
I am new to php and mysql and am having problems understanding why a specific function to update a value within the databse isnt working.
I want to be able to change a "0" int to a "1" when the user clicks the link. (I am using the value 0 / 1 to track if the user account is active or not).
The link in question reads:
<?php
$user = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
//check to see if the user is active or not
if ($user [0]['active'] == 0)
{
printf("Your account is not currently active ");
printf('Click Me');
printf(" to reactivate");
}
//assuming they have logged in they will probably want to make themselves active
?>
When I click the link the console reports:
Uncaught ReferenceError: activate is not defined
I have defined activate in a separate functions.php file that is being loaded and has the correct permissions. (I am sure it is being loaded by the code above as when I define activate manually in the code above the I get an error telling me I cannot define 2 functions with the same name).
The functions.php section reads:
function activate()
{
require("../templates/activate_user.php");
exit;
}
Finally, the activate_user.php reads:
<?php
// configuration
require("../includes/config.php");
query("UPDATE users SET active = 1 WHERE id = ?", $_SESSION["id"]);
return false;
?>
I have searched and searched on how to fix this error, but I have not been able to fix the issue. I am guessing it might be related to scope of activate, but am not sure that is the right path.
Any help well received, this is my first venture into php/mysql so all points welcome.
Thanks;
Andy
The onclick="activate();" is Javascript code. The rest of your code is written in PHP. Both won't work together this way.
In the interest of keeping things simple I have solved the problem by calling the same page and defining the function within that page:
<?php
function activate()
{
require("../templates/activate_user.php");
exit;
}
//check to see if the user is active or not
if ($user [0]['active'] == 0)
{
printf("Your account is not currently active ");
printf('Click Me');
printf(" to reactivate");
//assuming they have logged in they will probably want to make themselves active
if(isset($_GET['action'])&& $_GET['action'] =='callfunction'){
activate();
}
}
?>
Not sure if its pretty or not, but it certainly works. Thanks for the help and comments (made searching much easier!)
I currently have a list of users in my mysql database. One of the columns is "type". I am trying to display certain data if type is equal to admin. If type is equal to anything else, it should just echo an error message.
Unfortunately, I have tried multiple methods but it just does not seem to be working out for me. Can anyone help me get this to work properly?
This is what I have, but obviously I am doing something wrong....
<?php
$usertype = $_SESSION['type'];
if ($usertype == "admin" ){
?>
admin stuff only goes here
<?
}
else
{
echo "not priveleged usertype";
}
?>
EDIT:
The following code works when displaying via username, however, I need content displayed by usertype, not the username.
<?php
if($_SESSION['user']['username'] == "oneoftheadminusernames" )
{
?>
Each page has to start with
<?php
#session_start();
?>
otherwise, php does not "see" the sessions contents. So that's probably it.
The # prevents the php error: A session has already been started... by the way.
Now, every page that uses the session must have this directive at the top.
At least, in a quick example, that reproduces your error perfectly.
If you are saving each logged in users type field in $_SESSION['type'] variable than the code you are writing is correct. Or if you are storing type in another variable than you that variable to check.
i have an idea like add a field EnableFlag in the table. if enablee flag is set to 1 consider it as a admin else as a User;