fopen error for creating a new file? - php

I was following a guide for creating a new file in php and I was using the following code:
function create($user, $name) {
/* Later on, this will connect to another server*/
$dir = $user->getFolder() . "/Projects/". $name;
if(file_exists($dir)) {
$this->error = "Directory: " . $dir . " already exists.";
} else {
mkdir($dir);
//Create the users.json file and add the owner
$json = fopen($dir . "/Data/users.txt", "w") or die("Cannot open file");
fclose($json);
}
}
The directory gets created but I receive the following error: "Warning: fopen(Jake/UserFolder//Projects/test/Data/users.txt): failed to open stream: No such file or directory in D:\xampp\htdocs\Collabs\Objects\Scripts\Project.php on line 14
Cannot open file"

The path shown in your error looks like it could be the problem.
Jake/UserFolder//Projects/test/Data/users.txt
There are two slashes between UserFolder and Projects. It looks like changing your code to
$dir = $user->getFolder() . "Projects/". $name;
Would get rid of the extra slash.

A couple of things that might have gone wrong:
You didn't pass path with a leading /, so fopen() will search relatively to the directory the script is executing in. I assume you'll want to pass an absolute path
you are testing for file_exists(), you should also check for is_dir(), to catch and handle the cases where a file with the same path already exists
you might consider calling mkdir($dir, 077, true) in order to create
the intermediary directories (see the mkdir() documentation)

Related

failed to open stream: Permission denied open server

