PHP - Loop cURL with increase id of URL - php

with the following code a name with an ID (each name in the gnd can be addressed by an ID) is received via the GND interface. This works.
Now i want to get many names at the same time with a cURL loop. The ID of the URL must always be increased by one and the cURL request must loop. How can I do this?
With this Code i receive for example names from the GND database
<?php
header('Content-type: text/html; charset=utf-8');
$User_Agent = 'Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0';
$url = "http://hub.culturegraph.org/entityfacts/118600001";
$request_headers = [];
$request_headers[] = 'Accept: application/json';
$request_headers[] = 'charset=utf-8';
$request_headers[] = 'Content-Type: application/json; charset=utf-8';
$request_headers[] = 'Accept-Encoding: gzip, deflate, identity';
$request_headers[] = 'Accept-Language: de,en-US;q=0.7,en;q=0.3';
for ($i = 1; $i <= 10; $i++)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $User_Agent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, "");
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch);
$data = json_decode($result, true);
if ($code == 200) {
$data = json_decode($result, true);
echo 'Erfolg';
} else {
$error = $data['Error'];
echo 'Beim anfordern der GND-Daten ist ein Fehler aufgetreten: Fehlercode ' . $error;
echo ' Zurueck<br />';
}
var_dump($data['preferredName']);
Result for URL with ID 118600001 = Gerhardt von Reutern
But how must the code be adapted, so that also the names of the URL's 118600002, 118600003 and so on are output? So as often as it is specified. Be it 100 or 1000 times.

change your $url variable to something like $base_url which is the url without the ID
$base_url = "http://hub.culturegraph.org/entityfacts/";
Then in your for loop you do:
$ch = curl_init($base_url . (118600001 + $i));
this rule can be removed, this is not necessary:
curl_setopt($ch, CURLOPT_URL, $url);
You should also handle the response inside the for loop, else you will only see the last person's name, after an incredibly long load time.

Related

'CURLE_URL_MALFORMAT' but all the syntax seems to be ok

I have an issue with a cUrl. Recently, I have found that the problem is in the syntax of the curl, because when I dump the request I want to execute and put it in PostMan it works, but the function inside my code doesn't and returns 3: 'CURLE_URL_MALFORMAT'. For information my curl version is 7.79.1
I have tried some different approaches with CURLOPT_RETURNTRANSFER, CURLOPT_POST and etc, but it does not work...
Here is my function:
private function cUrl_CreateContactFastFood($merchant_token, $arr)
{
$status = "active";
$Contact_name = $arr["customerName"];
$Contact_email = '';
if($Contact_email=='') {
$Contact_email= 'FastFoodCustomer#ttt.com';
}
$Contact_phone = $arr["phoneNumber"];
$Contact_address = $arr["endAddressResolved"];
$url = 'http://dostavka-bg.com/api_services/insert_contact';
$curl_params = '?keys=f74192da825962d3b1c2b2aa616ab68b&merchant_token='.$merchant_token.'&name='.$Contact_name.'&email='.$Contact_email.'&phone='.$Contact_phone.'&address='.$Contact_address.'&status='.$status;
$ch = curl_init();
$headers = array(
'Accept: */*',
'User-Agent: ',
'Accept-Encoding: gzip, deflate, br',
'Host: dostavka-bg.com',
'Connection: keep-alive'
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url.$curl_params);
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
}
Here is the solved problem:
private function cUrl_CreateContactFastFood($merchant_token, $arr)
{
$status = "active";
$Contact_name = $arr["customerName"];
$Contact_email = '';//$arr["customer"]["invoicing_details"]["company_address"];
if($Contact_email==''){
$Contact_email= 'FastFoodCustomer#ttt.com';
}
$Contact_phone = $arr["phoneNumber"];
$Contact_address = $arr["endAddressResolved"];
$url = 'http://dostavka-bg.com/api_services/insert_contact';
$curl_params = '?keys=f74192da825962d3b1c2b2aa616ab68b&merchant_token='.urlencode($merchant_token).'&name='.urlencode($Contact_name).
'&email='.urlencode($Contact_email).'&phone='.urlencode($Contact_phone).'&address='.urlencode($Contact_address).'&status='.urlencode($status);
$ch = curl_init();
$headers = array(
'Accept: */*',
'User-Agent: ',
'Accept-Encoding: gzip, deflate, br',
'Host: dostavka-bg.com',
'Connection: keep-alive'
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url.$curl_params);
curl_setopt($ch, CURLOPT_POST, 1);
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$info = curl_version();
curl_close($ch);
return true;
}
The URL you're passing includes several query string parameters, only some of which are shown in your example, but some of which probably include punctuation or other characters which aren't allowed in URLs. Those need to be correctly encoded by either:
Calling urlencode or rawurlencode on each parameter as you build up the query string.
Using http_build_query to format it all for you, rather than manually concatenating the parts.

