SFTP Opendir failing when called via Function - php

I have a bunch of php pages that are running on a schedule that pull data from different SFTP sources, to try and minimise this as a temporary fix I am turning them into functions and having one page that calls each of them
However, when converting these to functions the pages are giving me error 500, through process of elimination I have found that it is when it using the opendir function via sftp
I have called the function page by itself with a reference to call itself as a test and it connects fine, but when called from another page it errors out.
The variables being used to open the directory via sftp are generated on the 'required' page so it's not losing anything via session variables
If I point it to an incorrect directory it is being caught by the error handling in place, but when it 'successfully' connects I get the error 500
Page1.php
<?php
require 'Page2.php';
sftpFunc();
?>
Page2.php
<?php
Function sftpFunc()
{
/* variable declarations and value assignments go here*/
if (!$FTP_CONN = ssh2_connect($FTP_HOST, $FTP_PORT))
die('Unable to connect');
if (!ssh2_auth_password($FTP_CONN, $FTP_USER, $FTP_PASS))
die('Unable to authenticate.');
if (!$FTP_STRE = ssh2_sftp($FTP_CONN))
die('Unable to create a stream.');
if (!$FTP_OPEN = opendir("ssh2.sftp://{$FTP_STRE}{$FTP_DIRI}"))
die('Could not open the directory');
}
?>

Updated the php version on the site from 7.2.34 to 7.3.11 and it seems to have done the trick, hadn't seen any version specific issues with opendir() before and it seemed to only happen when using it through a function on a different page.
Not sure on the why, but at least this worked.

Related

PHP 7 - SFTP keeps interrupting page to load

I'm currently trying to get a file from a server by php sftp. I managed to authenticate and connect to the server. The problem is, that if I want to open a dir on said server, the page just keeps loading until my browser tells me the loading of the page has been interrupted. This only happens, if I try open a dir that EXISTS. If I open a dir that doesn't exist, I get a normal error message.
Therefor I'm not quite sure, wether this is a mistake in my code or a problem with the ftp server.
My Code:
ini_set("display_errors", "1");
$host = "<host>";
$port = 22;
$conn = ssh2_connect($host);
$username = "<user>";
$pub_key = "/home/<user>/.ssh/id_rsa.pub";
$pri_key = "/home/<user>/.ssh/id_rsa";
if (ssh2_auth_pubkey_file(
$conn,
$username,
$pub_key,
$pri_key
)) {
if(!$sftp = ssh2_sftp($conn)){
die("SFTP Connection failed");
};
opendir("ssh2.sftp://".intval($sftp)."/./");
};
Has anyone ever experienced something similar?
I'd be glad for any help :)
~François
It is the expected way.
Opendir return a handle. Your function is working, it's just that you do nothing with the data, and your php script do nothing. It's just waiting with the information
Just handle data, or at least write an echo and it should be ok.
check the manual, there is a working example http://php.net/manual/en/function.opendir.php

Including the same file over many pages

I am writing a simple app for a school project that is not too big. I have the following files:
signup.php
login.php
view_photos.php
that have the following in common: they connect to a database and execute queries. In every file I find myself repeating the your typical database connection code snippet:
$mysql = new mysqli( 'localhost', 'root', '', 'imagebox');
if( $mysql->connect_errno ) {
echo "Connection failure: " . $mysqli->connect_error;
exit();
}
Is there a way to do this once in the index.php file and pass the connection to other pages without having to repeat the same line in every page that requires a database connection?
Use PHP's include feature, though I recommend using require instead (as require aborts script execution if the file doesn't exist).
Documentation is here: http://php.net/manual/en/function.require.php
Use require_once to prevent duplicate inclusion if you have cycles in your include-dependency tree.
Place your common code in a separate file. Then use
include('myfile.php');
where you want the common code to appear

is mysql_connect in header bad practice?

I have a normal website. It uses PHP to call a MySQL table. To save on typing it out all the time, I include() a connect.php file which connects to the database for me on every page. The website keeps getting a "mysql too many connections" error. Is it a bad idea to connect at the start of a page like this?
Should I create a new connection each time a PHP script needs it, then close that connection with mysql_close after that script is done? I had avoided doing as it would add repeated lines of code to the website but I'm wondering if that's what's causing the issue?
So at the moment my code is similar to this:
<?php
include("connect.php"); //connects to database using mysql_connect() function
...
PHP script that calls mysql
...
another PHP script that calls mysql
?>
Should I change it to something like this?
<?php
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
PHP code that calls mysql
mysql_close();
...
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
more PHP code that calls mysql
mysql_close();
?>
You should avoid making new connections to your database, as long as possible.
Making connection to database is a slow and expensive process. Having an opened connection consume few resources.
By the way, stop using mysql_* functions. Use mysqli_* or PDO.
Should I create a new connection each time a PHP script needs it [...] ?
Yes, that makes most sense, especially if not every page needs a mysql connection.
In PHP this works by setting up the database credentials in the php.ini file and you can just call mysql_select_db and it will automatically connect to the configured database if no connection exists so far.
If you write new code, encapsulate the database connection in an object of it's own so that you can more fine-grained control when to connect to the database.
Modern frameworks like for example Silex allow you to lazy load such central components (Services), so you have configured them and can make use of them when you need them but you don't need to worry about the resources (like the connection limit in your example).
[...] close that connection with mysql_close after that script is done?
You don't need that normally because PHP does this for you.
I do not think there is anything really wrong with this style of coding. It all depends on what kind of app you are writing. Just make sure you check your scripts well and get ride of any errors, you should be fine.
This is what i usually do
<?php session_start(); include "inc/config.php";
//require_once('chartz/lib/idiorm.php');
if ($_SESSION["login1"]== "Superadmin" or $_SESSION["login1"]== "User" or $_SESSION["login1"]=="Administrator")
{
$snames = $_SESSION["name1"];
$id = $_SESSION["id1"];
$stype = $_SESSION["login1"];
$stokperm = $_SESSION['stokperm'];
$navtype = $_GET['nav'];
include("inc/ps_pagination.php");
}
else
{
header ("location: ../../../index.php");
}
?>
Am not saying its the very best way out there, we are all still learnig...
I also thing you should take the advice of blue112 very seriously. Most of my apps are writing in the old fashion way, but Use mysqli_* or PDO is the way to go.

