-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

8
  • Apache look after access (or it should unless you have changed it) Commented Apr 4, 2022 at 10:22
  • Check your htdocs or htdocs\sitemaker directories… You're just giving a filename, not an absolute path, so PHP will save the file relative to whatever Apache's working directory is. Commented Apr 4, 2022 at 10:25
  • stackoverflow.com/questions/8423404/… Commented Apr 4, 2022 at 10:26
  • @OMi Shah: thanks for your help but that link refer to get_content problem my problem is for put_content and the allow_url_fopen is on. Commented Apr 5, 2022 at 9:15
  • @RiggsFolly: I didn't get what you mean! Commented Apr 5, 2022 at 9:19

1 Answer 1

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."; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.