Been trying to connect Filezilla and my website together via PHP and SFTP is proving to be tedious.
How do you connect with STFP, the information online is very brief for the most part, I have downloaded the SSH2.php file and have used the code that is included in the file (the Test File) and it does not work. The page does not load, an error message is displayed due to the use of the SSH2 functions I suspect.
Connection
// Connect to FileZilla
include("../model/connection.php");
$con = new SFTPobj();
$connect = $con->serverConnection();
Test File:
Class SFTPobj{
function serverConnection()
{
include('../controller/SSH2.php');
$server = "xx";
$user = "xx";
$pass = "xx";
$ssh = new Net_SSH2($server);
if (!$ssh->login( $user, $pass)) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
}
}
Test File- * code (irrelavant for the most part):
<?php
// Connect to database
include("../model/connection.php");
$con = new SFTPobj();
$connect = $con->serverConnection();
if(isset($_POST['submit']))
{
$file = $_FILES['file'];
print_r($file);
$fileName=$_FILES['file']['name'];
$fileTmpName=$_FILES['file']['tmp_name'];
$fileSize=$_FILES['file']['size'];
$fileError=$_FILES['file']['error'];
$fileType=$_FILES['file']['type'];
#only allow images
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
#Image types
$allowed = array('jpg','jpeg', 'png');
#Check file type
if(in_array($fileActualExt,$allowed))
{
if($fileError === 0)
{
if($fileSize < 500000) #500KB
{
$fileNameNew = uniqid('', true).".".$fileActualExt; #Random Number Generate
$fileDestination = '../view/pictures/week1'.$fileNameNew;
move_uploaded_file($fileTmpName,$fileDestination);
header("Location:../view/test.php?uploadSuccess");
}else{
echo "Your file is too big";
}
}else{
echo "There was an error uploading your file";
}
}else{
echo "You can not upload files of this type";
}
}
?>
From your file:
include('../controller/SSH2.php');
In the zip file download SSH2.php is in the Net/ directory. There's also a Crypt/ directory and a Math/ directory. Both of those are needed and the relative path's need to be correct as well.
The fact that you've taken SSH2.php out of the Net/ directory makes me think you may not have the other requisite files. And even if you do I'm skeptical that they're in the right relative location.
Also, since you appear to be using the 1.0 branch, you may need to set the include_path to get it to work properly, depending on where you place the directory:
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include('Net/SSH2.php');
?>
Really, I'd just recommend against picking and choosing the files you think you need. Just take the entire phpseclib zip file and dump it into the phpseclib file.
Related
I am working on my school project which we use Winscp as a server.
So im new to php trying to work on image upload and I have read many articles saying I need to edit my php.ini file and set file_uploads directive to "on". But I just do not know where my php.ini file is at.
Here is my link to my phpinfo.php: http://cgi.sice.indiana.edu/~baehy/phpinfo.php
So it says my php.ini is at /etc/php.ini and I cannot find it on my computer(i know it may sound silly)
Every comment is appreciated! Thank you all in advance!
Here is my code
<?php
session_start();
include('database.php');
ini_set('max_exection_time', 60);
if(!isset($_SESSION['userid'])){
header('location: http://cgi.sice.indiana.edu/~baehy/team72index.php');
} else {
echo "Welcome " . $_SESSION['userid'] . "<br>";
if(isset($_POST['submit'])){
$title = $_POST['title'];
$category = $_POST['category'];
$description = $_POST['description'];
//get file from the form and get following information
$file = $_FILES['coverimage'];
$fileName = $_FILES['coverimage']['name'];
$fileTmpName = $_FILES['coverimage']['tmp_name'];
$fileSize = $_FILES['coverimage']['size'];
$fileError = $_FILES['coverimage']['error'];
$fileType = $_FILES['coverimage']['type'];
//retrieve file extention using explode()
$fileExt = explode('.', $fileName);
//because some file extentions might be in capital letters
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png');
if(in_array($fileActualExt, $allowed)){
if($fileError === 0){
//if the size of the file is lesser than 1M kb = 1000mb
if($fileSize < 1000000){
$fileNameNew = uniqid('',true).".".$fileActualExt;
chmod('uploads/',0777);
echo "permission granted to uploads directory!" . "<br>";
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
echo $fileNameNew . "<br>";
echo "Successfully uploaded your file" . "<br>";
} else {
echo "Your file is too big to upload" . "<br>";
}
} else {
echo "There was an error uploading your file" . "<br>";
}
} else {
echo "This file extention is not allowed to be uploaded" . "<br>";
}
$sql = "INSERT INTO `recipe` (title, category, description, coverimage, userid)
VALUES ('".$title."', '".$category."', '".$description."', '".$fileName."', '".$_SESSION['userid']."')";
$result = mysqli_query($conn, $sql);
if($result){
echo "successfully added to database";
} else {
echo "failed to add to database";
}
$showImage = mysqli_query($conn, "SELECT `coverimage` FROM `recipe`");
}
}
p.s. and also do I need to put the absolute path of the folder('uploads') to use it in the code? Thank you!
Php.ini is system file located at remote web server and it contains global configuration for PHP. Only privileged users can edit php.ini.
You can change local configuration for your script using function ini_set, for example:
ini_set('max_exection_time', 60);
According to phpinfo() you sent, you already have file_uploads set to On. So you don't need to edit anything. Just open link you sent, press CTRL+F and search for file_uploads.
By the way, WinSCP is only application used to transfer files to remote web server using FTP/SFTP or similar protocols. Actually your web server is running on RHEL Apache 2.4.6. Just see section SERVER_SOFTWARE in your phpinfo.
Using WinSCP, connect to remote server. Go to remote server's root directory and then go to /etc/php.ini.
It won't be on your computer, it's on the remote server. The server is running on Apache. You are using Winscp as a FTP software to access the files of remote server.
Learn how to use WinSCP - https://www.siteground.com/tutorials/ssh/winscp/
I am uploading files to a server using php and while the move_uploaded_file function returns no errors, the file is not in the destination folder. As you can see I am using the exact path from root, and the files being uploaded are lower than the max size.
$target = "/data/array1/users/ultimate/public_html/Uploads/2010/";
//Write the info to the bioHold xml file.
$xml = new DOMDocument();
$xml->load('bioHold.xml');
$xml->formatOutput = true;
$root = $xml->firstChild;
$player = $xml->createElement("player");
$image = $xml->createElement("image");
$image->setAttribute("loc", $target.basename($_FILES['image']['name']));
$player->appendChild($image);
$name = $xml->createElement("name", $_POST['name']);
$player->appendChild($name);
$number = $xml->createElement("number", $_POST['number']);
$player->appendChild($number);
$ghettoYear = $xml->createElement("ghettoYear", $_POST['ghetto']);
$player->appendChild($ghettoYear);
$schoolYear = $xml->createElement("schoolYear", $_POST['school']);
$player->appendChild($schoolYear);
$bio = $xml->createElement("bio", $_POST['bio']);
$player->appendChild($bio);
$root->appendChild($player);
$xml->save("bioHold.xml");
//Save the image to the server.
$target = $target.basename($_FILES['image']['name']);
if(is_uploaded_file($_FILES['image']['tmp_name']))
echo 'It is a file <br />';
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
else {
echo $_FILES['image']['error']."<br />";
echo $target;
}
Any help is appreciated.
Eric R.
Most like this is a permissions issue. I'm going to assume you don't have any kind of direct shell access to check this stuff directly, so here's how to do it from within the script:
Check if the $target directory exists:
$target = '/data/etc....';
if (!is_dir($target)) {
die("Directory $target is not a directory");
}
Check if it's writeable:
if (!is_writable($target)) {
die("Directory $target is not writeable");
}
Check if the full target filename exists/is writable - maybe it exists but can't be overwritten:
$target = $target . basename($_FILES['image']['name']);
if (!is_writeable($target)) {
die("File $target isn't writeable");
}
Beyond that:
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
Echoing out the error parameter here is of no use, it refers purely to the upload process. If the file was uploaded correctly, but could not be moved, this will still only echo out a 0 (e.g. the UPLOAD_ERR_OK constant). The proper way of checking for errors goes something like this:
if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
// file was properly uploaded
if (!is_uploaded_File(...)) {
die("Something done goofed - not uploaded file");
}
if (!move_uploaded_file(...)) {
echo "Couldn't move file, possible diagnostic information:"
print_r(error_get_last());
die();
}
} else {
die("Upload failed with error {$_FILES['images']['error']}");
}
You need to make sure that whoever is hosting your pages has the settings configured to allow you to upload and move files. Most will disable these functions as it's a sercurity risk.
Just email them and ask whether they are enabled.
Hope this helps.
your calls to is_uploaded_file and move_uploaded_file vary. for is_uploaded_file you are checking the 'name' and for move_uploaded_file you are passing in 'tmp_name'. try changing your call to move_uploaded_file to use 'name'
How can I check if a specific file exists on a remote server using PHP via FTP connections?
Some suggestions:
Use ftp_size, which returns -1 if it doesn't exist: http://www.php.net/manual/en/function.ftp-size.php
Use fopen, e.g. fopen("ftp://user:password#example.com/somefile.txt", "r")
Use ftp_nlist, check to see if the filename you want is in the list: http://www.php.net/manual/en/function.ftp-nlist.php
I used this, a bit easier:
// the server you wish to connect to - you can also use the server ip ex. 107.23.17.20
$ftp_server = "ftp.example.com";
// set up a connection to the server we chose or die and show an error
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
ftp_login($conn_id,"ftpserver_username","ftpserver_password");
// check if a file exist
$path = "/SERVER_FOLDER/"; //the path where the file is located
$file = "file.html"; //the file you are looking for
$check_file_exist = $path.$file; //combine string for easy use
$contents_on_server = ftp_nlist($conn_id, $path); //Returns an array of filenames from the specified directory on success or FALSE on error.
// Test if file is in the ftp_nlist array
if (in_array($check_file_exist, $contents_on_server))
{
echo "<br>";
echo "I found ".$check_file_exist." in directory : ".$path;
}
else
{
echo "<br>";
echo $check_file_exist." not found in directory : ".$path;
};
// output $contents_on_server, shows all the files it found, helps for debugging, you can use print_r() as well
var_dump($contents_on_server);
// remember to always close your ftp connection
ftp_close($conn_id);
Functions used: (thanks to middaparka)
Login using ftp_connect
Get the remote file list via ftp_nlist
Use in_array to see if the file was present in the array
Just check the size of a file. If the size is -1, it doesn't exist, so:
$file_size = ftp_size($ftp_connection, "example.txt");
if ($file_size != -1) {
echo "File exists";
} else {
echo "File does not exist";
}
If the size is 0, the file does exist, it's just 0 bytes.
Source
A general solution would be to:
Login using ftp_connect
Navigate to the relevant directory via ftp_chdir
Get the remote file list via ftp_nlist or ftp_rawlist
Use in_array to see if the file was present in the array returned by ftp_rawlist
That said, you could potentially simply use file_exists if you have the relevant URL wrappers available. (See the PHP FTP and FTPS protocols and wrappers manual page for more information.)
This is an optimization of #JohanPretorius solution, and an answer for comments about "slow and inefficient for large dirs" of #Andrew and other: if you need more than one "file_exist checking", this function is a optimal solution.
ftp_file_exists() caching last folder
function ftp_file_exists(
$file, // the file that you looking for
$path = "SERVER_FOLDER", // the remote folder where it is
$ftp_server = "ftp.example.com", //Server to connect to
$ftp_user = "ftpserver_username", //Server username
$ftp_pwd = "ftpserver_password", //Server password
$useCache = 1 // ALERT: do not $useCache when changing the remote folder $path.
){
static $cache_ftp_nlist = array();
static $cache_signature = '';
$new_signature = "$ftp_server/$path";
if(!$useCache || $new_signature!=$cache_signature)
{
$useCache = 0;
//$new_signature = $cache_signature;
$cache_signature = $new_signature;
// setup the connection
$conn_id = ftp_connect($ftp_server) or die("Error connecting $ftp_server");
$ftp_login = ftp_login($conn_id, $ftp_user, $ftp_pwd);
$cache_ftp_nlist = ftp_nlist($conn_id, $path);
if ($cache_ftp_nlist===FALSE)die("erro no ftp_nlist");
}
//$check_file_exist = "$path/$file";
$check_file_exist = "$file";
if(in_array($check_file_exist, $cache_ftp_nlist))
{
echo "Found: ".$check_file_exist." in folder: ".$path;
}
else
{
echo "Not Found: ".$check_file_exist." in folder: ".$path;
};
// use for debuging: var_dump($cache_ftp_nlist);
if(!$useCache) ftp_close($conn_id);
} //function end
//Output messages
echo ftp_file_exists("file1-to-find.ext"); // do FTP
echo ftp_file_exists("file2-to-find.ext"); // using cache
echo ftp_file_exists("file3-to-find.ext"); // using cache
echo ftp_file_exists("file-to-find.ext","OTHER_FOLDER"); // do FTP
You can use ftp_nlist to list all the files on the remote server. Then you should search into the result array to check if the file what you was looking for exists.
http://www.php.net/manual/en/function.ftp-nlist.php
The code has been written by: #Drmzindec should be change a little:
if (in_array($check_file_exist, $contents_on_server))
to
if (in_array($file, $contents_on_server))
I need to transfer a file from my Unix machine to a Windows machine. Problem is i can transfer a file already created on my machine via ftp from unix to any machine. also i can open webdav connection create new file and save it there.
What i am unable to do is to write my code to upload my file fro my local location using webdav.
i tried using pear client but due to lack of documentation, i am still not able to achieve the task .
Here is my attempt:
include("/usr/share/pear/HTTP/WebDAV/Client.php");
global $filename, $logger;
try {
/* $client = new HTTP_WebDAV_Client();
$user="username";
$pass = "pwd";
$dir = "webdavs://".$user.":".$pass."#hostname/";
var_dump($client->stream_open($dir."test4.txt","w",null,$path));
$client->stream_write("HELLO WORLD! , I am great ");
$client->stream_close();
$client->dir_opendir($dir,array());
var_dump($client->dirfiles);
$req =new HTTP_Request($dir);
$req->setBasicAuth($user, $pass);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$result = $req->addFile('file_upload_field', $filename);
if (PEAR::isError($result)) {
echo $result->getMessage();
} else {
$response = $req->sendRequest();
if (PEAR::isError($response)) {
echo $response->getMessage();
} else {
echo $req->getResponseBody();
}
}*/
$ftp_server = "hostname-ftp";
//$ftp_server = "hostname-webdav";
$connection = ftp_connect($ftp_server);
ftp_login($connection, 'user', 'pwd);
ftp_put($connection, $filename, $filename, FTP_BINARY);
unlink($filename);
} catch(Exception $e){
$message = "There was a problem while uploading" . $filename;
$logger->error($message);
}
It was a togh call, but i figured it out. I am adding my code snippet so it may be helpful for someone. Instead of uploading the file, i converted that file into data stream and then copied that data stream to my call that writes stream on webdav server.
try {
$filecsv = file_get_contents($filename);
$client = new HTTP_WebDAV_Client_Stream();
$user="user";
$pass = "pass";
$dir = "webdavs://".$user.":".$pass."#hostname/";
$client->stream_open($dir."db_user_exports.csv","w",null,$path);
$client->stream_write($filecsv);
$client->stream_close();
unlink($filename);
} catch(Exception $e){
$message = "There was a problem while uploading" . $filename;
$logger->error($message);
}
How can I upload a remote file from a link for example, http://site.com/file.zip to an FTP server using PHP? I want to upload 'Vanilla Forum Software' to the server and my mobile data carrier charges high prices, so if I could upload the file w/o having to upload it from my mobile I could save money and get the job done too.
Made you this function:
function downloadfile($file, $path) {
if(isset($file) && isset($path)) {
$fc = implode('', file($file));
$fp = explode('/', $file);
$fn = $fp[count($fp) - 1];
if(file_exists($path . $fn)) {
$Files = fopen($path . $fn, 'w');
} else {
$Files = fopen($path . $fn, 'x+');
}
$Writes = fwrite($Files, $fc);
if ($Writes != 0){
echo 'Saved at ' . $path . $fn . '.';
fclose($Files);
}
else{
echo 'Error.';
}
}
}
You may use it like this:
downloadfile("http://www.webforless.dk/logo.png","folder/");
Hope it works well, remember to Chmod the destination folder 777.
((If you need it to upload to yet another FTP server, you could use one of the FTP scripts posted in the other comments))
Best regards. Jonas
Something like this
$con=ftp_connect("ftp.yourdomain.com");
$login_result = ftp_login($con, "username", "password");
// check connection
if ($conn_id && $login_result) {
// Upload
$upload = ftp_put($con, 'public_html/'.$name, "LOCAL PATH", FTP_BINARY);
if ($upload) {
// UPLOAD SUCCESS
}
}
More info: http://php.net/manual/en/function.ftp-put.php
A ) download the file via an url :
$destination = fopen("tmp/myfile.ext","w");
//Myfile.ext is an example you should probably define the filename with the url.
$source = fopen($url,"r");
while (!feof($source)) {
fwrite($destination,fread($source, 8192));
}
fclose($source);
fclose($destination);
B) Upload the file on FTP :
$file = 'tmp/myfile.ext';
$fp = fopen($file, 'r');
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
echo "UPLOAD OK";
} else {
echo "ERROR";
}
ftp_close($conn_id);
fclose($fp);
This just a quick example , there is probably lot of improvement which can be done on this code , but the main idea is here.
Note : if you have a dedicated server it's probably faster and easier to download the file with a call to wget.
More info on FTP can be found in the doc
Simply:
copy('ftp://user:pass#from.com/file.txt', 'ftp://user:pass#dest.com/file.txt');
The PHP server will consume bandwidth upload and download simultaneously.
Create a php script in a web-accessible folder on your target server, change the values of $remotefile and $localfile, point your browser to the script url and the file will be pulled.
<?php
$remotefile="http://sourceserver.com/myarchive.zip";
$localfile="imported_archive.zip";
if(!copy($remotefile, $localfile)) {
echo("Transfer Failed: $remotefile to $localfile");
}
?>