Using same MySQL Connection in different PHP pages

I am creating a simple Web Application in PHP for my college project. I am using the MySQL database.
I connect to the database in login.php. After connection I assign the connection to $_SESSION["conn"] and then redirect to main.php.
In main.php I write $conn = $_SESSION["conn"]. But the connection in $conn does not work.
I thought that as the login.php script ends, the connection gets closed. So I tried using mysql_pconnect instead of mysql_connect but that too does not work.
I know I can reconnect to the database in every PHP file. But I don't want to do this. I want to use the same connection in all PHP files.
Instead of saving the DB connection in a session you should make the connection calls in a separate file such as db.php and then require it from each of your scripts. For example, place your connection in db.php:
mysql_connect('...', '...', '...');
mysql_select_db('...');
and then bring it in in login.php:
require('db.php');
$res = mysql_query('...');
You can then do the same for each PHP file that needs access to the DB and you'll only ever have to change your DB access credentials in one file.
After connection I assign the connection to $_SESSION["conn"] and then redirect to main.php.
You'll probably want to read up on PHP sessions. You can't store resources (database connections, file handles, etc) in a session, because they can not be serialized and stored.
Keep in mind that each and every visit to a PHP script invokes a new instance of the PHP interpreter (via CGI, via FastCGI, or via a built-in module), and invokes a new instance of the script. Nothing is shared between script calls, because the entire environment goes away when the script exits.
The other answers are correct -- you'll need to connect to the database on every script call. Place the connection in a common include file for convenience.
The second request may not be served by the same web server process as the first, which means that you will have a completely separate set of database resources. You'll need to connect again in this new process in order to run queries.
What I normally have is a Connection class that pages will require in order to establish a connection. Something along the lines of:
class Connection {
public $dbConnection = null;
public $isConnectionActive = false;
private $dbServer = null;
private $dbCatalog = null;
private $dbUser = null;
private $dbPassword = null;
}
This class handles opening and closing of the connection on any pages.
It sounds that you want to make your php connections persistants , in that way and if it is so , then you have to create a PDO Object with the required parameters to create a new PHP PDO Object that will attempt to connect to mysql , and in the object instanciation , try to pass persistancy option value to true , you may have available in every php scripts the same PDO Connection Objetc but you will end up to face issues with that way ... but it is not reconmmanded as PHP Programming Best Pratices ... the best way to do so is to include a connection file for every script in your project. Read PHP Documentation for Persistant Connections in order to learn more about Issues found for these Connection Objets especially for recent php versions. PHP Announced that Persistant Connections are on the way to be dropped from futur version as it may increase server workload with persistant ressources ... Sorry if it is too late

Understanding PHP's database connection variable

How can you have only one declaration of the database connection variable, $dbconn?
My login script is based on the following procedure
If the user is not authenticated, he is thrown back to the login page
If the user is authenticated, he gets an $_SESSION["logged_in"] = true;
Then when the user is browsing the main page or other pages that need auth, they just check if the $_SESSION["auth"] is set.
I have the database variable only at the beginning of my index.php:
$dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123");
I do not the connection by db_close() anywhere in my codes.
I source my login script to index.php which uses my database.
However, I get the standard warnings of not getting access to db when I do not have the variable declaration also in my scripts. If I add the declaration to each of my scripts, I get an access to db.
We need to first understand how PHP is running the show here before we can delve into the wide, wide world of database connections.
Each PHP page request fires off a new PHP script. While you may have sessions turned on, that's an internal PHP construct only. The database sees this as a new connection/process connecting to the server. Therefore, it creates a new process on the database for it, so long as you call your pg_connect code. Otherwise, Postgres has no idea who you are or what session you want to use. Moreover, once the parent process dies, it generally kills the Postgres session (in this case, the PHP script runs and then dies once it's finished). Sometimes these can leave zombies roaming the streets of Postgres, but by and large, it'll just kill them.
If you want to use SQL code in your PHP script, you must connect to the database in that script before making a call to Postgres.
If i remember your other question you're redirecting to login.php? Which means that no the dbconn variable will not exist because it was initialised on another page.
if you required login.php from index.php it would work
$dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123");
require_once('login.php');

Categories