-4

file_put_contents is not working for the following code? (I used xampp)

I try:

    $url = 
    'http://localhost/main_assets/images/company/news/142861-Spring-Break-main-pic.jpg';
      
    $file_name = basename($url);
    
    echo "url:";
    var_dump($url);
    
    echo "file_name:";
    var_dump($file_name);

    if (file_put_contents($file_name, file_get_contents($url)))
    {
        echo "File downloaded successfully";
    }
    else
    {
        echo "File downloading failed.";
    }

result:

url:
C:\xampp\htdocs\sitemaker\a_php_codes\controllers\testurl\ctrl_index.php:16:string 'http://localhost/main_assets/images/company/news/142861-Spring-Break-main-pic.jpg' (length=81)

file_name:
C:\xampp\htdocs\sitemaker\a_php_codes\controllers\testurl\ctrl_index.php:19:string '142861-Spring-Break-main-pic.jpg' (length=32)
File downloaded successfully


but there is no file in the following directory:

C:\xampp\htdocs\sitemaker\a_php_codes\controllers\testurl\

I can see the image when I enter the address to the browser; result no file no error ...!! I do some search but most result is because of permission issue. I check the folders permission: enter image description here enter image description here

1 Answers1

0

Many thanks to @deceze for the answer and @RiggsFolly for editing my question. As I mentioned above I was looking in the folder that php file is running:

C:\xampp\htdocs\sitemaker\a_php_codes\controllers\testurl\

and expect the result file of the file_put_contents will appear in that folder but the file is in the htdocs folder (maybe the xampp default folder).
That was my problem and because of that, there is no error. I use Predefined constants DIR and my problem is solved. here is my final code:

  $url = 
'http://localhost/main_assets/images/company/news/142861-Spring-Break-main-pic.jpg';
  
$file_name = basename($url);

$filePath = __DIR__ . "\\" . $file_name; 

if (file_put_contents($filePath, file_get_contents($url)))
{
    echo "File downloaded successfully";
}
else
{
    echo "File downloading failed.";
}
E_net4
  • 27,810
  • 13
  • 101
  • 139