Cannot create a file - php

I am trying to create a file using php to a dirctory which has cmod 0777 so it should be fine.
Here is the code:
$fh = fopen("/_myfiles/myfile.txt", "w+");
if ($fh==false)
{
die("unable to create file");
}
But all I get is "unable to create file". Any ideas on what it could be?
Note: For the path I've also tried:
$fh = fopen($_SERVER['DOCUMENT_ROOT']."/_myfiles/myfile.txt", "w+");
with no success.

fopen() generates an E_WARNING message on failure.
I recommend using error_reporting(E_ALL) to show the warning and this should help you to troubleshoot the problem from there.

Check write permissions on the directory you want to create the file in.
Also the directory "_myfiles" should exist (it won't be created automatically).
If they are correct, then this will create the file in the same directory where the PHP script is located:
$basedir = dirname(__FILE__);
$fh = fopen($basedir . DIRECTORY_SEPARATOR . 'myfile.txt', 'w+');

Related

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");

How can I read .txt file from my server [PHP]?

I'm creating a Telegram Bot in PHP.
My aim now is read from a .txt file a integer and put him in a variable.
This text.txt is uploaded in a server. I tryed to do this:
$filename = "http://<MY HOST NAME>/test_bot/file/text.txt";
$fp = fopen($filename, "r+");
$send = fgets($fp);
fclose($fp);
echo $send;
But when I try to open my index.php, nothing comes out written.
am I doing something wrong?
Since you are opening from a remote host you can't open for read/write, just read. Try this instead:
$fp = fopen($filename, "r");
If you are trying to open a file on the same server as the PHP script then do not use the "http://..." path but instead the local file path and then you can open it for read/write. In the case of your script it does not appear you need write access so "r" should be sufficient.
To access without http just use the path to the file:
$filename = '/path/to/file/text.txt';
$fp = fopen($filename, "r+");
Or if you want a relative path from the script itself I prefer:
$filename = dirname(__FILE__) . '/../some/relative/path/text.txt';

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
}
// ...

PHP Write File Error

I have a page called index.php which is calling a function "writelog" in includes/Logger.php
I have file located at includes folder and code is as below.
function writelog($logText){
$myFile = "testlog.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $logText + "\n";
fwrite($fh, $stringData);
fclose($fh);
}
It shows errror "can't open file" . I have set FullPermission for everyone and still it says it cant access file.I tried to put file in same folder as index.php and same error. What can be possible cause ? Am I having wrong path ?
Try using the full path of the log file
$myFile = "/full/path/to/testlog.txt";
I am assuming this file is also in includes, I'm guessing this is called from another script so the path would be one of the calling script. You can use this:
$prevdir = getcwd();
chdir(dirname(__FILE__));
$myFile = "testlog.txt";
chdir($prevdir);
But it's best to use absolute paths

php: writing files

I want to create a file on the webserver dynamically in PHP.
First I create a directory to store the file. THIS WORKS
// create the users directory and index page
$dirToCreate = "..".$_SESSION['s_USER_URL'];
mkdir($dirToCreate, 0777, TRUE); // create the directory for the user
Now I want to create a file called index.php and write out some content into it.
I am trying:
$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");
fclose($ourFileHandle);
// append data to it
$ourFileHandle = fopen($ourFileName, 'a') or die("can't write to file");
$stringData = "Hi";
fwrite($ourFileHandle, $stringData);
But it never gets past the $ourFileHandle = fopen($ourFileName, 'x') or die("can't open file"); Saying the file does not exist, but that is the point. I want to create it.
I did some echoing and the path (/people/jason) exists and I am trying to write to /people/jason/index.php
Does anyone have any thoughts on what I am doing wrong?
PHP 5 on a linux server I believe.
-Jason
First you do :
$dirToCreate = "..".$_SESSION['s_USER_URL'];
But the filename you try to write to is not prefixed with the '..', so try changing
$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
to
$ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php';
or probably tidier:
$ourFileName = $dirToCreate . '/index.php';
You are probably getting the warning because the directory you are trying to write the file into does not exist
It could be a result of one of your php ini settings, or possibly an apache security setting.
Try creating the dir as only rwxr-x--- and see how that goes.
I recall a shared hosting setup where "safemode" was compiled in and this behaviour tended to occur, basically, if the files/dirs were writable by too many people they would magically stop being acessible.
Its probably doc'd in php, but ill have to check.
why not use:
file_put_contents( $filename, $content )
or you could touch the file before writing to it.
Does the file 'index.php' already exist? When you fopen with the 'x' mode, if the file exists fopen will return FALSE and trigger a warning.
What i first noticed is you are making a directory higher in the tree, then attempting to make the php file in the current folder. Correct me if i'm wrong, but aren't you trying to make the file in the new created folder? if i recall php correctly (pardon me it's been a while, i'll probably add something from another language in here not noticing) here is an easier to understand way for a beginner, of course change the values accordingly, this simply makes a directory and makes a file then sets permissions.
<?php
$path = "..".$_SESSION['s_USER_URL'];
// may want to add a tilde (~) to user directory
// path, unixy thing to do ;D
mkdir($path, 0777); // make directory, set perms.
$file = "index.php"; // declare a file name
/* here you could use the chdir() command, if you wanted to go to the
directory where you created the file, this will help you understand the
rest of your code as you will have to perform less concatenation on
directories such as below */
$handle = fopen($path."/".$file, 'w') or die("can't open file");
// open file for writing, create if it doesn't exist
$info = "Stack Overflow was here!"; // string to input
fwrite($handle, $info); // perform the write operation
fclose($handle); // close the handle
?>

Categories