I am attempting to transfer a zip file via ftp from one server to mine, so that I can use the data in the file to update my database table. Here is my ftp.php file:
<?php
header('Content-type: text/html; charset=utf-8');
$date = "2013-05-21-11-19-40";
$ftp_server="ftp.server.com";
$ftp_user_name="BookCellar";
$ftp_user_pass="*****";
$file = "/reports/other/compreport_abebooks_" .$date. ".zip";//tobe uploaded
$remote_file = "/chroot/home/bookcellaronline.com/html/testbcos/accounting/compreport_abebooks_" .$date. ".zip";
?>
and my ftpUpload.php file is:
<?php
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file));
header('Content-Type: application/zip');
require_once('ftp.php');
// set up basic connection
$conn_id = ftp_ssl_connect($ftp_server);//ftp_connect
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((! $conn_id ) || (! $login_result )) {
echo "FTP connection has failed!" ;
exit;
} else {
echo "Connected for user $ftp_user_name" ;
}
ftp_chdir($conn_id, '/home/bookcell/bookcellaronline.com/html/testbcos/accounting/');
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
echo "successfully uploaded $file\n";
exit;
} else {
echo "There was a problem while uploading $file\n";
exit;
}
echo $php_errormsg;
// close the connection
ftp_close($conn_id);
?>
When I run these I get the error messge:
[<a href='function.ftp-put'>function.ftp-put</a>]: failed to open stream: No such file or directory in /chroot/home/bookcell/bookcellaronline.com/html/testbcos/accounting/ftpUpload.php on line 25
Line 25 is:
if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
I have researched a bunch of other posts on SO and have not found a solution. My connection works, but I can't get the file to transfer.
How do I (if even possible) get this to transfer to my server?
EDIT: Am I missing the fact that I need to connect not only to their server($file) AND my server ($remote_file)????
You can't put a path to the destination file
$remote_file = "/chroot/home/bookcellaronline.com/html/testbcos/accounting/compreport_abebooks_" .$date. ".zip";
e.g. - this doesn't work
ftp_put($conn, '/www/site/file.html','c:/wamp/www/site/file.html',FTP_BINARY);
you have to put
<?php
ftp_chdir($conn, '/www/site/');
ftp_put($conn,'file.html', 'c:/wamp/www/site/file.html', FTP_BINARY );
A FTP server hides his absolute path /home/bookcell/bookcellaronline.com/html/
All folders must be relative to the root
ftp_chdir($conn_id, '/testbcos/accounting/');
test the result of ftp_chdir ! Are your in the right directory ?
echo ftp_pwd($conn_id);
Try to connect to the FTP server via a browser.
ftp://BookCellar#ftp.server.com
What you get is / the root. Folders and files that you see in the browser, are below the root directory.
Update : A working out of the box example.
the $password = line must be replaced with Download pass
ftp.php
<?php
$password = "????";
$resource = ftp_connect('ftp.strato.com');
$login = ftp_login($resource, 'ftp_mx_all#moskito-x.de', $password);
$list = ftp_rawlist($resource, '/');
print_r($list);
?>
You will get with print_r
Array ( [0] => drwxr-xr-x 2 ftp ftp 4096 May 23 20:15 aFolder [1] => -rw-r--r-- 1 ftp ftp 167 May 23 20:25 tutorial.txt )
we can see there is a folder aFolder and a file tutorial.txt.
We are interest what files are in the folder aFolder ?
So replace the $list = with
$list = ftp_rawlist($resource, '/aFolder');
and run the php script again. The output :
Array ( [0] => drwxr-xr-x 3 ftp ftp 4096 May 23 19:24 .. [1] => -rw-r--r-- 1 ftp ftp 167 May 23 20:25 tutorial.txt [2] => -rw-r--r-- 1 ftp ftp 271 May 23 21:16 tutorial.zip )
Now we want to download aFolder/tutorial.txt .
Add following below print_r($list); .
echo "<br />\n";
$local_file = "tmp.txt" ;
$file = ftp_get($resource, $local_file, '/aFolder/tutorial.txt',FTP_ASCII);
if ($file) {
echo "$local_file has been successfully written\n";
} else {
echo "An error has occurred\n";
}
The Output :
The folder where the php script is has changed.
now there is a new file tmp.txt !
If you bring this little script to run. We can go further.
From our chat :
Your server does not allow a ftp call to a url.
look allow_url_fopen = ON
echo ini_get('allow_url_fopen');
if (!ini_get('allow_url_fopen')) {
ini_set('allow_url_fopen', 1);
}
echo ini_get('allow_url_fopen');
Then try it again.
set_time_limit(0);
exec("wget --continue http://example.com/site.zip");
exit;
In the first excerpt change the remote tile to be
`$remote_file = "compreport_abebooks_" .$date. ".zip";`
prior to the put you are changing into the directory.
Also note that the directory that you reference in the ftp_chdir call differs from the one in the $remote_file referenced at the top.
/home/bookcell/bookcellaronline.com/html/testbcos/accounting/
vs
/chroot/home/bookcellaronline.com/html/testbcos/accounting/
Related
I am working on to upload the file to FTP using PHP FTP. while putting the file to the server, its throw error.
what I did:
$ftp_conn = ftp_connect(SAP_SERVER_HOST, SAP_SERVER_PORT, 60);
if (!ftp_login($ftp_conn, SAP_SERVER_USER, SAP_SERVER_PASSWORD)) {
echo 'not connected<br/>';
} else {
$localfile = '/abc/txt/15375127769260.txt';
$serverfile = '/folder/15375127769260.txt';
// echo ftp_pwd($ftp_conn);
if (ftp_put($ftp_conn, $serverfile, $localfile, FTP_BINARY)) {
echo "Successfully uploaded $localfile.";
} else {
echo "Error uploading $localfile.";
}
// close connection
ftp_close($ftp_conn);
}
Suggest Me, what I miss in this code.
For anyone stumbling upon this:
my file was sent correctly after adding ftp_pasv($conn_id, true);
Note that it must be added after ftp_login().
ftp-pasv on php.net
are you using right folders and ports ?
$ftp_conn = ftp_connect(SAP_SERVER_HOST, SAP_SERVER_PORT, 60);
it should be port 21
and in local file you must get get the realpath of the file whit realpath() function
and for remote server the path is based on ftp base folder
Take a look of realpath http://php.net/manual/pt_BR/function.realpath.php
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 can connect to a server using an FTP client and move files up and down with no issue. When I try with ftp_put it fails to upload the files. I am opening a directory on server 1 and reading the files and removing anything with any . listing, as the files are read i am displaying the files on screen to see that they are listed and then trying to upload them using ftp_put to server 2 but they are failing to upload. Can anyone see why this does not work please. The permissions on the folder on server 2 are set correctly and i am connected and have tried using pasv mode.
$conn_id = ftp_connect($ftp_server,$port);
$login_result = ftp_login( $conn_id, $ftp_user_name, $ftp_user_pass );
if (!$conn_id) {
echo 'Failed to connect';
} else {
if (!$login_result) {
echo 'Failed to log in';
} else {
ftp_pasv($conn_id, true);
$path='this/path';
$dir_handle = opendir($path) or die("Error opening $path");
while ($file = readdir($dir_handle)) {
if (substr($file,0,1)=='.') {
} else {
$upload = ftp_put($conn_id, 'Testdir/FilesInThisDir/'.$file, $file, FTP_ASCII);
print (!$upload) ? 'Cannot upload '.$file : 'Upload complete';
print "<br>";
}
}
}
}
ftp_close($conn_id);
The answer turned out to be simple really. The guy did not give me the absolute path to work with :)
I have written Following code to connect to FTP, which gives me an error "Warning: preg_match() [function.preg-match]: Unknown modifier 'p'"
<?php
// define some variables
$ftp_server="www.abc.com";
$ftp_user_name="username";
$ftp_user_pass="password";
$local_file = 'L021-D8127-BLUEWASH-2T.jpg';
$server_file = '/abc/photos/L021-D8127-BLUEWASH-2T.jpg';
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
//
//Enable PASV ( Note: must be done after ftp_login() )
//
$mode = ftp_pasv($conn_id, TRUE);
// get contents of the current directory
$contents = ftp_nlist($conn_id, "abc/photos");
// output $contents
//var_dump($contents);
foreach($contents as $file){
if(!preg_match("/L021-D8127-BLUEWASH-([1-9]|10)(T|S)\.jpg/i", $file)){
// continute if its not the file I want to download
continute;
}
// try to download file and save to $local_file
if (ftp_get($conn_id, $local_file, file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
}
else {
echo "There was a problem\n";
}
}
// close the connection
ftp_close($conn_id);
?>
On the server in "photos" folder i have multiple instances of same image but with different name sequence like
L021-D8127-BLUEWASH-2T.jpg
L021-D8127-BLUEWASH-3T.jpg
L021-D8127-BLUEWASH-4T.jpg
and so on till 10T.jpg
And similarly ...
L021-D8127-BLUEWASH-2S.jpg
L021-D8127-BLUEWASH-3S.jpg
L021-D8127-BLUEWASH-4S.jpg
and so on till 10S.jpg
My Question is with one single FTP connection open how do i do to ..
1) Check if all occurenes of L021-D8127-BLUEWASH-( 1 t0 10 )T.jpg & L021-D8127-BLUEWASH-( 1 t0 10 )S.jpg Exists.
2) If the Image(s) Exists Download all files matching
3) I do not want to use 20 FTP Connections simultaneously ?
So what you want to do in your scrip there is call ftp_nlist
$contents = ftp_nlist($conn_id, ".");
And loop through the result set of that.
foreach ($contents as $file) {
$local_file = '';
$server_file = '';
ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)
}
etc...
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");
}
?>