Command to upload a file with WinSCP by FTP? - php

I have an FTP server, but don't know the command to upload from a PHP form. I need a command to upload with WinSCP. My code so far is below:
<html>
<body>
<?php
if(isset($_FILES["uploaded"]))
{
print_r($_FILES);
if(move_uploaded_file($_FILES["uploaded"]["tmp_name"],"<root>/domains/sigaindia.com/public_html/reymend/".$_FILES["uploaded"]["name"]))
echo "FILE UPLOADED!";
}
else
{
print "<form enctype='multipart/form-data' action='fup1.php' method='POST'>";
print "File:<input name='uploaded' type='file'/><input type='submit' value='Upload'/>";
print "</form>";
}
?>
</body>
</html>

$host = "ftp.example.com";
$user = "anonymous";
$pass = "";
// You get this from the form, so you don't need to do move_uploaded_file()
$fname = "/public_html/new_file.txt";
$fcont = "content";
function ftp_writeFile($ftp, $new_file, $content, $debug=false) {
extract((array)pathinfo($new_file));
if (!#ftp_chdir($ftp, $dirname)) {
return false;
}
$temp = tmpfile();
fwrite($temp, $fcont);
rewind($temp);
$res = #ftp_fput($ftp, $basename, $temp, FTP_BINARY);
if ($debug) echo "a- '$new_file'".(($res)?'':" [error]")."<br/>";
fclose($temp);
return $res;
}
$ftp = ftp_connect($host);
if (!$ftp) echo "Could not connect to '$host'<br/>";
if ($ftp && #ftp_login($ftp, $username, $password)) {
ftp_writeFile($ftp, $fname, $fcont, true);
} else {
echo "Unable to login as '$username:".str_repeat('*', strlen($password))."'<br/>";
}
ftp_close($ftp);
http://au.php.net/manual/en/book.ftp.php

I have an FTP server, but don't know the command to upload from a PHP form. I need a command to upload with WinSCP. My code so far is below:
If you're talking about PHP and forms than that's HTTP - HTTP is not FTP and vice versa.
WinSCP is an SSH client. SSH is a different protocol from HTTP. SSH is a different protocol from FTP.
If you want your PHP script to transfer files uploaded to the webserver to an FTP server, try something like:
foreach ($_FILES as $f) {
if (file_exists($f['tmp_name'])) {
$dest = 'ftp://' . $username . ':' . $password .
'#' . $ftpserver . $ftp_path;
file_put_contents($f['tmp_name'], $dest);
}
}

Related

Trying to get all content of directory from one server to another using ssh2_scp_recv in php

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

I am not able to trasfer file and folder from one server to another server

Please find the following code. In addition to this I forget to state that I am actually running this script on magento web store but it doesn't matter since I am getting all things okay except file transfer.
<?php
require_once('app/Mage.php');
Mage::app();
$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
$array1=array();
$array2=array();
echo $destination_dir = dirname(__FILE__);
$remote_file = '/B303501/_Datenblatt.pdf';
$ftp_server = "*******";
$ftp_user = "************";
$ftp_pass = "******";
$local_file = '/E212002M';
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
foreach ($products as $product) {
array_push($array1,$product->getData("sku"));
array_push($array2,$product->getData("image"));
}
// try to login
if (#ftp_login($conn_id, $ftp_user, $ftp_pass)) {
//echo "Connected as $ftp_user#$ftp_server";
ftp_pasv($conn_id, true);
if(!#copy('/B303501/_Datenblatt.pdf','/media/catalog/product/demo/'))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
} else {
echo "File copied from remote!";
}
$i = 0;
$contents = ftp_nlist($conn_id, ".");
foreach ($contents as $cont) {
if(in_array($cont,$array1)){
echo $cont. "</br>";
$buff = ftp_rawlist($conn_id, '/'.$cont.'/');
echo "<pre>";
print_r($buff);
echo "</pre>";
$tobecopied = 'http://www.example.com/index.html';
$target = $destination_dir . '/media/catalog/product/demo/';
foreach($buff as $key){
if(!#copy('/'.$cont.'/'.$key,'/media/catalog/product/demo/'))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
} else {
echo "File copied from remote!";
}
}
$i++;
}
}
} else {
echo "Couldn't connect as $ftp_user\n";
}
I am getting following error while file transfer from one server to another server.
I have both live server and I am also get logged-in successfully but can't figure out what's happening while file transfer.
The following is the error.
/var/www/clients/client348/web979/web
COPY ERROR: 2
copy(/B303501/_Datenblatt.pdf): failed to open stream: No such file or directoryB303501
Any help would be highly appreciate.
Let me know if you need any further information regarding above.
Thanks
I think you should use ftp_get not copy. Also make sure that directory hierarchy exists at your destination because either ftp_get nor copy won't create missing directories for you.
I finally sort it out issue. The ftp you I am using is just normal ftp but In order to loggedin into another server you need SFTP credentials except this all above is in working mode.
Thanks for your support

PHP script to upload all files and folders to FTP server

I have a problem and i cant figure it out. I have a folder in local server that i want to upload it via FTP to a remote server. When i run the script in XAMP-apache in Windows i can upload it with no problems the subfloders and all files, now i try to use the same PHP script for the same folder to the same destination from linux apache but i get "file not found, please try again"
Any help will be much appreciated. Thank you!
<?php
ob_start();
set_time_limit(0);
$sourcedir="source_folder"; //this is the folder that you want to upload with all subfolder and files of it.
$ftpserver="192.168.1.150"; //ftp domain name
$ftpusername="user"; //ftp user name
$ftppass="user"; //ftp passowrd
$ftpremotedir="destination_folder"; //ftp main folder
$ftpconnect = ftp_connect($ftpserver);
$ftplogin = ftp_login($ftpconnect, $ftpusername, $ftppass);
if((!$ftpconnect) || (!$ftplogin))
{
echo "cant connect!";
die();
}
function direction($dirname)
{
global $from,$fulldest,$ftpremotedir,$ftpconnect,$ftpremotedir;
chdir($dirname."\\");
$directory = opendir(".");
while($information=readdir($directory))
{
if ($information!='.' and $information!='..' and $information!="Thumbs.db")
{
$readinfo="$dirname\\$information";
$localfil=str_replace("".$from."\\","",$dirname)."";
$localfold="$localfil\\$information";
$ftpreplacer=str_replace(array("\\\\","\\"),array("/","/"),"$ftpremotedir\\".str_replace("".$fulldest."","",$dirname)."\\$information");
if(!is_dir($information))
{
$loading = ftp_put($ftpconnect, $ftpreplacer, $readinfo, FTP_BINARY);
if (!$loading)
{
echo "<font color=red>Files not found... Please try again...</font>"; echo "<br>"; fls();
}
else
{
echo "<font color=green> Please wait... Uploading files</font>"; echo "<br>"; fls();
}
}
else
{
ftp_mkdir($ftpconnect, $ftpreplacer);
direction("$dirname\\$information");
chdir($dirname."\\");
fls();
}
}
}
closedir ($directory);
}
function fls()
{
ob_end_flush();
ob_flush();
flush();
ob_start();
}
$from=getcwd();
$fulldest=$from."\\$sourcedir";
direction($fulldest);
ftp_close($ftpconnect);
echo '<font color=red>Your folder is now ready for use <font color=red>';
?>
>
You've got a lot of backslashes in there. Are you using backslashes as your directory separator? That won't work on Linux. You either have to use / or DIRECTORY_SEPARATOR.

Uploading a file using WebDav protocol from Unix

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);
}

Uploading a File from a Remote Server to an FTP Server with PHP

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");
}
?>

Categories