I've got my login and session validity functions all set up and running.
What I would like to do is include this file at the beginning of every page and based on the output of this file it would either present the desired information or, if the user is not logged in simply show the login form (which is an include).
How would I go about doing this? I wouldn't mind using an IF statement to test the output of the include but I've no idea how to go about getting this input.
Currently the login/session functions return true or false based on what happens.
Thanks.
EDIT: This is some of the code used in my login/session check but I would like my main file to basically know if the included file (the code below) has returned true of false.
if ($req_method == "POST"){
$uName = mysql_real_escape_string($_POST['uName']);
$pWD = mysql_real_escape_string($_POST['pWD']);
if (login($uName, $pWD, $db) == true){
echo "true"; //Login Sucessful
return true;
} else {
echo "false";
return false;
}
} else {
if (session_check($db) == true){
return true;
} else {
return false;
}
}
You could mean
if (include 'session_check.php') { echo "yeah it included ok"; }
or
logincheck.php'
if (some condition) $session_check=true;
else $session_check=false;
someotherpage.php
include 'session_check.php';
if ($session_check) { echo "yes it's true"; }
OR you could be expecting logincheck.php to run and echo "true" in which case you're doing it wrong.
EDIT:
Yes it was the latter. You can't return something from an included file, it's procedure not a function. Do this instead and see above
if (session_check($db) == true){
$session_check=true;
} else {
$session_check=false;
}
Actually..
$session_check=session_check($db);
is enough
Depending on where you want to check this, you may need to declare global $session_check; or you could set a constant instead.
you could have an included file which sets a variable:
<?php
$allOk = true;
and check for it in you main file:
<?php
include "included.php";
if ($allOk) {
echo "go on";
} else {
echo "There's an issue";
}
Your question seems to display some confusion about how php includes work, so I'm going to explain them a little and I think that'll solve your problem.
When you include something in PHP, it is exactly like running the code on that page without an include, just like if you copied and pasted. So you can do this:
includeme.php
$hello = 'world';
main.php
include 'includeme.php';
print $hello;
and that will print 'world'.
Unlike other languages, there is also no restriction about where an include file is placed in PHP. So you can do this too:
if ($whatever = true) {
include 'includeme.php';
}
Now both of these are considered 'bad code'. The first because you are using the global scope to pass information around and the second because you are running globally scoped stuff in an include on purpose.
For 'good' code, all included files should be classes and you should create a new instance of that class and do stuff, but that is a different discussion.
Related
I created a function to allow me to debug PHP scripts so long as a variable ($debug) is set to 1:
function debug($msg) {
if ($debug == 1) {
echo $msg;
} else {
return false;
}
}
That way, at the top of my script (before the functions.php file is called), I write:
$debug = 1;
to enable debugging, then:
debug("Function executed: " . $data);
at certain points so that I know string values/whatever at that point, with the desired response being the message displayed upon the screen.
However, regardless of what the value of the $debug string is, I never see any echo'd statements.
How can this be achieved?
Debug is not available to your function because it is out of scope. You either:
Need to pass it as a parameter
Use the global keyword to include it in your function (discouraged)
.
function debug($msg, $debug){
if($debug==1){
echo $msg;
} else {
return false;
}
}
or
function debug($msg){
global debug;
if($debug==1){
echo $msg;
} else {
return false;
}
}
It's difficult to say because you provided too few data.
The reason can be that your $debug variable is not known inside a function. Because using globals is not adviced, consider using constants define("DEBUG",1);.
EDIT
I presented within another question how I use a class for doing the same thing as class names are also globally accessed.
The global variable is not accessible to functions until you make it so. Eg:
function debug($msg( {
global $debug;
etc...
PS: Please, don't do this. Find a better way. Really.
$debug is your global variable, so it is not accessible in your function
There is also the possibility to declare a const, (and then just insure the namespace is correct), like this:
const debug = true;
function newPrint($msg) {
if (\debug === true) {
echo $msg;
} else {
return false;
}
}
\newPrint("heey");//will print "heey"
so just dont use a variable, but use a const.
Im adding php inside an article using DirectPHP plugin.
My goal is to create a script that will include a file with text when the user has member = true; and when not to not show anything.
I have added this piece of code in a module in the top next to the logo:
<?php
if ($user =JFactory::getUser()->guest)
{
$member = false;
echo "Welcome guest, sign up and read nice quotes";
}
else
{
$member = true;
$user =& JFactory::getUser();
echo "Welcome " . $user->username;
}
?>
I have set member = true; now that the person has signed in. If he isnt signed in its on false.
Then inside the article I have:
<?php
if ($member == false)
{
$file = file_get_contents ('quotes/quotes.html');
echo $file;
}
?>
<hr id="system-readmore" />
<?php
if ($member == true)
{
include_once JPATH_SITE.'/quotes/random.php';
echo ShowQuotes();
}
?>
I cant find the problem making this not run. The quotes are shown for both $member = false; and $member = true; Are includes always being parsed despite the if statement? Same goes for file_get_contents? I tried to see if the $member declaration from the header is being kept within the parsing and wrote:
<?php
if ($member = true)
{
echo "Logged in";
}
?>
and it worked good so the problem is within the include_once and file_get_contents, I tried to pinpoint it as much as I can.
Thanks in advance for your help!
This is probably your issue:
if ($member = true)
{
echo "Logged in";
}
This is always assigning the value of true to $member.
Also here:
if ($user =JFactory::getUser()->guest)
You might have the same assignment problem (not sure if you intended to set $user and do a conditional at one here.
I might suggest getting in the habit of writing condditionals like this:
if (true === $member) { ... }
By inverting the order of the items, if you ever accidentally type = instead of == or ===, then you will get an error, instead of having the code silently perform unexpectedly.
You seem to have a scope issue here: you are declaring $member in a module, but $member won't be available to the article: and php will evaluate ($something == false) to always succeed if $something is undefined, if you want to check if a variable is really false you need to use ($something===false). Read more here: http://www.php.net/manual/en/language.types.boolean.php
That being said, since there is no real overhead to JFactory::getUser()->guest, just use that as well in you article!
btw, enable notices in your php configuration (either on screen or to a log file) and make sure you read that as you develop, it will tell you whatever is wrong, developing without seeing the errors is a guessing game, you can only bang your head against the wall so many times... you eventually need to switch on the light :-)
I want to check if 'dbas.php' is included in 'ad.php'. I wrote the code -
ad.php
<?php if(file_exists("dbas.php") && include("dbas.php")){
// some code will be here
}
else{echo"Database loading failed";}
?>
I successfully tested the file_exists() part but don't know if the include() will work well or not, cause I tried in localhost and if the file is in directory then it never fails to include. So I don't know how this code would behave in the server if much traffic be there. So please tell me is my code correct ?
-Thanks.
Solved: Thank you so much for your answers.
Using php's require method is more suitable if you want to be absolutely sure that the file is included. file_exists only checks if the file exists, not if it's actually readable.
require will produce an error if inclusion fails (you can catch the error, see Cerbrus' answer).
Edit:
However, if you don't want the script to halt if the inclusion fails, use the method is_readable along with file_exists, like:
if( file_exists("dbas.php") && is_readable("dbas.php") && include("dbas.php")) {
/* do stuff */
}
Simply use require:
try {
require 'filename.php';
} catch (Exception $e) {
exit('Require failed! Error: '.$e);
// Or handle $e some other way instead of `exit`-ing, if you wish.
}
Something that wasn't mentioned yet: you could add a boolean, like:
$dbasIncluded = true;
In your dbas.php file, then check for that boolean in your code. Although generally, if a file doesn't include properly, you'd want php to hit the brakes, instead of rendering the rest of the page.
file_exists("dbas.php") Is doing the checking. If it exists, then do the include.
if(file_exists("dbas.php"){
include("dbas.php")
//continue with you code here
}
Put your functionality in a function and use function_exists to check if it is there.
include ("php_file_with_fcn.php");
if (function_exists("myFunc")) {
myFunc();
// run code
} else {
echo "failed to load";
}
In your case, the incusion file would be
function db_connect() {
$user = "user";
$pass = "pass";
$host = "host";
$database = "database";
mysql_connect($host, $user, $pass);
return mysql_select_db($database);
}
and the main file:
include("db_connect.php");
if (function_exists("db_connect")) {
if (db_connect() === TRUE) {
// continue
} else {
// failed to connect (this is a different error than the "can't include" one and
// actually **way** more important to handle gracefully under great load
}
} else {
// couldn't load database code
}
Use this code instead of your code, because in your code if file is not exist in server then php errors arise and that is not good so use this code:
if(file_exists("dbas.php")) {
include_once("dbas.php");
} else {
echo"file is not found";
}
This code means if file exists on server then function include else file is not found echo.
write
echo "file is includ"
at the end of "dbas.php"
I made a login script, when I want to check when the user is logged in, I use the function logged_in(), which consists of:
function logged_in()
{
if(isset($_SESSION['id']))
{
return true;
}
else
{
return false;
}
}
the session is set here:
else if ($login === true)
{
echo 'Login success.';
include 'include/aside.php';
include 'include/footer.php';
$userid = id_from_username($username);
$usernameforsession = username_from_id($userid);
$_SESSION['id'] = $userid;
$_SESSION['username'] = $usernameforsession;
header( "refresh:2;url=index.php");
exit();
}
And this is an example of me using it in 'index.php':
if(logged_in() === true)
{
echo 'Site content when user is logged in.';
} else if(logged_in() === false)
{
include 'include/widgets/register.php'; //registration form
}
And yes, the function is included in every page.
I made this function so it should work...
Why isn't it working?
Replace this code:
if(logged_in() === true)
With this code:
if(isset($_SESSION['id']))
That cuts out all the middlemen.
Although you have listed quite a bit of code, are you sure you are including session_start(); at the top of each page? You need to call this before you do anything at all with the session variables.
The second thing is that the error message is showing that the function isn't defined - are you sure you have it either in the source for the page or as an include to the code that defines it on each page?
If you have it in a file called 'functs.php', you need to include() it in every page that will make a call to that function.
If you are absolutely sure that the declaration is being included on every page, then I would suggest that you check to make sure the function is not declared as a method inside an object.
Why is the construction brittle? I tried "!empty ( get_original_passhash() )" as a condition, but it ignites the error that you cannot use the return value.
if ( get_original_passhash () != '' )
{
set_login_session ( get_original_passhash() );
}else
print("Please, log in.");
I would be inclined to assign the variable before you test it, and probably also clean up your formatting a little too:
$original_hash = get_original_passhash();
if ($original_hash != ""){
set_login_session(get_original_passhash());
} else {
print("Please Log In");
}
You should also ensure that get_original_passhash() is returning the right type of variable - interger, string, boolean, etc.
Edit:
function get_original_passhash(){
$dbconn = pg_connect("host=localhost port=5432 dbname=heoa user=heoa password=123");
if(!empty($passhash_session)){
return $passhash_session;
} else {
return $passhash_post;
}
}
What is this code supposed to do? It connects to a database, and then tests a variable that just appears out of nowhere? Your code isn't working because, from the example's you've provided us, nothing is even being set. Is this the full source code for this function?
You may want to split up your logic:
if (is_logged_in()) {
set_login_session(get_original_passhash());
} else {
print("Please Log In");
}
Since, in the conditional, you don't want the pass hash. You want to know if they're logged in or not.