Uploading a file to my Linux PHP web host through a URL - php

First of all, I don't know if this is where I have to ask this question; so I'll count on the moderators to move it if need be.
I have a Linux PHP web hosting account on GoDaddy.
When I have to upload a file, I normally use FTP, either a client or the host's file manager.
However, if the file is one which I have to download from another website, I would prefer if I could "download" it directly to my hosting account; the reason being that I'm in Mauritius and our connection is among the slowest in the world. So I would prefer using the high (I'm just assuming it's higher) bandwidth of the host so that transfers go more quickly.
So, my question is: does anyone of you have a solution (PHP script, Java applet, or anything) that I could use to achieve that?
Thanks in advance,
Yusuf

First of this might be a security risk on your server.
Secondly, here's little untested code:
<?php
echo 'get file...';
$data=file_get_contents('http://...target-url...');
if($data===false)die('Failed getting file.');
echo 'saving file...';
$succ=file_put_contents('...target-file...',$data);
echo $succ ? 'Success' : 'Failed saving file';
?>
Usable script (put into file "down.php" in your web root):
<?php
echo 'get file...';
if(!isset($_REQUEST['from'])die('Fail: Parameter "from" not set.');
if(!isset($_REQUEST['to'])die('Fail: Parameter "to" not set.');
$data=file_get_contents($_REQUEST['from']);
if($data===false)die('Failed getting file.');
echo 'saving file...';
$succ=file_put_contents($_REQUEST['to'],$data);
echo $succ ? 'Success' : 'Failed saving file';
?>
Usage (run it in from web browser):
http://yoursite.com/down.php?from=http://yourothersite.com/file-content.txt&to=/var/www/public_html/target.txt
WARNING: Make sure you remove script after use, it is a grave security issue.

Wget I use it for downloading wordpress straight to a server:
# Download the title page of example.com to a file
# named "index.html".
wget http://www.example.com/
# Download Wget's source code from the GNU ftp site. wget
ftp://ftp.gnu.org/pub/gnu/wget/wget-latest.tar.gz
The example are from the link above.

Christian trick make better with this code.
You can create a folder like d on your host and protect it with password! Then create a new index.php and put beloow code on it
<?php
echo 'Get file...';
$url = $_REQUEST['from'];
$filename= preg_replace('/\\?.*/', '', basename($url));
$to ='dl/'.$filename;
$data=file_get_contents($_REQUEST['from']);
if($data===false)die('Failed getting file.');
echo "<br/>".'Saving file...';
$succ=file_put_contents($to,$data);
echo $succ ? "<br/>".'Success' : "<br/>".'Failed saving file';
?>
finally create a folder named dl to store downloaded files.
Usage (run it in from web browser):
http://yoursite.com/d/?from=http://yourothersite.com/file.txt

Related

How to upload file in php from browser with no user input

I am working on a php web app .
I need to upload a file to the web server, with customer info - customers.csv.
but this process needs to be automated ,
The file will be generated in a Point of Sale app , and the app can open a browser window with the url ...
first i taught i would do something like this www.a.com/upload/&file=customers.csv
but read on here that is not possible,
then i taught i would set a value for the file upload field and submit form automatically after x seconds. Discovered thats not possible .
Anybody with a solution , will be appreciated .
EDIT
I have tried this and it works ,file is uploaded to remote server
is it working only because the php script is running on the same pc where csv is sitting ???
$file = 'c:\downloads\customers.csv';
$remote_file = 'customers.csv';
// set up basic connection
$conn_id = ftp_connect('host.com');
// login with username and password
$login_result = ftp_login($conn_id,'user','password');
// 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);
This is of course not possible, imagine how this could be abused to upload on linux as example the /etc/passwd. The only way it might be possible is to use a Java Applet, but this is for sure not the best way.
You could try to let your PoS Application make a web request with the customers.csv file and let a WebAPI handle the upload, this may be possible, but I have no expierence with Point of Sale Applications.
Best might be, if the solution above cannot be considered, to just prompt the user to provide the file above and check over name + content if it is the correct one.
This is a bit tricky, but if your CSV is not too long, you could encode it in base64, send to the webserver as a GET parameter and then, in the server side, decode and store it as a CSV file.
If the file is too big to do that, you have to use other method, like the java applet pointed by #D.Schalla or even install and configure a FTP server, and make the Point of Sale app uploads the file there.
Other alternative, specially good if you cannot modify the sale app, is to install a web server in the client side and write a small php script to handle the upload process. In this way, the sale app could call a local url (something like: http:// localhost/upload.php) and it's this script the one in charge to upload the file which can be achieve with a classical HTTP POST, a FTP connection or any other way you can think about.
MY Solution , which will work with out setting up web server on client side.
This is for windows but can be adapted to linux
On client side
Local Application opens cmd and runs this command ftp -n -s:C:\test.scr
WHICH opens test.scr - a file with ftp commands e.g.
open host.com
user1
passwOrd
put C:\downloads\customers.csv public_html/customers.csv
more info here :
http://support.microsoft.com/kb/96269
more commands :
http://www.nsftools.com/tips/MSFTP.htm#put

PHP file doesn't rewrite

I make a site map, and make it with php file, that generate it from mysql. I change host and now I have problem with writing into file. I can't understand something.
Here is my example:
<?php
$xml = 'bla bla xml'; //... some xml generating code
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/my_site_map.xml', 'w');
if($fp)
echo 'we opened it';
else
echo 'we failed';
$fwrite=fwrite($fp, $xml, strlen($xml));
if($fwrite==false)
echo "another fail";
fclose($fp);
echo "we done";
?>
The question is: my file my_site_map.xml have a permission 664 (rw-rw-r--), and I can't use this script if I open this php page from browser, so, if I try to do this I'll see: "we failed another fail we done"; But if I open this through crontab and see a log file, I can see this: "we opened it we done". I want exactly this but the main problem is that the file isn't have been rewritten. Why? And how can I fix this? Thanks.
My server is nginx not an Apache, didn't thought that this info will valuable
Well I don't have enough rep to comment so this will have to be an answer.
I'm going to take a stab in the dark and say the file is owned by your user or root, not the process that is running the webserver. Nor is the file owned by the group the webserver process is run under.
So either chown/chgrp the file to be owned by the apache(?!) process running, e.g. chown apache file or set the file to have write permissions to everyone, e.g. chmod 666 file
Don't chmod 777 as commented above unless it's an executable file and you want anyone to be able to run it. The 1st solution is a better practice than just giving anyone read access to a file.
Edit: In comment to the comments on the original answer above, if the file isn't an executable then don't give it 7 for any permisions. 6 is read/write and is suitable for a text file you are opening to write to (even 2 is if it comes to that).
Edit 2: Try catching any exceptions that your fopen function runs in a try catch block:
try {
$fp = fopen($_SERVER['DOCUMENT_ROOT'].'/my_site_map.xml', 'w');
} catch (Exception $e) {
echo "The error is" . $e->getMessage();
}
For PHP code here are the links to change it on the fly. You can change it to what ever make your edits then change it back as needed.
http://php.net/manual/en/function.chmod.php
http://php.net/manual/en/function.chown.php
http://php.net/manual/en/function.chgrp.php
Examples are included on each link with the documentations. Find the permissions that works best for what your doing. There isn't a one size fits all for permissions since it really depends on your end product (web app, page, what ever).

PHP exec() and SSL

I use third part framework (exe file) for conneting one php application with taxt service.
Framework is open source, exe file sign xml, give soap cover and send it to central information tax system.
When i open this in batch file (run.bat), all working good:
Raverus.FiskalizacijaDEV.EXE.exe GetInvoice "" "C:\xampp\htdocs\get\racun.xml" "C:\xampp\htdocs\get\OutInvoice.xml" true true "C:\xampp\htdocs\get\certifikat.pfx" "Pwd"
but when i open in PHP using "echo exec('run.bat');" server give me this error:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Does anybody have idea how i can resolve this? When i mannualy open batch file (in windows) all working. I use Xampp server.
The PHP user doesn't have the needed configuration or access rights.
If you are unsure which user is running your PHP script, you can use something like this to find out:
<?php
echo '<pre>';
system('set', $retval);
echo ' </pre>';
it should give out information as to which user your PHP is using. Then set up the env for that user so he can run your batch file. This might include importing the certificate for that user.

PHP - Create directory on different server

I have Wamp (server called emerald) running and Mamp running on my Mac. People register on Mamp. Emerald is basically file hosting.
Emerald connects to Mamp's mysql database, to login users. However, I want to create a directories for new registrations on Emerald using PHP.
How can I do this? I have tried using this code:
$thisdir = "192.168.1.71";
$name = "Ryan-Hart";
if(mkdir($thisdir ."/documents/$name" , 0777))
{
echo "Directory has been created successfully...";
}
But had no luck. It basically needs to connect the other server and create a directory, in the name of the user.
I hope this is clear.
You can't create directories through http. You need a filesystem connection to the remote location (a local hard disk, or a network share for example).
The easiest way that doesn't require setting up FTP, SSH or a network share would be to put a PHP script on Emerald:
<?php
// Skipping sanitation because it's only going to be called
// from a friendly script. If "dir" is user input, you need to sanitize
$dirname = $_GET["dir"];
$secret_token = "10210343943202393403";
if ($_GET["token"] != $secret_token) die ("Access denied");
// Alternatively, you could restrict access to one IP
error_reporting(0); // Turn on to see mkdir's error messages
$success = mkdir("/home/www/htdocs/docs/".$dirname);
if ($success) echo "OK"; else echo "FAIL";
and call it from the other server:
$success = file_get_contents("http://192.168.1.71/create_script.php?token=10210343943202393403&dir=HelloWorld");
echo $success; // "OK" or "FAIL"
Create a script on another server that creates the dir and call it remotely.
Make sure you have security check (+a simple password at least)
There is no generic method to access remote server filesystems. You have to use a file transfer protocol and server software to do so. One option would be SSH, which however requires some setup.
$thisdir = "ssh2.sftp://user:pass#192.168.1.71/directory/";
On Windows you might get FTP working more easily, so using an ftp:// url as directory might work.
As last alternative you could enable WebDAV (the PUT method alone works for file transfers, not creating directories) on your WAMP webserver. (But then you probably can't use the raw PHP file functions, probably needs a wrapper class or curl to utilize it.)
I know this is old but i think this might me useful, in my experience:
if(mkdir($thisdir ."/documents/name" , 0777))
doesn't work, i need to do it:
mkdir($thisdir, 0777);
mkdir($thisdir ."/documents" , 0777);
mkdir($thisdir ."/documents/name" , 0777));
hope it helps :)

How to make a file_exist from a server to the local machine?

how to test if a file exist on the current computer using the application ?
I try to put the full url at my file like this, but it doesn't work :
if(file_exists("C:/wamp/www/project/photo/".$nom_photo))
{
echo "file exist";
$extension=pathinfo("C:/wamp/www/project/photo/".$nom_photo,PATHINFO_EXTENSION);
echo "<br>";
$nom=md5($nom_photo.time().rand(0, 99999)).".".$extension;
echo $nom;
rename("C:/wamp/www/project/photo/".$nom_photo,"C:/wamp/www/project/photo/".$nom);
echo "<br>";
}
How to fix it ?
PHP operates server side and has NO ACCESS to the files on the machine running the web browser, unless they are indeed the same machine.
If you are meaning to find a way to test if a file exists on the web server, the file_exists() function you mentioned should find it. There are many reasons this might fail, including safe_mode, file permissions, and using the wrong path.
The server doesn't have any access to the clients filesystem, this would be a major security flaw.
Also javascript is sandboxed so you couldn't do it on the client side either.
The only way I can think of doing this is to get the user to download a separate application that looks for the file and reports back to the server.

Categories