Error saving image to Facebook profile via PHP SDK

0

Good afternoon!

I'm using the Facebook SDK to login to my site, I can return the data, including the profile photo link, but I can not save the image, the following error occurs:

A PHP Error was encountered

Severity: Warning

Message: file_put_contents (./ images / profile / image name returned ): failed to open stream: No such file or directory

For this I use the cURL library with the file_put_contents function.

$imgUrl = "http://graph.facebook.com/ID FACEBOOK/picture?width=300"; 
$imagename= basename($imgUrl);
if(file_exists('./'.$imagename)){continue;} 
$image = $this->curl->getImg($imgUrl); 
file_put_contents('./imagens/perfil/'.$imagename,$image);

cURL:

function getImg($url) {         
    $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 = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

    

asked by anonymous 26.07.2017 / 21:19

2 answers

0

By changing the basename () function, which searched for the name of the image by a name, the image was saved correctly. getting this way

$imgUrl = "http://graph.facebook.com/ID FACEBOOK/picture?width=300"; 
$imagename = "foto_do_usuario.jpg"
if(file_exists('./'.$imagename)){continue;} 
$image = $this->curl->getImg($imgUrl); 
file_put_contents('./imagens/perfil/'.$imagename,$image);
    
29.07.2017 / 06:22
0

Imagine the following file hierarchy:

/ (raiz do site ou projeto)
  pasta1
    arquivo1.php
  pasta_arquivos
    imagem
  arquivo2.php

Now suppose that file1.php has the following content:

<?php
require '../arquivo2.php';

And the 2.php file has the following content:

<?php
file_put_contents('./pasta_arquivos/imagem', 'vai funcionar?');

If file1.php is executed, the file / directory error is not found, because the ./ will be done in relation to the file1.php, and not in relation to the 2.php file (which would work).

This problem can be solved by using the DIR constant (it returns the directory of the file being included, either by include or require). Then the contents of .php file will be changed to:

<?php
file_put_contents(__DIR__ . '/pasta_arquivos/imagem', 'vai funcionar?');
    
27.07.2017 / 03:33