Error saving Facebook profile picture via PHP SDK

Good afternoon!

I am using Facebook SDK to login to my website, I am able to return the data including the profile photo link, but I am unable to save the image, the following error occurs:

A PHP Error was encountered

Severity: Warning

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

For this I use cURL library with function file_put_contents.

$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;     
} 

note: using this same code with the url of an image from another location works perfectly.

Author: Rafael Gonçalves, 2017-07-26

2 answers

Imagine the following file hierarchy:

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

Now suppose the file1.php has the following content:

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

And file2.php has the following content:

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

If the file1.php is executed the file/directory error Not Found will be displayed, as ./ will be done in relation to file1.php, and not in relation to the file2.php (that would work).

This problem can be solved with the use of the constant DIR (returns the directory of the file being included, either by include or require). Then the file content2.PHP headquarters be changed to:

<?php
file_put_contents(__DIR__ . '/pasta_arquivos/imagem', 'vai funcionar?');
 0
Author: Juven_v, 2017-07-27 01:33:22

When changing the basename () function, which searched for the image name 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);
 0
Author: Rafael Gonçalves, 2017-07-29 04:22:51