Misspelled RegEx in PHP function preg_match()

This is a question about PHP, cURL, preg_match(), RegEx, and Instagram.
I'm trying to write a cURL PHP code that logs-in to Instagram, and then access content only available to a validated (logged-in) user. In this question there's an interesting code just for that.
I copy-pasted the code, which is the following:
<?php
$username = "yourname";
$password = "yourpass";
$useragent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36";
$cookie=$username.".txt";
#unlink(dirname(__FILE__)."/".$cookie);
$url="https://www.instagram.com/accounts/login/?force_classic_login";
$ch = curl_init();
$arrSetHeaders = array(
"User-Agent: $useragent",
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: deflate, br',
'Connection: keep-alive',
'cache-control: max-age=0',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$page = curl_exec($ch);
curl_close($ch);
// try to find the actual login form
if (!preg_match('/<form method="POST" id="login-form" class="adjacent".*?<\/form>/is', $page, $form)) {
die('Failed to find log in form!');
}
$form = $form[0];
// find the action of the login form
if (!preg_match('/action="([^"]+)"/i', $form, $action)) {
die('Failed to find login form url');
}
$url2 = $action[1]; // this is our new post url
// find all hidden fields which we need to send with our login, this includes security tokens
$count = preg_match_all('/<input type="hidden"\s*name="([^"]*)"\s*value="([^"]*)"/i', $form, $hiddenFields);
$postFields = array();
// turn the hidden fields into an array
for ($i = 0; $i < $count; ++$i) {
$postFields[$hiddenFields[1][$i]] = $hiddenFields[2][$i];
}
// add our login values
$postFields['username'] = $username;
$postFields['password'] = $password;
$post = '';
// convert to string, this won't work as an array, form will not accept multipart/form-data, only application/x-www-form-urlencoded
foreach($postFields as $key => $value) {
$post .= $key . '=' . urlencode($value) . '&';
}
$post = substr($post, 0, -1);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $page, $matches);
$cookieFileContent = '';
foreach($matches[1] as $item)
{
$cookieFileContent .= "$item; ";
}
$cookieFileContent = rtrim($cookieFileContent, '; ');
$cookieFileContent = str_replace('sessionid=; ', '', $cookieFileContent);
$oldContent = file_get_contents(dirname(__FILE__)."/".$cookie);
$oldContArr = explode("\n", $oldContent);
if(count($oldContArr))
{
foreach($oldContArr as $k => $line)
{
if(strstr($line, '# '))
{
unset($oldContArr[$k]);
}
}
$newContent = implode("\n", $oldContArr);
$newContent = trim($newContent, "\n");
file_put_contents(
dirname(__FILE__)."/".$cookie,
$newContent
);
}
$arrSetHeaders = array(
'origin: https://www.instagram.com',
'authority: www.instagram.com',
'upgrade-insecure-requests: 1',
'Host: www.instagram.com',
"User-Agent: $useragent",
'content-type: application/x-www-form-urlencoded',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: deflate, br',
"Referer: $url",
"Cookie: $cookieFileContent",
'Connection: keep-alive',
'cache-control: max-age=0',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
sleep(5);
$page = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $page, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie1);
$cookies = array_merge($cookies, $cookie1);
}
var_dump($page);
curl_close($ch);
?>
You must, of course, change the $username's value from yourname to an actual username, and $password's value from yourpass to the corresponding password of the username. Also, I don't think this code will work if 2-step authentication is enabled in the account of the user (ie., for example, a MMS is sent to the linked phone number, or an email is sent to the linked email), therefore, 2-step authentication must be disabled in the user's account settings.
However, when I run this PHP script in Chrome, I get the message Failed to find log in form!, meaning that, on line 35, the pattern (written as a RegEx) /<form method="POST" id="login-form" class="adjacent".*?<\/form>/is wasn't found in the variable $page, which at the same time is basically the HTML of the classic Instagram login page.
It's weird that such pattern is not being found, because there's indeed a HTML named <form method="POST" id="login-form" class="adjacent" (to check it yourself, go to the login page, press Ctrl+U, then Ctrl+F, and then paste the previous pattern). So, I assume this is because the RegEx is somehow misspelled. Is that correct?
Even weirder, I tested it on the page RegEx101.com, and the test was successful. So, why is PHP saying the pattern wasn't found?
The idea is that the pattern can be found in the code of the original question, so that I can log-in automatically/programmatically. Keep in mind that more preg_match() functions are used later in the code, eg. on lines 42, 48 (preg_match_all()), 70 (preg_match_all()), and 137 (preg_match_all()).
EDIT: I realized that if I add var_dump($page); just before line 35, I get bool(false) (in other words, the HTML output is bool(false) Failed to find log in form!). I think this is the reason why the code returns the message Failed to find log in form!. However, why is the value of $page returning that?

