Download file from url to server - php

I have this code but it's not working, can someone tell me what to do? I don't know PHP, just started to learn PHP. I'm trying to put url in form and get that file downloaded from url to my server.
$prevod = $_POST['prevod'];
$url = file_get_contents("$prevod");
$fp = fopen("prevodi/", "w");
fwrite($fp, $url);
fclose($fp);
<form action="prevod.php" method="post">
<input name="prevod" type="text"/>
<input type="submit" value="Pronađi"/>
</form>

Try this and please avoid quotes for variables
$prevod = $_POST['prevod'];
$url = file($prevod);
you have to give path before filename then it will work if it was protected then you have to access by curl
$urldata = realpath('../severname/folder/'.$prevod.'');
$fp = fopen('../foldername/subfolder','w');
$newfile = realpath('../foldername/subfolder/'. $prevod .'');
file_put_contents($newfile, $urldata);
<form action="prevod.php" method="post">
<input name="prevod" type="text"/>
<input type="submit" value="Pronađi"/>
</form>

Create prevod.php then add following code. Please create "prevodi" directory also. You can change file name by variable $with_extension. Now it is for gif file.
<?php $ch = curl_init();
$source = $_POST['prevod'];
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$with_extension="filename.gif";
$destination = "prevodi/". $with_extension;
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
?>

Related

How to transfer image file from one server to other server using curl in php? [duplicate]

