Sunday, August 2, 2015

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?
shareimprove this question
1 
fopen cannot write to a URL, so $url_destination is definitely starting on the wrong foot. The path must be a local filesystem path. –  Jon Dec 7 '12 at 10:06 
   
try to change permissions to 777 for /project_images directory –  Nick Dec 7 '12 at 10:10
   
   
@ÁlvaroG.Vicario The OP already stated in his question that that question doesn't fix his problem. – JaredMcAteer Dec 7 '12 at 14:19
   
@JaredMcAteer - The OP admitted later that "he didn't upload properly". –  Álvaro G. Vicario Dec 7 '12 at 15:54
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/'.
shareimprove this answer
   
I thought I had tried that one already (see my post where I actually included that!), but I guess it didn't upload properly. This solved it. –  Isaac Askew Dec 7 '12 at 10:09
1 
Great :) .. usually using dirname(FILE) is the best solution in these cases –  Sorin Trimbitas Dec 7 '12 at 10:10
1 
+1 i <3 dirname(FILE) –  Dale Dec 7 '12 at 10:11
   
Another improvement of your code .. try to stick to ' instead of " if you don't use code like this : $str = "content of test is $test"; –  Sorin Trimbitas Dec 7 '12 at 10:13