How to upload files from database on FTP remote server? [duplicate] - php

This question already has answers here:
PHP ftp_put fails
(2 answers)
Closed 1 year ago.
I use PHP to upload images from a host into FTP remote server.
I have already stored the names of the files that need to be uploaded to the FTP remote server, stored on the database.
After connecting to DB and a query for select information of images, I passed variables with $_SESSION to another PHP file for upload them on FTP remote server like this:
conn_auth.php for select target images:
<?php
if (file_exists(__DIR__.'/conn_auth/db_conn.php')){
include __DIR__.'/conn_auth/db_conn.php';
}else{
die('Connection is Failed ...!');
}
$conn = OpenConn();
$sql = "SELECT * FROM users where status = 'Active'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$user_id = $row["id"];
//search for user_id in userAthentication Table in DB
$sql = "SELECT * FROM userauthentication where user_id = $user_id";
$result = $conn->query($sql);
$user_auth = $result->fetch_assoc();
$user = array(
'id'=>$row['id'],
'name'=>$row['name'],
'family'=>$row['family'],
'auth_image'=>'',
'file_name'=>$user_auth["image"],
'phone'=>$row["phone"]
);
$url = "/home/root/app_name_1/uploads/".$user["file_name"];
if(!file_exists($url)){
$url = "/home/root/app_name_2/uploads/".$user["file_name"];
}
$user['auth_image'] = $url;
session_start();
$_SESSION["userInfo"] = $user;
$_SESSION["userAuth"] = $user_auth;
if (file_exists(__DIR__.'/conn_auth/get_auth.php')){
include __DIR__.'/conn_auth/get_auth.php';
}else{
die("I can't Connect to the Server");
}
}
} else {
echo "0 results";
}
CloseConn($conn);
On this file, I try to connect to FTP remote server and upload images with the ftp_put() method, but it does not work:
<?php
include_once __DIR__.'../conn_auth.php';
session_start();
$ftp_server="*.***.***.**";
$ftp_user_name="****";
$ftp_user_pass="**********";
$file = $_SESSION["userInfo"]['auth_image']; //to be uploaded
$folder_name = $_SESSION["userInfo"]['phone'];
$file_name = $_SESSION["userInfo"]["file_name"];
$remote_file = "/HDD/pics/$folder_name";
$conn_id = ftp_connect($ftp_server,21);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_mkdir($conn_id,'auth_pics').ftp_chdir($conn_id,'auth_pics');
if (ftp_mkdir($conn_id,"$folder_name")){
ftp_chdir($conn_id,$folder_name);
}else{
echo "I Can't Create Folder For : ".$folder_name;
die();
}
// upload a file
$upload = ftp_put($conn_id, $remote_file, $file, FTP_BINARY);
if ($upload) {
echo "successfully uploaded : $file\n";
} else {
echo "There was a problem while uploading...\n";
}
// close the connection
ftp_close($conn_id);
?>

Mostly your FTP server doesn't support active mode connections, so you may try to switch to the passive mode using the ftp_pasv, but make sure to do this after you logged into the server (after ftp_login).
If you face some troubles while using the native API functions, you may want to try out an FTP client library, like this, that I've built.
Hope you find this answer useful for you.

Related

Pureftpd-upload while uploading image through ftp

I am trying to upload image from one server to another server through FTP by using PHP.But the uploaded data shows.pureftpdupload.5809ed2f.15.7b36.24316ca6 error.
I am using this code.
$connection = 'servername';
$username = 'xxxx';
$password = 'yyyy';
$local_file = 'http://servername/test.jpg';
$remote_file = 'admin/files/company/test.jpg';
$connection = ftp_connect($server);
if (#ftp_login($connection, $username, $password)) {
// successfully connected
//echo 'connected';exit;
} else {
echo 'not connected';
return false;
}
if (ftp_put($connection, $remote_file, $local_file, FTP_BINARY)) {
echo "successfully uploaded\n";
} else {
echo "There was a problem while uploading \n";
}
My guess is that you want to upload a local file from a web server. But by mistake or misunderstanding, you are using file's HTTP URL (http://servername/test.jpg) instead of file's local path.
Try to use a real local path, like /home/user/test.jpg.
This may work as a generic solution: $_SERVER['DOCUMENT_ROOT']."/test.jpg"

how to implement pagination while fetching data from file server in php

I wrote a php script which fetches the data from file server,it lists all the uploaded file on server.
Now problem is there is large no. of file on my server ,i want limited results per page how can i implement pagination for this.
My php code is :
$ftp_server = "ftp.abc.com";
$ftp_user = "uploads#abc.com";
$ftp_password = "xyz";
$conn = ftp_connect($ftp_server) or die("could not connect to ftp server");
if (ftp_login($conn, $ftp_user, $ftp_password)) {
$contents = ftp_nlist($conn, $path);
foreach($contents as $value) {
$i++;
echo "$i <a href='#form' id='url_title' class='links'>$value</a><br><br> <br>";
}
}

PHP script to copy a file from 1 FTP to another FTP

