I have 2 servers. And i want to transfer a file from one server to an other with cURL. Can anyone show me a good example of this ? What options should I give to cURL .....
Thx.
Plenty of resources available, here are a couple:
http://dtbaker.com.au/random-bits/uploading-a-file-using-curl-in-php.html
http://www.phpclasses.org/package/3753-PHP-Upload-files-via-HTTP-POST-using-Curl.html
Never used them nor had a need to. But should help you get started.
sender.php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// true to return the transfer as a string of the return value
// of 'curl_exec' instead of outputting it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, 'http://localhost/test/curl/receiver.php');
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
'euro' => '#eurodance.pls',
'flush' => '#flush_next.png',
'first_name' => 'Vadim'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
print_r($response);
receiver.php
if(isset($_FILES)){
$temp_file_name = $_FILES['euro']['tmp_name'];
$original_file_name = $_FILES['euro']['name'];
// Find file extention
$ext = explode ('.', $original_file_name);
$ext = $ext [count ($ext) - 1];
// Remove the extention from the original file name
$file_name = str_replace ($ext, '', $original_file_name);
$new_name = '_'.$file_name . $ext;
//echo $file_name ." ". $ext;
if (move_uploaded_file ($temp_file_name, $new_name)) {
echo "success";
} else {
echo "error";
}
}
if(isset($_FILES)){
$temp_file_name = $_FILES['flush']['tmp_name'];
$original_file_name = $_FILES['flush']['name'];
// Find file extention
$ext = explode ('.', $original_file_name);
$ext = $ext [count ($ext) - 1];
// Remove the extention from the original file name
$file_name = str_replace ($ext, '', $original_file_name);
$new_name = '_'.$file_name . $ext;
//echo $file_name ." ". $ext;
if (move_uploaded_file ($temp_file_name, $new_name)) {
echo "success";
} else {
echo "error";
}
}
Using cURL seems like using the wrong tool for the job(ie when you have a hammer every problem looks like a nail) based on what you have given, why not look at SCP/SFTP or even rsync if the former is not flexible enough. If not ,you would have to host the file on your source server and initiate cURL to request the file(ie over http)
Related
I have a problem with Joining 2 functions, So I am use https://github.com/spatie/pdf-to-image - this function for convert uploaded pdf(s) to image(s). this is working fine, but this function uploads converted images to the local directory, but i want to change it and save converted images to the yandex disk not a local directory. my function with curl for upload files to yandex disk working fine too, but i dont know how to join this 2 functions,
I want to change $pdf->setPage($pageNumber)->saveImage($pageNumber . '.jpg'); to uploadtoyandexdisk("folder", "", $pageNumber . '.jpg'); for uploading to yandex disk, can you help ?
//edited code
if(!empty($_FILES["fileToUpload"])){
error_reporting(E_ALL);
ini_set("display_errors", 1);
function uploadtoyandexdisk($folder, $file, $name) {
if(empty($file)){
$filename = $name;
$filepath = $_FILES["fileToUpload"]["tmp_name"];
} else{
$filename = $name;
$filepath = $file;
}
$yandexusername = "username";
$yandexpassword = "password";
$credentials = array($yandexusername,$yandexpassword);
$filesize = filesize($filepath);
$fh = fopen($filepath, 'r');
$remoteUrl = 'https://webdav.yandex.ru/uploads/'.$folder.'/';
$ch = curl_init($remoteUrl . $filename);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, implode(':', $credentials));
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $fh);
curl_setopt($ch, CURLOPT_INFILESIZE, $filesize);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response=curl_exec($ch);
fclose($fh);
echo $response;
}
include "../inc/extensions/pdftoimage/Pdf.php";
$pdf = new Spatie\PdfToImage\Pdf($_FILES["fileToUpload"]["tmp_name"]);
foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) {
$pdf->setCompressionQuality(50);
$pdf->setPage($pageNumber)
->saveImage($pageNumber . '.jpg');
$imgdata = $pdf->setPage($pageNumber)->getImageData($pageNumber . '.jpg');
uploadtoyandexdisk("uploads", $imgdata, $pageNumber . '.jpg');
}
}
An easy look at the source code helps to solve the problem: while saveImage is used to save the converted data to a file, you can call getImageData with the same argument to get the raw data. If you post that raw data to the Yandex server instead of reading data from a file, you should be done
I need to give my images an extension, depending on their type and also create a completely new name for them. Can I get the extension before I send the file to the server?
$_POST['image'] is a URL of an image. $new_name is supposed to be added while running the switch.
$image = $_POST['image'];
$ch = curl_init($image);
curl_setopt($ch, CURLOPT_HEADER, 0);
$imagedata = curl_exec($ch);
list($width, $height, $type) = getimagesize($filename);
switch ($type) {
case 1: ....... //Give the filename a .gif extension and so on for every filetype
}
$fp = fopen('../images/' . $new_name, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_close($ch);
fclose($fp);
!FOUND ANSWER! (sorry if I'm answering my own question wrong (in means of simply "editing" the question), comment on how to do it correctly, if I'm wrong ;)
I simply need to run the cURL function 2 times, but with different names. The first one simply gets me the info about the file, and the second one saves it wit the $new_name
$image = $_POST['image'];
$ch = curl_init($image); curl_setopt($ch, CURLOPT_HEADER, 0);
$imagedata = curl_exec($ch); $info = curl_getinfo($ch,
CURLINFO_CONTENT_TYPE); curl_close($ch);
if($info == "image/jpeg") //Running a code that will give the image an
appropriate extension...
$cf = curl_init($image); $fp = fopen('../images/' . "image.jpg",
'wb'); curl_setopt($cf, CURLOPT_FILE, $fp); curl_exec($cf);
curl_close($cf); fclose($fp);
Hi i want to save the image from a web url to my local folder .below is my code
<?php
$url = 'http://dev.aviesta.com.mx/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/r/bridal-shoes1.jpg';
$saveto = '/var/www/';
function grab_image($url,$saveto){
$url = 'http://dev.aviesta.com.mx/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/r/bridal-shoes1.jpg';
$saveto = '/var/www/';
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
?>
i have try this code but it doesn't work for me please suggest me some idea
in php.ini file made one change as below
allow_url_fopen = On
and uncomment following line.
extension=php_curl.dll
OR
$img = file_get_contents('http://graph.facebook.com/'.$response['user_id'].'/picture?type=large');
$image_name = time().".jpg";
/* putting image into the orignal images folder to keep the original image */
$upload_path = "img".DS."origional_images".DS."";
file_put_contents("img".DS."origional_images".DS.$image_name, $img);
tried code
i have tried below code according to the comment you have posted.
unfortunatly in your comment you have extra ' at the end of url link get rid of that extra ' and it will work as expected.
$img = file_get_contents('http://dev.aviesta.com.mx/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/r/bridal-shoes1.jpg');
$image_name = time().".jpg";
$upload_path = "img/";
file_put_contents("img/".$image_name, $img);
Why use cURL?
$url = 'http://dev.aviesta.com.mx/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/r/bridal-shoes1.jpg';
$saveto = '/var/www/image_' . time() . '.jpg';
grab_image($url, $saveto);
function grab_image($url, $saveto) {
// Assumes a correctly encoded URL
$image = file_get_contents($url);
if (!$image)
return false;
file_put_contents($saveto, $image);
if (!file_exists($saveto))
return false;
return true;
}
Also be sure to check that the web server has permission to write to /var/www/
Use $fp = fopen($saveto, 'wb');.
i am using this curl class for saving the file -->
class CurlHelper
{
/**
* Downloads a file from a url and returns the temporary file path.
* #param string $url
* #return string The file path
*/
public static function downloadFile($url, $options = array())
{
if (!is_array($options))
$options = array();
$options = array_merge(array(
'connectionTimeout' => 5, // seconds
'timeout' => 10, // seconds
'sslVerifyPeer' => false,
'followLocation' => false, // if true, limit recursive redirection by
'maxRedirs' => 1, // setting value for "maxRedirs"
), $options);
// create a temporary file (we are assuming that we can write to the system's temporary directory)
$tempFileName = tempnam(sys_get_temp_dir(), '');
$fh = fopen($tempFileName, 'w');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FILE, $fh);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $options['connectionTimeout']);
curl_setopt($curl, CURLOPT_TIMEOUT, $options['timeout']);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $options['sslVerifyPeer']);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $options['followLocation']);
curl_setopt($curl, CURLOPT_MAXREDIRS, $options['maxRedirs']);
curl_exec($curl);
curl_close($curl);
fclose($fh);
return $tempFileName;
}
}
$url = 'http://graph.facebook.com/shashankvaishnav/picture';
$sourceFilePath = CurlHelper::downloadFile($url, array(
'followLocation' => true,
'maxRedirs' => 5,
));
this above code will give me the temporary url in $sourceFilePath variable now i want to store that image in my image folder. I am stuck here...please help me in this...thank you in advance.
There is a pretty easy option for this:
$url = 'http://graph.facebook.com/shashankvaishnav/picture';
$data = file_get_contents($url);
$fileName = 'fb_profilepic.jpg';
$file = fopen($fileName, 'w+');
fputs($file, $data);
fclose($file);
You don´t even need anything else then.
Or if file_get_contents is disabled (usually it isn´t), this should also work:
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://graph.facebook.com/shashankvaishnav/picture');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$fileName = 'fb_profilepic.jpg';
$file = fopen($fileName, 'w+');
fputs($file, $data);
fclose($file);
Edit: This is not possible anymore, since you can´t use the username for API calls anymore. You have to use an (App Scoped) ID after authorizing a User with the Facebook API instead of the username.
$filename = 'abcd.jpg';
$to = 'image/'.$filename;
if(copy($sourceFilePath,$to))
echo 'copied';
else
echo 'error';
$profile_Image = 'http://graph.facebook.com/shashankvaishnav/picture';
$userImage = $picturtmp_name . '.jpg'; // insert $userImage in db table field.
$savepath = '/images/';
insert_user_picture($savepath, $profile_Image, $userImage);
function insert_user_picture($path, $profile_Image, $userImage) {
$thumb_image = file_get_contents($profile_Image);
$thumb_file = $path . $userImage;
file_put_contents($thumb_file, $thumb_image);
}
$fbprofileimage = file_get_contents('http://graph.facebook.com/senthilbp/picture/');
file_put_contents('senthilbp.gif', $fbprofileimage);
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);
}
}
?>