Issue with PHP Include - php

I have a function called uploadfile:
<?php
function UploadFile (){
//ftp credentials set here
$connection = ftp_connect($server);
$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);
if (!$connection || !$login) { die('Connection attempt failed!'); }
$upload = ftp_put($connection, $dest, $source, FTP_ASCII, $startpos = 0);
if (!$upload) { echo 'FTP upload failed!'; }
ftp_close($connection);
}
I am calling it like this:
<?php
if( isset( $_REQUEST['modify'] ))
{
UploadFile();}
?>
The problem is that the code runs as soon as the page loads (without any call to the function). it seems to make no difference where the include_once 'upload file.php' is placed.
Obviously I don't want the code to run until the function is called.
Advice/pointers appreciated...

I believe the comments have pretty much answered the question.
The 'include_once' is not going to run the function, it just includes the reference to the function. You could even put the function in the same file as the if condition and it still won't run unless the if condition is met.
For a case where the function doesn't run, you could change the if condition to:
<?php
if(false){
UploadFile()
}
?>
If it is still running every time after this point, you have another call to UploadFile somewhere else in your code.

Related

security for a page function in php

so here I have a page that holds all the functions.
I give name "init-admin" and I call all these functions on all admin pages
this is the content of init-admin.php
<?php
session_start();
require_once "admin-functions/db.php";
require_once "admin-functions/admin.php";
require_once "admin-functions/navigation1-content.php";
require_once "admin-functions/navigation1-press.php";
require_once "admin-functions/navigation1-restrospective.php";
require_once "admin-functions/navigation1-inquiries.php";
require_once "admin-functions/navigation2-earrings.php";
require_once "admin-functions/navigation2-necklaces.php";
require_once "admin-functions/navigation2-bracelets.php";
require_once "admin-functions/navigation2-sets.php";
require_once "admin-functions/navigation2-men-jewelrys.php";
require_once "admin-functions/navigation2-object_arts.php";
require_once "admin-functions/navigation2-rings.php";
require_once "admin-functions/navigation2-pin_pendant.php";
?>
and this is one of the functions I call as an example. Its function name is "admin.php" this is his content
//1. REGISTER
function Register($username, $email, $password){
global $connect;
$username = mysqli_real_escape_string($connect, $username);
$email = mysqli_real_escape_string($connect, $email);
$password = mysqli_real_escape_string($connect, $password);
$password = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO admin (admin_username, email, password, actor) VALUES ('$username', '$email', '$password', '1')";
if( mysqli_query($connect, $query) ){
return true;
}else{
return false;
}
}
function prevent_twin_names($username){
global $connect;
$username = mysqli_real_escape_string($connect, $username);
$query = "SELECT * FROM admin WHERE admin_username ='$username'";
if( $result = mysqli_query($connect, $query) ){
if(mysqli_num_rows($result) == 0) return true;
else return false;
}
}
my problem here if i give session like
require_once "core-admin/init-admin.php";
if( !isset($_SESSION['admin_username']) ){
$_SESSION['msg'] = 'page can not open';
header('Location:admin_login.php'); exit();
}
on the function page I get an error "to many redirect".
so I want to ask here if the function page if not given session will be dangerous?
but if I try to call the page function in the browser page that appears only blank pages.
can anyone explain? ty
Okay, so you seem to have various problems here, I will try to answer one question at a time.
header()
With PHP we have the header function; we can use for various purposes, to change the location of the page:
header('Location: index.php');
Or to set the type of content your page is displaying:
header('Content-Type: text/plain');
This is useful when dealing with certain parts of your code. header location is probably the most used function, but you have to be careful when using it. It's usually bound to run you into problems.
The error you are getting comes from redirecting the user too many times with one attempt. That, I believe, is different for each browser.
To fix that error you have to look for where else you set a header, and make sure you only set one header per page. Also note:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Functions
So first let's deal with your function questions. The reason your function page is blank when you load it in your browser it's because it's inside of a function. That means that the block of code before your eyes will only run when initiated. Thus, a blank page.
In practice this would look like:
function foo()
{
return 'Hello Foo!';
}
To get the output out of that function I have to initiate it in my code somewhere, either in it's own file (not a good practice) or where in the code I need it. You can initiate it by
echo foo();
or assign it to a variable:
$foo = foo();
The purposes of functions is so that you do not have to write the same code over and over again. You write one block of code with general guidelines and each time you need the code to be executed, you then call the function.
Sessions
Now that we have discussed functions, please do not add a session to your function. You want functions to be as reusable as possible, add a session at the top of your page.
<?php
session_start();
// some code ...
if(isset($_POST['submit'])
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if( Register($username, $email, $password) === true )
{
echo 'Registration Complete';
}
else
{
echo 'Registration failed';
}
}
?>
<html>
<head>
</head>
<body>
<form id="registration">
</form>
</body>
</html>
Now when the register, you can call the function. That would be better practice than to start you session with your function.
Here's why, your registration function will come after some code has already been written; a session has to start at the top. Or else it would not run properly. To fix that you can create a function which create a session for you:
function start_my_session()
{
session_start();
}
This one is very simple, but you can buff up your security with different session function. For more information on session security look at PHP's Manual.