My aim is to download multiple files into the folder on my localhost. I am uploading them using the HTML form.
Here is the code (really sorry that I can't give a link to the executable version of the code because it relies on too many other files and database if anyone knows the way then please let me know)
foreach ($_FILES as $value) {
$dir = '/';
$filename = $dir.basename($value['name']);
if (move_uploaded_file($value['tmp_name'],$filename)) {
echo "File was uploaded";
echo '<br>';
}
else {
echo "Upload failed";
echo '<br>';
}
}
So this little piece of code give me an error:
And here are the lines of code:
The problem is that the adress is correct, I tried enterring it into my file directory and it worked fine, I have seen some adviced on other people's related questions that // or \ should be used instead, but my version works just fine! Also I have checked what's inside the $_FILES and here it is if that's required for someone trying to help:
Thank you very much if anyone could help!!
You are trying to move the file to an invalid (or non-existent) path.
For the test you will write
$dir = 'c:/existing_dir/';
$filename = $dir.basename($value['name']);
If you want to move the file to a folder that is relative to the running file try
$dir = '../../directory/';// '../' -> one directory back
$filename = $dir.basename($value['name']);
By starting your file path with $dir = '/'; you are saying store the file on the root folder, I assume of C:
Apache if correctly configures should not allow you access to C:\
So either do
$dir = '../';
$filename = $dir.basename($value['name']);
to make it a relative path or leave the $dir = '/'; out completely

In php code, use shell_exec correctly in my case

I have question about how to save log in correctly directory. My php code:
public static function log(test $testination) {
echo($testination->getDetails()."\n");
$log_filename = shell_exec("cd; ~/log/");
$log_filename2 = "log";
if (!file_exists($log_filename2))
{
mkdir($log_filename, 0777, true);
}
$log_file_data =$log_filename.'/logs_' . date('d-M-Y') . '.log';
file_put_contents($log_file_data, var_dump($testination) . "\n", FILE_APPEND);
}
in this code, I create a folder in the same place as my PHP file, then create folder log if this not exist.
I want to save in begining (just cd) then create log folder if this not exist I try this code
$log_filename = shell_exec("cd; ~/log/");
i get warning/error
PHP Warning: file_put_contents(/logs_18-Aug-2020.log): failed to open stream: Permission denied in /test/test/Helper.php on line 318
Any idea how to do it? Please im stuck.
Any help will be appreciated.
That's not how you should use file_put_contents: it does not know anything about that attempt to change the directory, as this will not affect the execution of PHP. If you want to get the directory of the current PHP file, you can use basename(__DIR__)
Additionall, cd; ~/log/ won't work in your shell as well.

PHP fopen doesn't find existing file

I'm currently writting a login-system with PHP, for that I need to read the files with some user-information in it.
But after changing the folder system, PHP fopen doesn't read the files anymore.
Both the users.php and userinf.csv files are in the samle folder.
I allready tried to change the filepath, hard-coded the filepath , recreated the file. All of which file.
//Read file
$fp = fopen("userinf.csv", "r");
if(!$fp)
{
echo "File couldn't be read";
return false;
}
Before changing the file system, it worked. But now I am geting the error:
Warning: fopen(userinf.csv): failed to open stream: No such file or directory in FILEPATH on line 45
When you use the fread function without any reference it could fail. I always say that you need to check your path first with getcwd()
<?php
echo getcwd(); //Current Working Directory
?>
Use absolute paths, always. It removes any ambiguity. Using a relative path may change based on where your script is located, among other things, depending on your system.
$fp = fopen("/home/somewhere/blah/userinf.csv", "r");
You can always use a variable for the path as well:
// Somewhere in your code
define('ROOT_PATH', "/home/somewhere/blah");
// In the implementation
$fp = fopen(ROOT_PATH . "/userinf.csv", "r");

Cannot use absolute path to a file received via STDIN in PHP CLI

As a part of some automation scripts I'm writing a function that asks the user for an absolute path to the file she wishes to use. The problem is that PHP throws Warning: fopen("/path/to/desired/file/file.txt"): failed to open stream: No such file or directory in /path/to/my/script/script.php on line 13 when the user inserts the file. Here is the general function:
function askFile() {
echo "Please specify the full path to your file.\n";
$usrInput = trim(fgets(STDIN, 1024));
$usrInput = '"' . $usrInput . '"';
echo $usrInput . "\n"; // Just to test the final string.
echo is_string($usrInput) ? "It's a string.\n" : "It's not a string.\n"; // Just to confirm that the variable holds a string.
if($handle = fopen($usrInput, 'r')) {
echo "Thank you. The file is now opened.\n";
} else {
"Sorry, could not open the file for reading.\n";
}
}
askFile();
The permissions for the file are, for testing purposes, wide open at 777. When I simply hard code the absolute path right inside fopen() everything works as expected, therefore the problem only occurs when the input comes from STDIN.

Using fopen and fwrite with Zend Framework?

I'm attempting to check for file existence with Zend Framework and, if the file doesn't exist, have it be created. Here's the code being used:
$filename = "/assessmentsFile/rubrics/$rubricID.php";
$somecontent = "test";
if (!$handle = fopen($filename, 'w+')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === false) {
echo "Cannot write to file ($filename)";
exit;
}
However, I assume due to Zend's way of handling file structure, if a file doesn't exist it just spits out:
Warning: fopen(/assessmentsFile/rubrics/1.php) [function.fopen]: failed to open stream: No such file or directory
Because the fopen function isn't working, fwrite is unable to write the file.
Is there another way of doing this?
Most likely the issue is with the path to $filename.
You have
$filename = "/assessmentsFile/rubrics/$rubricID.php";
which tries to create a file in the root of the server in a directory called assessmentsFile.
Most likely you need to be using:
$filename = $_SERVER['DOCUMENT_ROOT'] . "/assessmentsFile/rubrics/$rubricID.php";
$_SERVER['DOCUMENT_ROOT'] should do the trick if the assessmentsFile folder is in your web root. Otherwise there are other variables you can use to get a fully qualified path, or you can simply hard-code the path:
$filename = "/home/yoursite/public_html/assessmentsFile/rubrics/$rubricID.php";
There's a function file_exists that tells you if the file exists, and with is_file you can check it's a file (and not a directory for example).
(Another way is to suppress warnings by putting an # before the function call (e.g. $handle=#fopen(...), but it's better to check for file existence)
Try this:
if(is_file($filename)){ // exists
$handle=fopen($filename,"w+");
}else{
$handle=fopen($filename,"w"); // create it
}
// ...

Categories