How to move image to another server PHP - php

I have two servers so i want when i upload file/image from first server ( using move uploaded file function),
file should be upload to second server.for this i used following code
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '#/path/to/file.txt'));
curl_setopt($ch, CURLOPT_URL, 'http://server2/upload.php');
curl_exec($ch);
curl_close($ch);
but i want to know that what code should be there in second servers "upload.php".And how can i mention path ?

first off, don't try to upload files with the # method, it was deprecated in PHP5.5, disabled-by-default in PHP5.6, and completely removed in PHP7.0. use CURLFile to upload files. to mention a path, just add the path as another post variable in the array. as for the receiver, read the handling file uploads in php article on php.net. finally, consider if you want to let anyone who finds the url to be able to upload any file or not. (probably not, you *probably* want to set a password on uploads), eg
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'file' => new CURLFile('path/to/file.jpg'),
'path' => '/where/ever/you/want.jpg',
'password' => 'd540cyLp419rdwelv8c-'
));
on the sender and
if (! hash_equals(hash('sha256', 'd540cyLp419rdwelv8c-', true), hash('sha256', (string) ($_POST['password'] ?? ''), true))) {
http_response_code(403); // forbidden
die("wrong/missing password.");
}
$upload_path = $_FILES["file"]["tmp_name"];
$requested_file_path = $_POST['path'];
on the receiver, again, see the aforementioned "handling file uploads in php" article to learn more.

Related

WP ALL Export - Php snippet works on one server but not another

Im using the wordpress plugin wp all export to export a csv file and send it via FTP. They plugin provider actually had a code snippet on their site to do exactly what I need The only thing I changed in their code was adding in my own FTP details
See code example below
function wpae_after_export( $export_id ) {
// Retrieve export object.
$export = new PMXE_Export_Record();
$export->getById($export_id);
// Check if "Secure Mode" is enabled in All Export > Settings.
$is_secure_export = PMXE_Plugin::getInstance()->getOption('secure');
// Retrieve file path when not using secure mode.
if ( !$is_secure_export) {
$filepath = get_attached_file($export->attch_id);
// Retrieve file path when using secure mode.
} else {
$filepath = wp_all_export_get_absolute_path($export->options['filepath']);
}
// Path to the export file.
$localfile = $filepath;
// File name of remote file (destination file name).
$remotefile = basename($filepath);
// Remote FTP server details.
// The 'path' is relative to the FTP user's login directory.
$ftp = array(
'server' => 'ftp URL',
'user' => 'ftp Password',
'pass' => 'ftp Username',
'path' => '/'
);
// Ensure username is formatted properly
$ftp['user'] = str_replace('#', '%40', $ftp['user']);
// Ensure password is formatted properly
$ftp['pass'] = str_replace(array('#','?','/','\\'), array('%23','%3F','%2F','%5C'), $ftp['pass']);
// Remote FTP URL.
$remoteurl = "ftp://{$ftp['user']}:{$ftp['pass']}#{$ftp['server']}{$ftp['path']}/{$remotefile}";
// Retrieve cURL object.
$ch = curl_init();
// Open export file.
$fp = fopen($localfile, "rb");
// Proceed if the local file was opened.
if ($fp) {
// Provide cURL the FTP URL.
curl_setopt($ch, CURLOPT_URL, $remoteurl);
// Prepare cURL for uploading files.
curl_setopt($ch, CURLOPT_UPLOAD, 1);
// Provide the export file to cURL.
curl_setopt($ch, CURLOPT_INFILE, $fp);
// Provide the file size to cURL.
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
// Start the file upload.
curl_exec($ch);
// If there is an error, write error number & message to PHP's error log.
if($errno = curl_errno($ch)) {
if (version_compare(phpversion(), '5.5.0', '>=')) {
// If PHP 5.5.0 or greater is used, use newer function for cURL error message.
$error_message = curl_strerror($errno);
} else {
// Otherwise, use legacy cURL error message function.
$error_message = curl_error($ch);
}
// Write error to PHP log.
error_log("cURL error ({$errno}): {$error_message}");
}
// Close the connection to remote server.
curl_close($ch);
} else {
// If export file could not be found, write to error log.
error_log("Could not find export file");
}
}
add_action('pmxe_after_export', 'wpae_after_export', 10, 1);
I first set this up on a hostgator dedicated server and it worked perfectly but when I tried to copy the exact same process into another server hosting via AWS I don't receive the file into my FTP.
I would assume there is some sort of configration within the cpanel on the AWS server but I cannot figure out what. I dont get any error message when running the export either so the only thing I can see is that the export runs to 100% quickly but still runs for about 2 mins before its complete.
I also checked with the FTP owner and confirmed there is nothing on their site blocking the file from one server but not the other.
Someone also suggested I ensure both servers have cURL installed which I did confirm.

How to upload a file into another server in slim3 php