Login script issue with database

I wrote a login script for a website that I am building using resources I have found online. When I ran my code on a local server it worked fine but now that I am actually running it online on a real server it doesn't work. I think I have narrowed down my error but with being new to PHP and not having prior experience with MySql I can't really fix my problem. This is the file for the login script:
//login file
<?php
class Login{
private $db_connection = null;
public function __construct(){
session_start();
$this->dologinWithPostData();
}
private function dologinWithPostData(){
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$this->db_connection()->connect_errno) {
// escape the POST stuff
$email = $_POST['email'];
// database query, getting all the info of the selected user (allows login via email address in the
// username field)
$sql = "SELECT email, password
FROM users
WHERE email = '" . $email ."'";
$result_of_login_check = $this->db_connection->query($sql);//This is 0
// if this user exists
if ($result_of_login_check->num_rows == 1) {
// get result row (as an object)
$result_row = $result_of_login_check->fetch_object();
// using PHP 5.5's password_verify() function to check if the provided password fits
// the hash of that user's password
if ($_POST['password'] == $result_row->password) {
// write user data into PHP SESSION (a file on your server)
$_SESSION['email'] = $result_row->email;
$_SESSION['user_login_status'] = 1;
} else {
$this->errors[] = "Wrong password. Try again.";
$_SESSION['user_login_status'] = 0;
}
} else {
$this->errors[] = "This user does not exist.";
}
} else {
$this->errors[] = "Database connection problem.";
}
}
print_r($this->errors);
}
public function isUserLoggedIn()
{
if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) {
return true;
}
// default return
return false;
}
}
?>
I run it in another file that is essentially the following:
//Run file
require_once("dbconfig.php");
include_once("login.php");
$login = new Login();
if($login->isUserLoggedIn() == true){
//go to another page }
The variables used to access the database are instantiated in dbconfig.php and are correct. With this code I get an error that says the page is not working and is unable to handle the request. When I comment out the line
if (!$this->db_connection()->connect_errno) {
and the else statement following it, the output is "This user does not exist". So I think the error has something to do with $this->db_connection()->connect_errno). If you can find where I went wrong or have any advice on how to rewrite the script to make it better, it is greatly appreciated.
This is a database establishing error your live remote server database configuration is different.Please verify you dbconfig.php file make sure
database name, host , port , username , password are well defined with your live database
This is wrong:
if (!$this->db_connection()->connect_errno) {
db_connection is simply a variable containing your DB connection object. It is NOT a method.
You probably want
if (!$this->db_connection->connect_errno) {
^--note lack of ()
instead.
I think issue with this follwoing check. your result gets more than 1 records.
// if this user exists
if ($result_of_login_check->num_rows == 1) {
......
}else{
$this->errors[] = "This user does not exist.";
}
make sure your email address is unique in Data table, if it is not unique then your above statement will fail and show the text "This user does not exist." from else part

How can check a php file is successfully included?

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"

Fatal error: Call to undefined function logged_in()

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.

Returning Boolean Value PHP MongoDB

I am trying to implement error proofing to a log in script. But, I cannot get it to work? I have no idea what is going on, or why it doesn't work like I expect it to. I have tried everything, please advise.
This is the method I am calling:
public function i_exist($this_username)
{
//$host_array = null;
//$host_array = $this->collection->findOne(array("Username" => $this_username));
//if ($host_array['Username'] = $this_username)
//{
return true;
//}
//return false;
}
This is how I am calling it:
if (!empty($_POST['Username']))
{
$host = new Host();
$event = new Event();
if ($host->i_exist($_POST['Username']))
{
header("Location: http://www.drink-social.com/error.php?login=duplicate");
}
It is supposed to check the database and see if that username is already in use. But it never directs to the error page? I have even tried commenting everything out and returning true, and returning 1. Nothing?
Any advice?
When you call header(); you will also need to call exit(); otherwise the script continues running.

Categories