Upload files to remote server using PHP - php

I’m a novice in php and html, and I found some codes that allowed me to upload files to a remote server using a html form and a php code.
I tested the code locally using wamp and I found some bugs, like I cannot overwrite an existing file and the formatting of the name of the file is not taken into consideration.
The files that I would like to upload are named in French and have spaces between them, the server is a debian server.
The goal of this code is to retrieve a URL.
The HTML code:
<form enctype="multipart/form-data" action="remote_upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
The PHP code:
$ftp_server = "192.168.1.111";
$ftp_user_name = "";
$ftp_user_pass = "";
$remote_dir = "C:\wamp\www";
// 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);
//default values
$file_url = "";
if($login_result) {
//set passive mode enabled
ftp_pasv($conn_id, true);
$file = $_FILES["uploadedfile"]["tmp_name"];
$remote_file = $_FILES["uploadedfile"]["name"];
$ret = ftp_nb_put($conn_id, $remote_file, $file, FTP_BINARY, FTP_AUTORESUME);
while(FTP_MOREDATA == $ret) {
$ret = ftp_nb_continue($conn_id);
}
if($ret == FTP_FINISHED) {
echo "File '" . $remote_file . "' uploaded successfully.";
} else {
echo "Failed uploading file '" . $remote_file . "'.";
}
} else {
echo "Cannot connect to FTP server at " . $ftp_server;
}

Related

upload multiple files and keep previous files like github do PHP/MYSQL

Hi stackoverflow family ,
my problem is that i want to upload multiple files (php/html/css etc..) and keep my old version of files like github does, like to upload new files and when i want go back to my olds files i find it and i can download it i searched in stackoverflow if there's someone that asked about this topic to help me and i didn't find anything
the main idea is that i can upload files (html/css/sql etc..) and when i want to upload new files i can anytime go back and find the old version of files like github exactly
<form method="POST" action="php/upload.php" enctype="multipart/form-data">
<div class="control-panel">
<label>Project folder name</label>
<input type="text" name="directoryName"><br>
<label>Project name</label>
<input type="text" name="projectName"><br>
<label>Project description</label>
<textarea name="description"></textarea><br>
<span>PUSH PROJECT</span>
<input type="file" name="uploadedFile" />
</div>
<input type="submit" class="uploadBtn button5" name="uploadBtn" value="Push" />
</form>
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "github";
$description = $_POST["description"];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_SESSION["username"];
$message = '';
echo "hello";
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Push')
{
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)
{
// get details of the uploaded file
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileType = $_FILES['uploadedFile']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
// sanitize file-name
$newFileName = (date("Y-m-d")."_".time()."_". $fileName) . '.' . $fileExtension;
// check if file has one of the following extensions
$allowedfileExtensions = array('jpg', 'php', 'html', 'zip', 'txt', 'xls', 'doc');
if (in_array($fileExtension, $allowedfileExtensions))
{
// directory in which the uploaded file will be moved
$dirc = $_POST["directoryName"];
mkdir($dirc);
$uploadFileDir = './'.$dirc.'/';
$dest_path = $uploadFileDir . $newFileName;
$projectName=$_POST["projectName"];
$sql = "INSERT INTO project
VALUES ('$user', '$dest_path','$description','$projectName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if(move_uploaded_file($fileTmpPath, $dest_path))
{
$message ='File is successfully uploaded.';
}
else
{
$message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
}
}
else
{
$message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions);
}
}
else
{
$message = 'There is some error in the file upload. Please check the following error.<br>';
$message .= 'Error:' . $_FILES['uploadedFile']['error'];
}
}
$_SESSION['message'] = $message;
//begin *********************************************************************
header("Location: ../");

Unable to connect a server with FTP and PHP

