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);
}
Related
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.
This is my code to send single file from local to SFTP server. Single file successfully send.
I want to send one folder from local to SFTP server , but i dont know how to send one folder. i need help
<?php
$src = 'xxxxxxx';
$filename = 'test.txt';
$dest = 'xxxxxxxx'.$filename;
// set up sftp ssh-sftp connection
$connection = ssh2_connect('xxxxxx', 22);
ssh2_auth_password($connection, 'username', 'password');
// Create SFTP session
$sftp = ssh2_sftp($connection);
$sftpStream = #fopen('ssh2.sftp://'.$sftp.$dest, 'w');
try {
if (!$sftpStream) {
throw new Exception("Could not open remote file: $dest");
}
$data_to_send = #file_get_contents($src);
if ($data_to_send === false) {
throw new Exception("Could not open local file: $src.");
}
if (#fwrite($sftpStream, $data_to_send) === false) {
throw new Exception("Could not send data from file: $src.");
} else {
//Upload was successful, post-upload actions go here...
}
fclose($sftpStream);
} catch (Exception $e) {
error_log('Exception: ' . $e->getMessage());
fclose($sftpStream);
}
?>
ssh2_scp_send in php looks like just support sending file.
maybe these ways work:
1.compress folder, send the compressed file
2.use ssh2 to mkdir, then send each file iteratively
3.try with system() function to excute cmd line order "scp -r folder_path user#host:target_path"
The below script is working successfully.
Getting file from one server to another
if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp',
'/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp')){
echo "\n recevied \n";
}else{
echo "\n not recevied\n";
}
But instead for fetching just a static file, I want to fetch folder with all its content inside.
With above example, the directory I would like to fetch to local server is "15721022890870"
/var/www/html/captures/store/2016/04/HK/15721022890870/
I have tried below code but doesn't work,
The remote server has directory, but the local server doesn't have, so I want to make directory then copy all its content inside
if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/',
'/var/www/html/captures/store/2016/04/HK/')){
echo "\n recevied done \n";
}else{
echo "\n not done \n";
}
<?php
$username = "your_username";
$password = "your_pass";
$url = 'your_stp_server_url';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
?>
This is from server to computer but you can modify the $localDir
On a server with PHP 5.2.17 running, using any function which makes use of the built in ftp wrapper to upload a file, creates an empty file on the server:
file_put_contents() returns with the accurate number of bytes
copy() also returns with true
Both create the file, but it's empty.
When trying with ftp_put() from the FTP extension, both in binary and ascii mode, it works well.
On my workstation with PHP 5.3.10 it somehow works also with the wrapper.
In code:
$source = '/tmp/testfile';
$target = 'ftp://user:pass#example.com/testfile';
copy($source, $target);
gives no error or warning, but leaves an empty file on the server.
$source = '/tmp/testfile';
$target = 'testfile';
$ftp = ftp_connect('example.com');
ftp_login($ftp, 'user', 'pass');
ftp_put($ftp, $target, $source, FTP_ASCII);
ftp_close($ftp);
works in every respect.
thanks for any suggestion!
Have you tried SSH2 libs? Some sample implementation below:
public function uploadSFTP($host_name, $port, $user, $publicSshKeyPath, $privateSshKeyPath, $remoteFile, $localFile, $fileOperation = 'w')
{
$ssh_conn = ssh2_connect($host_name, $port);
if (ssh2_auth_pubkey_file($ssh_conn, $user, $publicSshKeyPath, $privateSshKeyPath))
{
$sftp_conn = ssh2_sftp($ssh_conn);
$inputfileStream = #fopen('ssh2.sftp://' . $sftp_conn . $remoteFile, $fileOperation);
try
{
if (!$inputfileStream)
throw new Exception('Could open remote file for writing: ' . $remoteFile);
$localFileContents = #file_get_contents($localFile);
if ($localFileContents === FALSE)
throw new Exception('Could not open local file for reading :' . $localFile);
if (#fwrite($inputfileStream, $localFileContents) === FALSE)
throw new Exception('Could not SFTP file');
}
catch (Exception $e)
{
// Do something...
}
fclose($sftpInfileStream);
}
}
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");
}
?>