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
}
// ...
Related
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");
I am trying to open a file for reading in php script but having trouble.
This is my code
$fileHandle = fopen("1234_main.csv", "r")or die("Unable to open");
if (!file_exists($fileHandle))
{
echo "Cannot find file.";
}
The script is in the same directory as the file I am trying to read and there are no other read/write permission errors as I can create/read other files in the same directory.
When I run the script I just get the "Cannot find file" error message. Why is this error message being shown? Surely if fopen() can't open the file the "or die statement" should end the script?
Also, why can't I open the file when it definitely exists and is in the same location as the script (I have also tried using the full path of the filename instead of just the filename).
I am fairly new to php (but have exp in c++) so if its a stupid question I apologize.
Many thanks
In PHP, file_exists() expects a file name rather than a handle. Try this:
$fileName = "1234_main.csv";
if (!file_exists($fileName))
{
echo "Cannot find file.";
} else {
$fileHandle = fopen($fileName, "r")or die("Unable to open");
}
Also keep in mind that filenames have to be specified relative to the originally requested php-script when executing scripts on a web server.
You can use file_get_content() for this operation. On failure, file_get_contents() will return FALSE.For example
$file = file_get_contents('1234_main.csv');
if( $file === false ){
echo "Cannot find file.";
}
file_exists() take the file-name as input, but the logic of your code has problem. You first try to open a file then you check its existence?
You first should check its existence by file_exists("1234_main.csv") and if it exists try to open it.
file_exists takes a string, not a file handle. See http://php.net/manual/en/function.file-exists.php
I'm currently trying to write to a txt-file with PHP, I've found this small script:
<?php
$filename = 'testFile.txt';
$somecontent = "Add this to the file\n";
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
}
else {
echo "The file $filename is not writable";
}
?>
I get a success-message, but nothing is written to the file. Even if I delete the txt-file I still get the success-message
Does anybody know how to troubleshoot a situation like this?
Your code works perfectly fine. However, note that the is_writable check will fail if the file does not exist yet.
If you execute it through a webserver, make sure you are not viewing a cached response.
Your first check with is_writable is not useful, as it fails if the file does not exist.
When you use fopen with the "a" parameter you appent to the file if it exists otherwise it will create a new one.
If you want to check if the file exists you can with file_exists ( http://php.net/manual/en/function.file-exists.php ), but it is not really necessary.
With your code, if you delete the file you should actually get a "the file is not writable" error... are you sure you have exactly that code?
Otherwise, I tried the code and it works fine (without the first if).
how to map the path to the file easily?
public_html/api/function.php
<?php
function writetologfile($content)
{
$filename = 'logfile/testing_randomstring.txt';
if (!$handle = fopen($filename, 'a'))
{
echo "Cannot open file ($filename)";
exit;
}
fclose($handle);
}
?>
the actual path of the text file is in public_html/r/admin/logfile/testing_randomstring.txt
so if I run the script at public_html/folder1/folder2/addlog.php, it won't be able to find the path to the testing_randomstring.txt
addlog.php
<?php
include("../../api/function.php");
writetologfile('hahaha');
?>
How I can able to easily point to this text file path, no matter where my php calling script is from.
I tried to change $filename = 'logfile/testing_randomstring.txt'; inside writetologfile function by enforcing it to absolute fix path,
something like $filename='/r/admin/logfile/testing_randomstring.txt',
but it is not working
Instead of using a relative path, you could specify an absolute path. Assuming public_html is in your home directory, try this:
$filename = '/public_html/r/admin/logfile/testing_randomstring.txt';
fopen(getenv('HOME') . $filename, 'a');
This uses getenv to read the contents of the environment variable $HOME.
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
?>