Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fopen() to write file into subdirectory

I already looked at this StackOverflow question and it didn't help (similarly titled).

I'm passing an image in from my Android application. If I type

$file = fopen('test.jpg', 'wb');

It works correctly and the image uploads; however, I want to allow for multiple uploads from android phones, so I want to randomize the name of the .jpg file so that I can save each new upload as a different name. I was trying this below:

$destination =  time() + rand(1, 1000) . ".jpg";
$url_destination = "/project_images/" . $destination;

$file = fopen($url_destination, 'wb');
fwrite($file, $binary);
fclose($file);

It doesn't write the file to the server, however. I tried different variations of the URL there - with 'project_images/', '/project_images/', even trying the full URL (which the aforementioned StackOverflow post corrected me on), and I still can't get it to write.

The permissions of the project_images folder are set to allow files to be written to it. Any ideas?

like image 541
Isaac Askew Avatar asked Dec 07 '12 10:12

Isaac Askew


People also ask

Does fopen work on directories?

The fopen can't be used to create directories. This is because fopen function doesn't create or open folders, it only works with files.

What is a file subdirectory?

Updated: 07/31/2022 by Computer Hope. In a computer file system, a subdirectory is a directory that is contained another directory, called a parent directory. A parent directory may have multiple subdirectories.

How is folder related to subdirectory?

A subdirectory is a type of website hierarchy under a root domain that uses folders to organize content on a website. A subdirectory is the same as a subfolder and the names can be used interchangeably.


2 Answers

Your problem is "/project_images" which is a wrong absolute path.

For it to work change it to "project_images/" or dirname(__FILE__).'/project_images/'.

like image 58
Sorin Trimbitas Avatar answered Sep 20 '22 09:09

Sorin Trimbitas


For those who use XAMPP on Windows: use DIRECTORY_SEPARATOR instead /

dirname(__FILE__).DIRECTORY_SEPARATOR.'project_images'.DIRECTORY_SEPARATOR
like image 45
bozydarlelutko Avatar answered Sep 20 '22 09:09

bozydarlelutko