Cannot extract the data from the website using PHP cURL

I am working on a project which needs to get the data from other webpage:
https://eth.ethfans.org/#/miner?0x2998850087633a4806191960c94ed535d97da598
I am trying to use the function cRUL:
<?php
$url = "https://eth.ethfans.org/#/miner?0x2998850087633a4806191960c94ed535d97da598";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>
However, I can only get the layout of the site, but I cannot get the data inside.
Can anyone help for this ?
Thanks in Advance.
Regards,
Alex
Use str_get_html to fetch the data from the layout:
$get_html = str_get_html($contents);
Example:
function check()
{
$url = "https://stackoverflow.com/questions/49248329/cannot-extract-the-data-from-the-website-using-php-curl";
$get_html = $this->get_curl($url);
#print_r($get_html); exit;
$get_html = str_get_html($get_html);
$fb = NULL;
foreach ($get_html->find('a') as $v) { // you can get what data from the layout
if(strpos($v->href, 'facebook'))
{
echo $fb = $v->href;
echo "\n";
break;
}
}
unset($get_html);
}
public function get_curl($url)
{
ob_start();
$ch = curl_init($url);
$headers = [
'Accept-Language: en-US,en;q=0.5',
'Cache-Control: no-cache',
'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/51.0',
];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_URL, $url);
$response = curl_exec ($ch);
curl_close ($ch);
ob_end_flush();
return $response;
}
you're hitting the wrong url, the page you're hitting only contains the layout and the javascript required to fetch the actual data, then the javascript fetch the data from https://eth.ethfans.org/api/page/miner?value=2998850087633a4806191960c94ed535d97da598 , so, do as the javascript does, and fetch that url.

How to generate Facebook User Access Token using curl