I would like to copy a file (eg. MYFILE.csv) from FTP 'SOURCE' to FTP 'TARGET'. What type of command would you recommend for a script in php?
I have tried this but it didn't work.
<?php
$server = 'ftp.TARGET.com' ;//address of ftp server
$user_name = 'USER_TARGET'; // Username
$password = 'PASSWORD_TARGET'; // Password
$source = 'MYFILE.csv';
$dest = '/in/MYFILE.csv';
$mode='FTP_ASCII';
// set up basic connection
$connection = ftp_connect($server) ;
// login with username and password
$login_result = ftp_login($server, $user_name, $password);
// upload a file
if (ftp_put($connection, $dest, $source, $mode)) {
echo "successfully uploaded $source\n";
} else {
echo "There was a problem while uploading $source\n";
}
// close the connection
ftp_close($connection);
?>
=> The php script will be hosted in a folder on FTP A.
Thank you for your guidance.
You can use file_put_contents
http://php.net/manual/en/function.file-put-contents.php
file_put_contents('ftp://user:pass#server/path/to/file.txt', $data);
It will return false on a failure:
if(file_put_contents('ftp://user:pass#server/path/to/file.txt', $data)) {
// ftp upload successful
} else {
// ftp upload failed
}
Why does your current method fail though?

can't download file from ftp with ftp_get (no error)

I'm trying to download file from ftp, but whatever i tried i couldn't download any file from ftp and it is not giving any error.
My code fetching file names from database and compares these file names with existing ftp file(names). If file name exist on ftp i want to download this file to my local-destination folder.
I can read ftp file names but i can't download them. Hope you can help me.
Here is my code
error_reporting(E_ALL);
$ftp_server = "xx.xx.y12.34"; //server
$bt = ftp_connect($ftp_server); // connect to ftp
$username = "myusername"; $pass = "mypass"; //username and password
$connection = ftp_login($bt, $username, $pass); // login ftp with username and password
ftp_pasv($bt, true);
if ((!$bt) || (!$connection)) {
echo "failed";
exit;
}else {
$path = "/1_Swatch Files/LG Swatches/";
$destination_folder = "/home/faruk/lasenza/media/color_samples/";
// mysql connection codes..
$results = $readConnection->fetchAll($query); // fetch file names from database
$contents_on_server = ftp_nlist($bt, $path);
foreach($results as $result){
$check_file_exist = $result["CLR_CODE"].".gif";
if(in_array($check_file_exist, $contents_on_server)) {
$server_file = $result["CLR_CODE"].".gif";
if (ftp_get($bt, $destination_folder , $server_file, FTP_BINARY)) {
echo 'Succeeded';
}else{
echo "There was a problem";
}
break;
}
}
}

PHP FTP upload error: Warning: ftp_put() [function.ftp-put]: Filename cannot be empty in

I'm having some trouble finishing my FTP file uploader using PHP. I'm using the example from php.net found here: http://php.net/manual/en/ftp.examples-basic.php and have modified the code slightly.
<?php
//Start session();
session_start();
// Checking the users logged in
require_once('config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$ftp_server="*";
$ftp_user_name="*";
$ftp_user_pass="*";
$paths="members/userUploads";
$name=$_FILES['userfile']['name'];
$source_file=$_FILES['userfile']['tmp_name'];
// 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);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
// upload the file
$upload = ftp_put($conn_id, $paths.'/'.$name, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
$CurrentUser = $_SESSION['CurrentUser'];
$qry = "SELECT * FROM members WHERE username='$CurrentUser'";
$result = mysql_query($qry);
$result = mysql_fetch_array($result);
$CurrentUser = $result[memberID];
$qry = "INSERT into uploads (UploadPath, UploadUser) VALUES('$file_name', '$CurrentUser')";
echo "Uploaded $source_file to $ftp_server as $paths.'/'.$name";
}
// close the FTP stream
ftp_close($conn_id);
?>
However, the code will work for some files but not others. When it doesn't work it gives the error:
Warning: ftp_put() [function.ftp-put]: Filename cannot be empty in ... on line 48.
The name might not be set if there was an error when sending the file. This would cause you to try to upload to members/userUploads/, which would cause ftp_upload to rightly complain about an empty filename.
A common reason for the error is exceeding the maximum allowed filesize. At the very least, check the error in the $_FILES entry for your file before attempting the FTP upload:
if ($_FILES['userfile']['error'] != UPLOAD_ERR_OK) {
// handle the error instead of uploading, e.g. give a message to the user
}
You can find the description of the possible error codes in the PHP manual.
That probably comes from $name or $source_file being blank, perhaps the file upload is sometimes failing and causing the problem. You could try using an if somewhere to make sure a file was uploaded such as:
if (empty($name)) {
die('Please upload a file');
}
Just to note, unless you are using variables in the string such as:
echo "Connected to $ftp_server, for user $ftp_user_name";
its preferable to use single quotes. Technically its faster that double quotes as it doesn't scan the string for variables. Plus I think it looks neater! :)
line 48 needs to be changed, note the double quotes and the elimination of .'/'. Depending on the name of the file you are trying to upload, you may be escaping part of it's name.
$upload = ftp_put($conn_id, "$paths/$name", $source_file, FTP_BINARY);

Categories