I am unable to connect to a FTP server when i am connecting it through our PHP code. Most embarrassing thing is that i get only false when trying to connect server with ftp_connect() method. No errors are reported. This is my first time when i am working with FTP in PHP. if anyone who have previously worked on it can help me out here. Here is my code :
/* Source File Name and Path */
$remote_file = $_SERVER['DOCUMENT_ROOT'] ."/some-folder/file.txt";
/* New file name and path for this file */
$ftp_host = 'ftp://targetserver.com/some folder/';
$ftp_user_name = 'user';
$ftp_user_pass = 'XXXXX';
/* New file name and path for this file */
$local_file = 'ftp://targetserver.com/some-folder/file.txt';
/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host, 21);
var_dump($connect_it);
/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );
/* Download $remote_file and save to $local_file */
if ( ftp_get( $connect_it, $local_file, $remote_file, FTP_BINARY ) ) {
echo "Successfully written to $local_file\n";
}
else {
echo "There was a problem\n";
}
/* Close the connection */
ftp_close( $connect_it );
Actually getting false means that your ftp client couldn't connect to the server for some reason
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
The best to do before you dive into php debugging is to try out another ftp client such as https://filezilla-project.org/ and see if all works fine, if not you will have saved your time because the issue not coming from your php script.
UPDATE 1
Then try this:
$ftp_host = 'targetserver.com';
http://php.net/manual/en/function.ftp-connect.php#refsect1-function.ftp-connect-parameters
The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.
And as for local_file and remote_file, they must be paths and not urls
http://php.net/manual/en/function.ftp-get.php#refsect1-function.ftp-get-examples
As ftp_connect function doesn't produce an error, I assume the extension is installed.
It is very possible this could be a firewall issue with port 21 blocked. (This is a very common reason)
<html>
<body>
<form enctype="multipart/form-data" action="upload_file.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
<?php
$ftp_server = "94.23.x.xxx";
$ftp_username = "anxxxxx";
$ftp_password = "6xxxxxxxx";
// setup of connection
$conn_id = ftp_connect($ftp_server) or die("could not connect to $ftp_server");
// login
if (#ftp_login($conn_id, $ftp_username, $ftp_password))
{
echo "conectd as $ftp_username#$ftp_server\n";
}
else
{
echo "could not connect as $ftp_username\n";
}
$file = $_FILES["uploadedfile"]["name"];
$remote_file_path = "/JustForTest".$file;
ftp_put($conn_id, $remote_file_path, $_FILES["uploadedfile"]["tmp_name"],
FTP_ASCII);
ftp_close($conn_id);
echo "\n\nconnection closed";
?>
Then what's the problem with the above code?

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

Uploading image to FTP using PHP

I have tried files upload to server using ftp connection in php and its not working, its connecting but getting Error like "Connected to XXXXXXXXXXX, for user XXXXXXXXXXXXX FTP upload has failed!" I have tried following code please help by correcting it,..
image.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome</title>
</head>
<body>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input name="submit" type="submit" value="Upload File" />
</form>
</body>
</html>
upload.php
<?php
$ftp_server = "XXXXXX";
$ftp_user_name = "XXXXXXX";
$ftp_user_pass = "XXXXXXXX";
$destination_file = "imagetest/123/".$_FILES['file']['name'];
$source_file = $_FILES['file']['tmp_name'];
// set up basic connection
$conn_id = ftp_connect($ftp_server);
ftp_pasv($conn_id, true);
// 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, $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";
}
// close the FTP stream
ftp_close($conn_id);
?>
I've tested your code and had a bit of a hard time to get it working, but what worked for me was to use something like /http_docs, or /public_html as the base/root folder.
Root folder names will vary from hosting services, so modify accordingly.
I.e. and with a few modifications:
<?php
$ftp_server = "XXXXXX";
$ftp_user_name = "XXXXXXX";
$ftp_user_pass = "XXXXXXXX";
$folder = "/http_docs/imagetest/123/";
$destination_file = $folder . $_FILES['file']['name'];
$source_file = $_FILES['file']['tmp_name'];
// rest of code
Sidenote:
Do not use a full path name.
I.e.: /var/user/you/public_html/ it won't work.

How to upload a file via ftp in PHP?

I have a form with html browse type and a submit button. I chose a file using browse button and submit the form. On form submission following code is called.
$conn_id="myid";
$conn_id = ftp_connect ( 'server' );
$ftp_user_name="username";
$ftp_user_pass="password";
// 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!" ;
exit;
} else {
echo "Connected to for user $ftp_user_name" ;
}
// upload the file
$upload = ftp_put( $conn_id, "images/signatures/" . $fileName , $_FILES['tmp_name'] , FTP_BINARY );
// check upload status
if(!$upload){
echo "FTP upload has failed!" ;
} else {
echo "Successfully Uploaded." ;
}
But it produce the following warning:
Warning: ftp_put(): Filename cannot be empty in /var/www/echdp/_ProviderSignature.php on line 70 FTP upload has failed!
But when I hard code the source path in above code then it upload the file on server:
$upload = ftp_put( $conn_id, "images/signatures/myfile.txt" , "/var/www/images/hello.txt" , FTP_BINARY );
Try this:
$file = 'somefile.txt';
$remote_file = '/public_html/dir/dir2/dir3/somefile.txt';
$ftp_server = "yourdomain.in";
$ftp_user_name = "ftpusername";
$ftp_user_pass = "ftppassword";
// 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);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
Your file will be uploaded in the /public_html/dir/dir2/dir3/ directory of your domain.
Caution: Never upload an index file when you are testing this feature.
Source: PHP.net
Example of html code with enctype:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="myfile" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
Do you have enctype in Form tag? Without the attribute your file won't be send.
For debugging of $_FILES array. Try
var_dump($_FILES);
to see if the data are correct.
Your variable:
$_FILES['tmp_name']
is used wrongly because $_FILES contain files not a one file. Therefore you should write:
$_FILES['your-name-in-html-form']['tmp_name'] // your-name-in-html-form = myfile in the example above
Have a look on the example: http://www.zymic.com/tutorials/php/creating-a-file-upload-form-with-php/
$_FILES['tmp_name']
isn't name of your file. It is stored in:
$_FILES['inputname']['tmp_name']
where inputname is name of your field. Also check your form for enctype ="multipart/form-data".
Be aware of simply putting on your server everything that user can send - if there is access to uploaded files by http (like http://yoursite/images/signatures/uploadedfile.xxx) someone can put .php files on your server and execute it !
Obviously $_FILES['tmp_name'] does not contain the filename. Try print_r($_FILES) to see what it contains. Also, use multipart/form-data as your form enctype.

Categories