Using PHP and Curl to POST an entire folder to another Server - php

What is the best way using PHP and Curl to POST an entire folder to another server.

you can:
post all files in the directory consequently
zip the directory and post the archive

$srcdir = '/source/directory/';
$dh = opendir($srcdir);
$c = curl_init();
curl_setopt($c, ....); // set necesarry curl options to specify target url, etc...
while($file = readdir($dh)) {
if (!is_file($srcdir . $file)) {
continue; // skip non-files, like directories
}
curl_setopt($c, CURLOPT_POSTFIELDS, "file=#{$srcdir}{$file}");
curl_exec($c);
}
closedir($dh);
That'd be the basics. You'd want some error handling in there, to make sure the source file is readable, to make sure the upload succeeds, etc.. The full set of CURLOPT constants are documented here.

Related

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?

Loading an external xml file and then saving it into a website directory using PHP

So I found this page: Load external XML and save it using PHP to help me out, but it doesn't seem to work for me.
I'm trying to do the same thing by loading an external xml file and saving it (with no changes to the xml file) into my website directories as a batch system. I have already dynamically created all the directories needed.
ex:
/xml/en/281
Now what I'm trying to do is load the company's xml files (https://thiscompany.com/xml/en/281/18511095_en.xml) and save it in my own directory as the same name, 18511095_en.xml in the 281 directory.
I've been researching and I am getting lots of simplexml_load_file and DOMDocument examples but I'm not getting the results I needed.
For all sake and purposes here is the code: (I'm changing the url of the actual xml file because my client doesn't want it out there.
EDITED from the responses below
$url = "https://thiscompany.com/xml/en/281/18511095_en.xml";
$timeout = 10;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$response = curl_exec($curl);
file_put_contents(__DIR__ . "/xml/18511095_en.xml", $response);
I'm assuming the problem is with the saveXML path. The xml directory is at the root of my website. Do I need to include, http://www.....com?
xml, en, and 281 all have 0777 permissions.
Any help would be appreciated.
You need to provide the path on your filesystem, not a URL.
e.g. "/var/www/www.example.com/htdocs/xml/en/281/18511095_en.xml"
Here's a simple way to copy a remote file into the same directory as your PHP file:
$url = "http://www.test.com/xmlfile.xml";
$contents = file_get_contents($url);
file_put_contents(dirname(__FILE__) . "/xmlfile.xml", $contents);
You can also accomplish this without having to use simplexml_load_string which will use more memory on your server. Instead try the following:
$xml = file_get_contents("https://thiscompany.com/xml/en/281/18511095_en.xml");
file_put_contents("/var/www/my/full/data/path/filename.xml", $xml);
$xml = simplexml_load_string($response);
$xml->saveXML("/xml/en/281/18511095_en.xml");
First of all, you should use a relative path instead of an absolute one. In this example you are trying to save the file under the /xml folder on the root filesystem and there's most likely no such directory and you don't have permissions to write to that directory (assuming it exists). Use a relative path.
Secondly, you don't need to parse the XML file, you can save it directly. Here's a working example:
$response = curl_exec($curl);
file_put_contents(__DIR__ . "/xml/en/281/xmlfile.xml", $response);
Further reading: Absloute path vs relative path in Linux/Unix

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

check and read file from subdomain

i have subdomain sub.domain.com. the subdomain points on a directory root/sub of my root dir on my Webserver.
now i have pdfs on another dir on the server root/pdf.
How can i check if a specific pdf exists and if it exists i want to copy the file to a temp dir of the subdomain.
if i call a php script sub/check.php an try to check a pdf that exists :
$filename = "http://www.domain.com/pdf/1.pdf";
if (file_exists($filename))
{
"exists";
}
else
{
"not exists";
}
It always shows : not exists.
If i take the url and put it in a browser - the pdf will be shown.
How can my php script in the /sub-folder access files in the root or root/pdf ?
bye jogi
file_exists() function does not work that way. It does not take remote URLs.
This function is used to check the file that exists on the file system.
Check the manual here
Make use of cURL to accomplish this.
<?php
$ch = curl_init("https://www.google.co.in/images/srpr/logo4w.png"); //pass your pdf here
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200)
{
echo "exists";
}
else
{
echo "not exists";
}
?>
file_exists() looks locally on the machine if a file exists. But what you are doing is using a URL.
Since you say your script is in the root folder, you need to do change
$filename = "http://www.domain.com/pdf/1.pdf";
into
$filename = realpath(dirname(__FILE__)) . "/pdf/1.pdf"; // first part gets current directory

Saving images from website to folder using curl php

I am able to save images from a website using curl like so:
//$fullpath = "/images/".basename($img);
$fullpath = basename($img);
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawData = curl_exec($ch);
curl_close($ch);
if(file_exists($fullpath)) {
unlink($fullpath);
}
$fp = fopen($fullpath, 'w+');
fwrite($fp, $rawData);
fclose($fp);
However, this will only save the image on the same folder in which I have the php file that executes the save function is in. I'd like to save the images to a specific folder. I've tried using $fullpath = "/images/".basename($img); (the commented out first line of my function) but this results to an error:
failed to open stream: No such file or directory
So my question is, how can I save the file on a specific folder in my project?
Another question I have is, how can I change the filename of the image I save on the my folder? For example, I'd like to add the prefix siteimg_ to the image's filename. How do I implement this?
Update: I have managed to solve first problem with the path after trying to play around with the code a bit more. Instead of using $fullpath = "/images/".basename($img), I added a variable right before fopen and added it to the fopen method like so:
$path = "./images/";
$fp = fopen($path.$fullpath, 'w+');
Strangely that worked. So now I'm down to one problem which would be renaming the file. Any suggestions?
File paths in PHP are server paths. I doubt you have a /images folder on your server.
Try constructing a relative path from the current PHP file, eg, assuming there is an images folder in the same directory as your PHP script...
$path = __DIR__ . '/images/' . basename($img);
Also, why don't you try this much simpler script
$dest = __DIR__ . '/images/' . basename($img);
copy($img, $dest);

Categories