I am trying to use file_put_contents on my local website to download some images from a website and save them to the C:\ drive. However when running the script I get an error
file_put_contents(C:\product_images\A): failed to open stream: Permission denied
I have full permission for the product_images folder and also the A folder inside.
I know I could just chmod in ubuntu but not sure what I could do with Windows. I just right clicked and selected properties and made sure all the users had all the permissions applied
public function showImage() {
$product_image = ['/ABCD/ABCD.jpg','/ABCDE/ABCDE.jpg'];
foreach($product_image as $product_images) {
$url = "http://images.url.com/product_images" . $product_images ."";
$letter = substr($product_images, 1, 1);
$folder = 'C:\product_images\ ' .$letter . '';
$new_folder = str_replace(' ', '', $folder);
file_put_contents($new_folder, file_get_contents($url));
}
$success = "Success!";
return $success;
}
foreach($product_image as $product_images) {
$url = "http://images.com/product_images" . $product_images ."";
$test = explode("/", $product_images);
$folder = 'C:\product_images\ ' . $test[2] . '';
$new_folder = str_replace(' ', '', $folder);
$newer_folder = str_replace('/', '\\', $new_folder);
file_put_contents($newer_folder, file_get_contents($url));
echo '../product_images/' . $test[2] . '';
echo '<br />';
}
file_put_contents works with URLs only if allow_url_fopen is on ("1"). Check it with
ini_get("allow_url_fopen");
Also notice that while your writing folder might have the required permissions, the parent folder may NOT. Both (possible) folders should have the permissions.
You can also test the folder if its writable (through is_writable)
Related
Below I have left my code. It currently works in my development environment (localhost), but when I push the changes to my live server it seems like my php doesn't create the folder/file.
public static function saveImage($image, $name, $path = '')
{
$img_data = explode(',', $image);
$mime = explode(';', $img_data[0]);
$data = $img_data[1];
$extension = explode('/', $mime[0])[1];
if(!file_exists('../public/media/img/' . $path)){
mkdir('../public/media/img/' . $path, 0755);
echo('Test1');
}
echo('test2');
file_put_contents('../public/media/img/' . $path . $name . '.' . $extension, base64_decode($data));
return 'media/img/' . $path . $name . '.' . $extension;
}
Locally it will hit echo('test1') the first time, then it will only hit echo('test2'). When its on the server it always hits the echo('test1')
By default mkdir is not create a path recursively. An example if on your server you dont have a ../public/media folder, mkdir returns false and dont create a path.
To solve this pass a third parameter to mkdir as true:
mkdir('../public/media/img/' . $path, 0755, true);
Do yourself a favour and use absolute pathes...
You can use the constant __DIR__ to evaluate the folder in which the script actually resides.
Relative pathes are calculated from the current working directory, which can be different than __DIR__
I'm using the mailReader script found here: https://github.com/stuporglue/mailreader
I am trying to copy the file(s) after upload to another folder.
The file(s) upload correctly to the folder where the script resides.
When I try to run a copy command, the filename variable is empty.
Here is the portion of the code I am working with: The last three lines are what I added.
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I receive confirmation by email that the file(s) are uploaded, then another email with the error message.
Warning: copy(/attachments/W7652222-546/1453406138_residential-print_from_td.pdf): failed to open stream: No such file or directory in /home/myhost/public_html/mailreader/mailReader.php on line 224
224 being the line number of my added code.
The source filename is missing from in front of /attachments...
Anyone have any thoughts?
$name is defined in the while loop and may not be accessible on the upper scopes my suggestion is to change your code to this:
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
$name = '';
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I hope this solves your problem
I ended up defining a constant of email_id in the private function saveToDb, then running a script after everything else is finished to query the table using the email_id and looping through the records moving the files.
so I come to you with this problem:
GIVENS:
I have Hostgator as the ISP.
I'm using PHP 5.5
The LINUX box is CENTOS
Shared Hosting Environment
I am a professional coder and experienced with LAMP for many years
PROBLEMS:
I'm NOT familiar with Jailed Shell but have an idea
I've tried the script and have been searching for an answer
Still Stuck...
Here's my current code:
function getMyFakeDir($myfile) {
$target = "";
$link = 'content/purchased-items/link';
symlink($target, $link);
echo "READ LINK: ". readlink($link);
return readlink($link);
}
Here's the called to the function:
$linkText = getMyFakeDir('SomePDFThatTheUserCanDownload.pdf');
Then I pass that "$linkText" var to PHPMailer and wala!!! The user clicks to download through the Symlink and I've written a code to make it expire after 24 hours. Yeah, I got that from PHP.net.
So, basically that's my problem....
Here's the error:
Warning: symlink(): Permission denied in /homeSomewhere/someMasterDir/public_html/webServices/somePHPFile.php on line 654
This is link 654 from above:
symlink($target, $link);
Thanks...
Figured it out.... Simple LOGIC!
First I had the PATHS all wrong. Here's the CORRECTED CODE:
//Generate Symbolic Link that blows away a fake directory each time
//A symbolic Link is created to "THIS" file below
$filename = $myfile;
//This is ANY directory on the server...
//A randomly named directory is created here...STEP 1
$downloaddir = "/home/someHostDir/public_html/sldktrulwiu2555ivd0fjvdfgdfgdfgdf/";
//Any directory NOT accessible by a browser - This is one level up
$safedir = "/home/someHostDir/content/purchased-items/";
//This is the equivalent of the $downloaddir and the browser is REDIRECTED here and the download begins
$downloadURL = "http://www.theSomeDomain.com/sldktrulwiu2555ivd0fjvdfgdfgdfgdf/"; //THIS IS THE FAKE DIRECTORY (Which I simply type gobbligook and created that mess above)
$letters = 'abcdefghijklmnopqrstuvwxyz';
srand((double) microtime() * 1000000);
$string = '';
for ($i = 1; $i <= rand(4, 12); $i++) {
$q = rand(1, 24);
$string = $string . $letters[$q];
}
$handle = opendir($downloaddir);
while ($dir = readdir($handle)) {
if (is_dir($downloaddir . $dir)) {
if ($dir != "." && $dir != "..") {
#unlink($downloaddir . $dir . "/" . $filename);
#rmdir($downloaddir . $dir);
}
}
}
closedir($handle);
mkdir($downloaddir . $string, 0777);
symlink($safedir . $filename, $downloaddir . $string . "/" . $filename);
//Header("Location: " . $downloadURL . $string . "/" . $filename);
That just about does it.
The result is a Dynamic directory inside the "/sldktrulwiu2555ivd0fjvdfgdfgdfgdf/" directory like this: "dfsgss/" and a "shortcut" to the REAL LOCATION where the files are. THEN when the file is downloaded, and the page returns to the INDEX.HTML, the code BLOWS OUT the FAKE directory Never more to be seen again. Thus, if the user wants to go back, they get the horrible 404 PAGE error that the file / has been moved or deleted. BUMMER.
That's it folks. Thanks for your assistance, it was you all the helped me release my error. TEAM WORK!
I have done chmod -R 777 on the root folder, but I'm still unable to successfully
upload (thus, write) to the uploaded folder!
Do I also have to change the php.ini file?
//$target_path = "http://localhost/photoServerProject/uploaded";
$target_path = "/photoServerProject/uploaded";
$fname = $_FILES["file"]["name"];
$upload_location = $target_path.'/'.$fname;
move_uploaded_file($_FILES["file"]["tmp_name"], $upload_location);
echo 'Moving file: ' . $fname . '</br></br>to: ' . $upload_location;
//echo "<img src=$upload_location>";
if(is_writeable($upload_location)){
echo '</br></br>Location <strong>is</strong> writeable ';
} else {
echo '</br></br>Location <strong>is NOT</strong> writeable ';
}
Output:
Moving file: camera.jpeg
to: /photoServerProject/uploaded/camera.jpeg
Location is NOT writeable
Try using
$targetPath= $_SERVER['DOCUMENT_ROOT'] . "photoServerProject/uploaded"
or
$targetPath= $_SERVER['DOCUMENT_ROOT'] . "/photoServerProject/uploaded"
I was confusing the difference between paths on my local drive vs server paths. My root folder (localhosts) for server paths is different than my local directory structure.
I was misunderstanding the difference between server and local disk directory structures. Namely, the root folders are different.
I'm surprised nobody brought up this issue.
Here's the solution:
<?php
$local_target = "~/webdev/photoServerProject/uploaded/";
$server_target = $_server['DOCUMENT_ROOT'] . "/photoServerProject/uploaded/";
$fname = $_FILES["file"]["name"];
$local_file_location = $local_target.$fname;
$server_file_location = $server_target.$fname;
move_uploaded_file($_FILES["file"]["tmp_name"], $local_file_location);
echo 'Moving file: ' . $fname . '</br></br>to local path: ' . $local_file_location;
echo '</br></br> But on the server it resides in : ' . $server_file_location;
echo '</br></br> See?';
echo "</br></br> <img src=$server_file_location>";
?>
I have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>