I am doing a project where I need to import Facebook Page feeds. For accessing Facebook page feeds, I need a page_access_token and to generate page_access_token I need User access token.
Here my question is
1.How to generate this User_access_token using CURL ? Most of the solution requires APP_KEY & APP_SECRET. Is it not possible to get user_access_token without any APP ?
Once I get the User_access_token how do I use it to get Page access Token using CURL.
You can´t get ANY Token without an App, but you don´t need to program anything in order to get a User Token. These articles explain everything in detail:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
https://developers.facebook.com/docs/facebook-login/
For example, you can use the API Explorer to select your App and generate User Tokens.
Wrong question, No tokens are needed
I just tried it and it took me less than 5 minutes, never having scraped FB in the past. I saved the page to my Server and brought up the page using my URL and it looked just like if I were on FB.
If a Browser can load the page with JavaScript disabled, then you can too.
You have to use https://m.facebook.com/, JavaScript is not required on their mobile site.
What you want to do, is not difficult at all.
Just go there in your Browser and copy the cookies key values into the Cookie: HTTP request header. Mine are x'ed out.
<?php
$request = array();
$request[] = 'Host: m.facebook.com';
$request[] = 'User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:39.0) Gecko/20100101 Firefox/39.0';
$request[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$request[] = 'Accept-Language: en-US,en;q=0.5';
$request[] = 'Accept-Encoding: gzip, deflate';
$request[] = 'DNT: 1';
$request[] = 'Cookie: datr=x; fr=x; lu=x s=xx; csm=x; xs=xx; c_user=x; p=-2; act=x; presence=x; noscript=1';
$request[] = 'Connection: keep-alive';
$request[] = 'Pragma: no-cache';
$request[] = 'ache-Control: no-cache';
$url = 'https://m.facebook.com/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_ENCODING,"");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILETIME, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 100);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT,100);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request);
$data = curl_exec($ch);
if (curl_errno($ch)){
$data .= 'Retreive Base Page Error: ' . curl_error($ch);
}
else {
$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$responseHeader = substr($data,0,$skip);
$data= substr($data,$skip);
$info = curl_getinfo($ch);
$info = var_export($info,true);
}
while(true){ // get cookies from response header
$s = strpos($head,'Set-Cookie: ',$e);
if (!$s){break;}
$s += 12;
$e = strpos($head,';',$s);
$cookie = substr($head,$s,$e-$s) ;
$s = strpos($cookie,'=');
$key = substr($cookie,0,$s);
$value = substr($cookie,$s);
$cookies[$key] = $value;
}
$cookie = ''; // format cookies for next request header
$show = '';
$head = '';
$delim = '';
foreach ($cookies as $k => $v){
$cookie .= "$delim$k$v";
$delim = '; ';
}
$fp = fopen("fb.html",'w');
fwrite($fp,"$data\n$info\n$responseHeader");
fclose($fp);
readfile('fb.html');

php curl not saving file to location

I have been searching for an answer for this all day, but with no luck!
I want to download/copy an image from the web to a location on my server, The code below doesn't seam to throw any errors other than the image is just not saving to the required or any directory.
As you can see I am using cURL to get the image and the variable $contents is returning true (1) so I am assuming the script works but I am actually missing something.
Many thanks in advance for your help. :-)
$dir = URL::base() . "/img/products/";
$imgSrc = "an image on the web";
$file = fopen($dir, "wb");
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$ch = curl_init($imgSrc);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file); // location to write to
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
$contents = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
fclose($lfile);
if ($curl_errno > 0)
{
Log::write("CURL", "cURL Error (".$curl_errno."): ".$curl_error);
}
else
{
Log::write("CURL", "Data received: " . $contents);
}
return;
Provide the file the writing access to PHP FILE using curl to store the contents. This can be done in three ways:
If you have the terminal access then use chmod to provide the writing access
If you have the CPanel access then use directory explorer then provide the writing access to the file by changing file properties.
You must have the access to FTP and change the file access attributes and provide the writing access.
Don't use curl.
If all you need to do is download an image, go for "file_get_contents" instead.
It's dead easy:
$fileContents = file_get_contents("https://www.google.com/images/srpr/logo4w.png");
File::put('where/to/store/the/image.jpg', $fileContents);
function saveImageToFile($image_url,$output_filename)
{
$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); //Saves over files
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
Your problem is quite simple, and I have no idea how everyone else ignored it. It is Laravel-specific. Your $dir variable returns an HTTP resource identifier. What you need is a filesystem identifier.
For laravel, change your URL::to() to path("public") to tell Laravel to stop using HTTP URIs and instead take the local path to the public folder (/your/laravel/setup/path/public/).
code
$dir = path("public") . "img/products/";
$imgSrc = "an image on the web";
$file = fopen($dir . substr($imgSrc,strrpos("/",$imgSrc)+1), "wb");
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$ch = curl_init($imgSrc);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file); // location to write to
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
$contents = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0)
{
Log::write("CURL", "cURL Error (".$curl_errno."): ".$curl_error);
}
else
{
Log::write("CURL", "Data received: " . $contents);
fwrite($file,$contents);
fclose($file);
}
return;
OK, finally got it all working and here is the code if anyone else ever tries to do the same sort of thing!
I was missing these parts:
$dir = $_SERVER['DOCUMENT_ROOT'] . "/img/products/";
and
fwrite($file,$contents);
So here is my final code... credit to Sébastien for pointing me in the right direction. Thanks.
if($method == 'save')
{
$productId = Input::get('pId');
$removeProductImages = DB::table('product_ref_images')->where('product_id', '=', $productId)->delete();
$imagesData = Input::get('imageRefs');
$dir = $_SERVER['DOCUMENT_ROOT'] . "/img/products/";
$sortOrder = 0;
for ($i=0; $i < count($imagesData); $i++) {
$imgSrc = trim($imagesData[$i]['imgSrc']);
$imgId = trim($imagesData[$i]['imgId']);
$file = fopen($dir . basename($imgSrc), "wb");
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$ch = curl_init($imgSrc);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
$contents = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0)
{
Log::write("CURL", "cURL Error (".$curl_errno."): ".$curl_error);
break;
}
else
{
fwrite($file,$contents);
fclose($file);
$imageIds = DB::table('product_ref_images')->order_by('image_id', 'desc')->first();
if($imageIds == null)
{
$imageIds = 0;
}
else
{
$imageIds = $imageIds->image_id;
}
$updateImages = DB::table('product_ref_images')
->insert(array(
'image_id' => $imageIds + 1,
'product_id' => $productId,
'flickr_image_id' => $imgId,
'sort_order' => $sortOrder++,
'local_storage_url' => $dir . basename($imgSrc),
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s")
));
}
}
return Response::json('Complete');
}
Remove this line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
You're storing the response to a file, not to the return variable. Otherwise, you have to save it yourself (like you did in the other solution).

Categories