I am using silm3 as my REST API framework and followed this to write my file upload script from API.
I am currently running my web app in a.xyz.com and my REST API is in b.xyz.com . Now I want to upload a picture into a.xyz.com/uploaded/ from b.xyz.com/upload.
$newfile->moveTo("/path/to/$uploadFileName");
is used to save the file in current subdomain. But I failed to upload it into another subdomain.
I search in the web, but didn't find any clue how to do it.
After moving the file on b.xyz.com in the correct position, do the following:
// Server B
// Move file to correct position on B
$newfile->moveTo("/path/to/$uploadFileName");
// Send file to A
$request = curl_init('a.xyz.com/upload');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, [
'file' => new CURLFile("/path/to/$uploadFileName")
]);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
curl_close($request);
a.xyz.com should then accept the file and proceed to storing it. If using Slim, in the same way as b.xyz.com does
...
$newfile->moveTo("/path/to/$uploadFileName");
or using PHP's core functions
// Server A
if ( !empty($_FILES["file"]) && !empty($_FILES["file"]["tmp_name"]) ) {
// Move file to correct position on A
$uploadFileName = basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], "/path/to/$uploadFileName");
}
Normally domains or subdomains are restricted to their own webspace, so you can't read or write other domain's files. The setting is calles open_basedir.
You have to set it in your vhost configuration but there are also other ways, like setting it with a .htacces file if your hoster allows it:
How can I relax PHP's open_basedir restriction?

how to open txt file from another server using php

I want to open and write a txt file from another server, but I don't know how to do it? Can anyone help me?
<?PHP
$fname=$_POST["fname"];
$groupid=$_POST["groupid"];
$myfile = fopen("Ji.txt", "a+") or die("Unable to open file!");
fwrite($myfile, $fname."|".$groupid."\r\n");
fclose($myfile)
?>
I want to replace Ji.txt with http://xxx.xxx.xx.x/ddd.txt
You can read the files over HTTP by using fopen or cURL.
You can't write to files over HTTP unless the server you are writing to is set up to understand an appropriate request. You could configure it to support PUT requests (make sure you have some kind of authn/authz system in place!) and make one using cURL.
Alternatively, you could use some other protocol to make the file available between servers (such as NFS).
Alternatively you can do it with the FTP functions
<?php
// Connect to remote FTP server
$conn = ftp_connect("ftp.example.com")or die("Cant connect to ftp server");
$login = ftp_login($conn, "username", "password");
// Open local (temporary) file handle
$fh = fopen("Ji.txt", "a+");
// Get remote file and save it to the previous file handle
if(ftp_fget($conn, $fh, "Ji.txt", FTP_ASCII))
{
// Local file has now been updated with the content of the remote Ji.txt
$fname = $_POST['fname'];
$groupid = $_POST['groupid'];
fwrite($fh, $fname.'|'.$groupid.'\r\n');
if(ftp_fput($conn, "Ji.txt", $fh, FTP_ASCII))
echo 'File saved to remote server';
else
echo 'Error saving to remote server';
}
else
echo 'Error downloading remote file';
ftp_close($conn);
fclose($fh);
?>
Read more about ftp_fput etc here: http://php.net/manual/en/function.ftp-fput.php
As long as allow_url_fopen is set to True you can pass an URL to fopen() and read the data. Writing however, is impossible. However, you can write a wrapper around the file that accepts both GET & POSTS requests. A GET returns the contents of the file and a POST (or PUT) saves content to the files. The downside of this is that you must add security and it's a lot more complex to save the data.
Assuming you have access to the other server and the text file is available at a web address (ie you can see it in a browser) then you can use fopen to grab it, make your edits or whatever and then post back to a script that will handle the post data and save the file using curl. Example code below copied from this answer
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '#/path/to/file.txt'));
curl_setopt($ch, CURLOPT_URL, 'http://server2/upload.php');
curl_exec($ch);
curl_close($ch);
Posting server should be something like this
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('ourfilename' =>'yourpath/test.txt'));
curl_setopt($ch, CURLOPT_URL, 'http://urlreceivepost/getfile.php');
curl_exec($ch);
curl_close($ch);
Then getfile.php at your above url
if ($_POST) {
$file= $_POST['ourfilename'];
$data = file_get_contents($file);
$new = 'test.txt';
file_put_contents($new, $data);
var_dump($new);}

php curl or file_get_contents too slow on hosted site

I'm using cUrl to get the file's contents of the same website's page, and writing to another file ( To convert dynamic php file into static php file for menu caching purpose )
$dynamic = 'http://mysite.in/menu.php';
$static = "../menu-static.php" ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$dynamic);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$file = curl_exec($ch);
file_put_contents($static, $file);
die();
It works perfect on localhost. But taking too much time when it is running on hosted website, and at last even the output file ($static = "../menu-static.php") is empty.
I can't determine where is the problem .. Please help
I've also tried file_get_contents instead of cUrl with no luck ..

How to download a file from server using ftp and how to save that file in my local folder

this is my code but this is not working whats a problem in this code.u have any another code.give me idea to download a file from server using ftp.i am trying this code in my localhost also in my own server.
$curl = curl_init();
$file = fopen("ftpfile/file.csv", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp:http://www.address.com/file.csv"); #input
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FILE, $file); #output
curl_setopt($curl, CURLOPT_USERPWD, "myusername:mypassword");
curl_exec($curl);
I'm guessing one of two things: the fopen call failed (and you're not checking if it succeeded by seeing if $file !== false), or the double-use of _returntransfer AND _file is not acting as you expect.
returntransfer tells curl to return the retrieved data in the exec call, instead of outputting it directly to the browser. I suspect that if you did $data = curl_exec($curl); file_put_contents('ftpfile/file.csv', $data) you'd end up with a properly populatd file. So... either remove the returntransfer option, or eliminate the whole _file business and output the file yourself using what the _exec call returns.

Categories