with html forms we can upload a file from a client to a server with enctype="multipart/form-data", input type="file" and so on.
Is there a way to have a file already ON the server and transfer it to another server the same way?
Thanks for hints.
// WoW! This is the fastest question answering page i have ever seen!!
When the browser is uploading a file to the server, it sends an HTTP POST request, that contains the file's content.
You'll have to replicate that.
With PHP, the simplest (or, at least, most used) solution is probably to work with curl.
If you take a look at the list of options you can set with curl_setopt, you'll see this one : CURLOPT_POSTFIELDS (quoting) :
The full data to post in a HTTP "POST"
operation. To post a file,
prepend a filename with # and use the
full path. This can either be
passed as a urlencoded string like
'para1=val1&para2=val2&...' or as an
array with the field name as key and
field data as value. If value is
an array, the Content-Type header will
be set to multipart/form-data.
Not tested,but I suppose that something like this should do the trick -- or at leasthelp you get started :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/your-destination-script.php");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'file' => '#/..../file.jpg',
// you'll have to change the name, here, I suppose
// some other fields ?
));
$result = curl_exec($ch);
curl_close($ch);
Basically, you :
are using curl
have to set the destination URL
indicate you want curl_exec to return the result, and not output it
are using POST, and not GET
are posting some data, including a file -- note the # before the file's path.
you can do it in the same way. Just this time your server who received the file first is the client and the second server is your server.
Try using these:
For the webpage on the second server:
<form>
<input type="text" name="var1" />
<input type="text" name="var2" />
<input type="file" name="inputname" />
<input type="submit" />
</form>
And as a script to send the file on the first server:
<?php
function PostToHost($host, $port, $path, $postdata, $filedata) {
$data = "";
$boundary = "---------------------".substr(md5(rand(0,32000)),0,10);
$fp = fsockopen($host, $port);
fputs($fp, "POST $path HTTP/1.0\n");
fputs($fp, "Host: $host\n");
fputs($fp, "Content-type: multipart/form-data; boundary=".$boundary."\n");
// Ab dieser Stelle sammeln wir erstmal alle Daten in einem String
// Sammeln der POST Daten
foreach($postdata as $key => $val){
$data .= "--$boundary\n";
$data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
}
$data .= "--$boundary\n";
// Sammeln der FILE Daten
$data .= "Content-Disposition: form-data; name=\"{$filedata[0]}\"; filename=\"{$filedata[1]}\"\n";
$data .= "Content-Type: image/jpeg\n";
$data .= "Content-Transfer-Encoding: binary\n\n";
$data .= $filedata[2]."\n";
$data .= "--$boundary--\n";
// Senden aller Informationen
fputs($fp, "Content-length: ".strlen($data)."\n\n");
fputs($fp, $data);
// Auslesen der Antwort
while(!feof($fp)) {
$res .= fread($fp, 1);
}
fclose($fp);
return $res;
}
$postdata = array('var1'=>'test', 'var2'=>'test');
$data = file_get_contents('Signatur.jpg');
$filedata = array('inputname', 'filename.jpg', $data);
echo PostToHost ("localhost", 80, "/test3.php", $postdata, $filedata);
?>
Both scripts are take from here: http://www.coder-wiki.de/HowTos/PHP-POST-Request-Datei
This is a simple PHP script I frequently use for while moving big files from server to servers.
set_time_limit(0); //Unlimited max execution time
$path = 'newfile.zip';
$url = 'http://example.com/oldfile.zip';
$newfname = $path;
echo 'Starting Download!<br>';
$file = fopen ($url, "rb");
if($file) {
$newf = fopen ($newfname, "wb");
if($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
echo '1 MB File Chunk Written!<br>';
}
}
if($file) {
fclose($file);
}
if($newf) {
fclose($newf);
}
echo 'Finished!';
Ex. if you have a file called mypicture.gif on server A and want to send it to server B, you can use CURL.
Server A reads the content as a String.
Post the string with CURL to Server B
Server B fetches the String and stores it as a file called mypictyre-copy.gif
See http://php.net/manual/en/book.curl.php
Some sample PHP code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"#/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
?>
It is Very easy.This is very easy & simple code
<html>
<body>
<?php
/*the following 2 lines are not mandatory but we keep it to
avoid risk of exceeding default execution time and mamory*/
ini_set('max_execution_time', 0);
ini_set('memory_limit', '2048M');
/*url of zipped file at old server*/
$file = 'http://i.ytimg.com/vi/Xp0DOC6nW4E/maxresdefault.jpg';
/*what should it name at new server*/
$dest = 'files.jpg';
/*get file contents and create same file here at new server*/
$data = file_get_contents($file);
$handle = fopen($dest,"wb");
fwrite($handle, $data);
fclose($handle);
echo 'Copied Successfully.';
?>
</body>
</html>
Type your Url in this variable - $file ="http://file-url"
Type your file save as in hosting sever- $dest = 'files.jpg';
The easiest way to transfer file one server into another server.
First, need to enable ssh2 php extension and use the following code
$strServer = '*.*.*.*';
$strServerPort = '*';
$strServerUsername = '*****';
$strServerPassword = '****';
**//connect to server**
$resConnection = ssh2_connect($strServer, $strServerPort);
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword))
{
//Initialize SFTP subsystem
$resSFTP = ssh2_sftp($resConnection);
$resFile = fopen("ssh2.sftp://{$resSFTP}/FilePath/".$filename, 'w');
$srcFile = fopen($path.$filename, 'r');
$writtenBytes = stream_copy_to_stream($srcFile, $resFile);
fclose($resFile);
fclose($srcFile);
}

Sending a file to a webservice with XML using cURL corrupts it

