I'm kinda new to PHP.
I've got two different hosts and I want my php page in one of them to show me a directory listing of the other. I know how to work with opendir() on the same host but is it possible to use it to get access to another machine?
Thanks in advance
Try:
<?php
$dir = opendir('ftp://user:pass#domain.tld/path/to/dir/');
while (($file = readdir($dir)) !== false) {
if ($file[0] != ".") $str .= "\t<li>$file</li>\n";
}
closedir($dir);
echo "<ul>\n$str</ul>";
You could use PHP's FTP Capabilities to remotely connect to the server and get a directory listing:
// set up basic connection
$conn_id = ftp_connect('otherserver.example.com');
// login with username and password
$login_result = ftp_login($conn_id, 'username', 'password');
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
exit;
}
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
// Retrieve directory listing
$files = ftp_nlist($conn_id, '/remote_dir');
// close the FTP stream
ftp_close($conn_id);
I was unable to get the FTP suggestions to work so I took a more unconventional route, basically it yanks the html from the "Index of" page and extracts the filenames.
Index page:
Index of /files
Parent Directory
1.jpg
2.jpg
Extraction code:
$dir = "http://www.yoursite.com/files/";
$contents = file_get_contents($dir);
$lines = explode("\n", $contents);
foreach($lines as $line) {
if($line[1] == "l") { // matches the <li> tag and skips 'Parent Directory'
$line = preg_replace('/<[^<]+?>/', '', $line); // removes tags, curtousy of http://stackoverflow.com/users/154877/marcel
echo trim($line) . "\n";
}
}
Related
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 fetch all the .ch files (located inside a specific folder) from my FTP server into my website using PHP. May I receive some guidance about how can I do it?
After reading these basic examples from the PHP manual, you can use parts of this code:
<?php
$dir = "/ftpdir/source/";
$dir1= "/websitedir/newfolder/"
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
//Check the file extension, several methods available
$ext=pathinfo($dir.$file);
// If the extension is ch, then copy the file
if($ext == "ch") {
if(copy($dir.$file,$dir1.$file)) {
echo $dir.$file." has been copied to ".$dir1.$file."<br>";
}
else { echo "Something went wrong.<br>"; }
}
}
closedir($dh);
}
}
?>
I hope this would help you.
Please check: http://php.net/manual/en/function.ftp-nlist.php
Example:
<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");
// output $contents
var_dump($contents);
?>
You can easy apply this for .ch using if($something == "ch") {...}
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");
}
?>