So I have some code that sends a career application to a webservice which then emails the file to the hr department as an attachment along with other elements in the form. All of the parts except for the file gets emailed as desired. The file gets uploaded to the server without being corrupted. But the resulting email attachment ends up being corrupted.
The problem is; the file ends abruptly before reaching EOF. Let's say it is a pdf file when I open both the original and the reduced size file in a text editor I see that the beginnings are identical until one of them suddenly ends. One of them is about 1MB and the corrupt one is about 600kB.
I have tried sending files smaller(4kB) than the resulting corrupt file but that file also gets corrupt in the same way. The resulting file is about 1kB.
The xml response I get says:
<?xml version="1.0" encoding="utf-8"?><SENDEMLRSP><RTCD>1</RTCD><EXP>OK</EXP><RSP_LIST><RSP><MSGID>0</MSGID><EID /><RESULT>Invalid length for a Base-64 char array or string.</RESULT></RSP></RSP_LIST></SENDEMLRSP>
It is this part that is of interest:
<RESULT>Invalid length for a Base-64 char array or string.</RESULT>
I have prepared a small form with only a file upload for testing purposes.
Here is the HTML:
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Here is the relevant PHP code:
if(isset($_FILES['file']['name']))
{
echo ($_FILES['file']['name']);
echo ($_FILES['file']['tmp_name']);
$target = $_FILES['file']['name'];
move_uploaded_file( $_FILES['file']['tmp_name'], $target);
$rawdata = file_get_contents($target);
$data = urldecode($rawdata);
$data = base64_encode($rawdata);
//error_log('uploadconvertscope');
$iletisimrcpt = '<RCPT>
<TA>someemail#address.com</TA>
<MSG>kgsg</MSG>
<SBJ>'. strlen($rawdata).'</SBJ>
<OBOE>'.OBOE.'</OBOE>
<OBON>'.OBON.'</OBON>
<ATT_LIST><ATT><FN>'.$_FILES['file']['name'].'</FN><DATA>'.$data.'</DATA></ATT></ATT_LIST>
</RCPT>';
$request = '<?xml version="1.0" encoding="utf-8"?>
<SENDEML>
<VERSION>1.0</VERSION>
<TOKEN>'.$token.'</TOKEN>
<JID>'.JOBID.'</JID>
<MSG>Kariyar Basvuru isteði baþarýyla yerleþtirildi.</MSG>
<SBJ>Kariyar Basvuru</SBJ>
<RCPT_LIST>
'.$iletisimrcpt.'
</RCPT_LIST>
</SENDEML>';
error_log($request );
$params = array('data' => $request);
$response = processRequest(EML_URL, $params);
error_log($response );
$xml = new SimpleXmlElement($response);
}
The processRequest function works with the rest of the message. So it may not be the problem but here is the code:
<?php
function processRequest($url, $params) {
if(!is_array($params))
return false;
$post_params = "";
foreach($params as $key => $val) {
$post_params .= $post_params?"&":"";
$post_params .= $key."=".$val;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false); // 'true', for developer testing purpose
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
$data = curl_exec($ch);
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
return $data;
}
?>
The file when read as a string between the looks like AHFAY3453GAW//LONG RANDOM STRING OF CHARACTERS//== it always ends with two "==" signs if that means anything.
I am really stumped as the files get uploaded OK with this C# code:
byte[] attach1 = File.ReadAllBytes(#"C:\Users\user\Downloads\amb.pdf");
string attach = Convert.ToBase64String(attach1);
EmlRequest.SetConnectionInformation("someapi.com", "admin", "password");
EmlRequest eml=new EmlRequest(){ MessageJobId="DASFA1SDFAWEFA4X2==" };
eml.Recipients.Add(new ApiEmlRecipient() { TargetAddress = "email#address.com" ,ToName="name",Message="xxx",Subject="subject"});
eml.Recipients[0].Attachments.Add(new ApiEmlAttachment() { FileName = "abm.pdf", Data = attach });
eml.Send();
Which is almost identical to it's PHP version.
I figured this out quite some time ago but only got down to writing an answer.
So the problem was that the "+" signs in the string were replaced by spaces.
This bit was responsible:
$rawdata = file_get_contents($target);
$data = urldecode($rawdata);
$data = base64_encode($rawdata);
I changed it to this:
$rawdata = file_get_contents($_FILES['uploadedfile']['tmp_name']);
$data = base64_encode($rawdata);
$data = urlencode($data);
Now it works.

Sending File with cURL

I've sent some post data with cURL and am now trying to send a file, getting lost along the way. I'm using a form with a file input. Then would like cURL to send it off to my server. Here is my upload page.
<form action="curl_page.php" method="post" enctype="multipart/form-data">
Filename: <input type="file" name="file" id="file" /> <br />
<input type="submit" name="submit" value="Submit" />
</form>
Here is my curl page with some issues.
<?php
$tmpfile = $_FILES['file']['tmp_name'];
$filename = basename($_FILES['file']['name']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://my_server/file_catch.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
?>
The file_catch.php on my server looks like this.
<?php
$folder = "audio/";
$path = $folder . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Thanks for any help!
You are not sending the file that you got through the post request. Use the below code for posting the file through CURL request.
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)
curl_exec($ch);
For more reference check the below link
Send file via cURL from form POST in PHP

How to get a file from another server and rename it in PHP

I was looking for a way to perform a number of tasks in PHP
Get a file from another server
Change the file name and extention
Download the new file to the end user
I would prefer a method that acts as a proxy server type thing, but a file download would be fine
Thanks in advance
Try this
<?php
$url = 'http://www.example.com/a-large-file.zip';
$path = '/path-to-file/a-large-file.zip';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
file_put_contents($path, $data);
?>
After you save rename the file with whatever name you need
Refer this
http://www.php.net/manual/en/ref.curl.php
See the example at http://www.php.net/manual/en/function.curl-init.php
This grabs the data and outputs it straight to the browser, headers and all.
If you have allow_url_fopen set to true:
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
Else use cURL:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
I use something like this:
<?php
$url = 'http://www.some_url.com/some_file.zip';
$path = '/path-to-your-file/your_filename.your_ext';
function get_some_file($url, $path){
if(!file_exists ( $path )){
$fp = fopen($path, 'w+');
fwrite($fp, file_get_contents($url));
fclose($fp);
}
}
?>

IMGUR file upload via PHP and cURL

I'm trying to upload an image to IMGUR via PHP.
This is the code:
<?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'mykey' => IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
This is the error message I receive:
Warning: fopen(image.jpg) failed to open stream: No such file or directory
I don't understand the part: $filename = "image.jpg";
Where does the filename come from since it's a base64 generated string?
Thanks,
Bob
That warning is because fopen is trying to read in the file image.jpg from the directory from which your script is running.
A good example on how to transfer a file through curl can be seen here
Send file via cURL from form POST in PHP
Where they have $localFile = $_FILES[$fileKey]['tmp_name']; you would put $localFile = '/path/to/image.jpg'; As well as change the server info and add in any other variables you may need to pass to imgur.
Change line 1 from:
$filename = "image.jpg";
To:
$filename = $_FILES['uploaded_file']['tmp_name'];
Then, to post... I recommend a form similar to this:
<form enctype="multipart/form-data" method="post" action="upload.php" target="my_iframe">
Choose your file here:
<input name="uploaded_file" type="file"/>
<input type="submit" value="Upload It"/>
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<script language="JavaScript">
<!--
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
}
document.getElementById(id).height= (newheight) + "px";
document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>
<IFRAME name="my_iframe" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>
If you put all your php into upload.php and then have that form on a page in the same directory, it's pretty close to being functional... Except you don't yet have an API_KEY in your source.
You can get an API KEY here: https://imgur.com/register/api_anon
In the end your php should look like this:
<?
if( isset($_FILES['uploaded_file']) )
{
$IMGUR_API_KEY = 'u432ewriuq3oirefuie'; //put your api key here
$filename = $_FILES['uploaded_file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
//$data is file data
$pvars = array('image' => base64_encode($data), 'key' => $IMGUR_API_KEY);
#$pvars = array('key' => $IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
#curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/gallery.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
$xmlsimple = new SimpleXMLElement($xml);
echo '<img height="180" src="';
echo $xmlsimple->links->original;
echo '">';
curl_close ($curl);
}
?>

Categories