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
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'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
}
// ...
i have this following php code :
$filename = '/front/style.css';
$cssfile='#h1{font-size:12px}';
if($id_file=fopen($filename, "w+"))
{
echo'file exist';
$id_file=fopen($filename, "w+");
flock($id_file,1);
fwrite($id_file,$cssfile);
flock($id_file,3);
fclose($id_file);
}
else
{
echo "file don t exist";
}
My file is empty but with space.
My file exist and it s writable.
I have nothing in my apache logs.
I m using Mamp with php 5.3.2.
Any ideas ?
Thx
A few mistakes I can see are:
You are using fopen to check if a file exists. That does not work. With the w+ mode PHP will try to create the file if it does not exist. Use the file_exits function to check the existence of a file.
You are opening the same file twice.
Also use PHP constants(LOCK_SH, LOCK_UN) for the second argument of flock. That will make your program more readable.
Updated
Have you checked if its writing to a different directory than you expect? Check your path to see where it defaults to, or even just do a search for the file and see where else it turns up. getcwd() will show what the current working dir is.
Have you checked the return value of fwrite to see if the write is actually working? If fwrite is successful, then try read the file in the code using the same $id_file and see if there is anything there while the program is still running.
You are calling fopen twice. w+ truncates the file and you are writing to the 2nd $id_file so my guess is that its being truncated when the 1st $id_file is being closed.
You can use this approach if your file empty after using fopen w+ option.
// only read
$filename = '/path/to/blah.txt';
$myfile = fopen($filename, "r");
$mydata = fread($myfile, filesize($filename));
$mynewdata = $mydata + 'abc';
fclose($myfile);
// only write
$myfile = fopen($filename, "w");
fwrite($myfile, $mynewdata);
fclose($myfile);
Short story:
I'm getting an open_basedir restriction in my php script - a simple "test writing a new file to disk" script. It SEEMS to me that I've got the open_basedir settings correct and the file is in the right location - but no luck, just the same error every time. I've searched for similar open_basedir problems on this site, but I've not seen any with this problem - where the directory looks right but it still throws errors.
My guesses as to what the problem is:
1) open_basedir doesn't work the way I think it does
2) My settings are wrong and I'm just not seeing it
3) It's actually something else, like IIS read/write permissions, etc
4) ???
Long story:
I'm working on an IIS server with PHP and I'm trying to get the following code snippet to work (a simple write file test):
date_default_timezone_set('America/Chicago');
$myFile = 'testfile.txt';
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Some Text\n";
fwrite($fh, $stringData);
$stringData = "Some More Text\n";
fwrite($fh, $stringData);
fclose($fh);
This php script is located at C:\inetpub\wwwroot\WEBDIRECTORY\test_write.php on my server
Here is my php.ini setting for open_basedir:
open_basedir = c:\inetpub\wwwroot;c:\inetpub\wwwroot\WEBDIRECTORY
Whenever I open the script's page, I am expecting to see no output, and then there should be a new file written on the server when I check back. This is what I get instead:
Warning: fopen(): open_basedir
restriction in effect.
File(testfile.txt) is not within the
allowed path(s): (c:\inetpub\wwwroot)
in
C:\inetpub\wwwroot\WEBDIRECTORY\test_write.php
on line 5 Warning:
fopen(testfile.txt): failed to open
stream: Operation not permitted in
C:\inetpub\wwwroot\WEBDIRECTORY\test_write.php
on line 5 can't open file
I've tried a lot of permutations: originally the open_basedir line was just
open_basedir = c:\inetpub\wwwroot
...but that didn't work, either.
I've also tried entering an absolute path for testfile.txt (c:\inetpub\wwwroot\WEBDIRECTORY\testfile.txt, etc) instead of just the name of the file itself, and I keep getting the same error message.
Any ideas? Thanks so much for your help.
Okay, so sorry to waste everyone's time - turns out it was a server setting my system administrator had set for me. (I'm new to this so I'll explain in general terms that I understand)
He'd set it up so that the server would not resolve an address for any files in the web directory except certain types you expect to find on a website, such as .htm, .html, .php, .jpg, etc. The file I was trying to read was .txt.
So, I wrote some test code:
$test = realpath('c:\inetpub\wwwroot\WEBDIRECTORY\testfile.php');
echo ("test = $test\n");
if($test == FALSE){
echo ("... is FALSE\n");
}
$test = realpath('c:\inetpub\wwwroot\WEBDIRECTORY\testfile.txt');
echo ("test = $test\n");
if($test == FALSE){
echo ("... is FALSE\n");
}
Which promptly returned this:
test = C:\inetpub\wwwroot\WEBDIRECTORY\testfile.php
test = ... is FALSE
So, realpath is refusing to return an address for anything ending in .txt, but is more than happy to do that for a .php file. This means that WHENEVER I put in an otherwise legal (within the basedir) filename that ends in an illegal extension, the server resolves that address not as "C:\inetpub\wwwroot\WEBDIRECTORY\testfile.txt" but as "". And of course, an empty string is not going to be in the basedir, returning open_basedir restriction errors.
BIZARRE! But makes sense now that I finally traced it back to its source. Thanks for all the tips! It helped me go through process of elimination and figure this one out.
It appears to be a permissions problem. Check the permissions on C:\inetpub\wwwroot\WEBDIRECTORY\ If special permissions are required sometimes you have to change the permissions on the .PHP script doing the writing. Typically you need both the directory and the script set, not just one or the other.
Here is a good script from the PHP manual for opening a file for writing:
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
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'm writing a PHP application and in my code i want to create create and return images to the browser. However, sometimes i'm getting some weird results where the image cannot be created since the file does not seem to exist.
Here is a sample error message I get and the code in a nutshell. I do know that the image exists, but still the method sometimes fails, and sometimes it succeeds, even for the same file.
The error:
Warning: imagecreatefrompng(path/to/image.png) [function.imagecreatefrompng]: failed to open stream: No such file or directory in file test.php on line 301
The code:
if (file_exists($filename)) {
$image = imagecreatefrompng($filename);
}
I would greatly appreciate any hints or tips of what might be wrong and how I can improve the code to be more stabile.
I suggest you use is_readable
if (is_readable($filename)) {
$image = imagecreatefrompng($filename);
}
The file may "exist" but is the file accessible? what does file_exists actually do?
if it opens the file and then closes it make sure that the file is actualy closed and not locked before imagecreatedfrompng fires.
it would be a good idea to try catching the error in a loop and make 4 or 5 attempts before handing back a controlled error.
maybe try is_readable() or is_writable() instead?
Have you considered checking for the correct permissions? If the file cannot be read, but the directory can, you would get file_exists(...) = true, but would not be able to open a handle to the file.
Use is_readable() to check whatever you have permission to access that file.
You can try GD :
IF($img = #GETIMAGESIZE("testimage.gif")){
ECHO "image exists";
}ELSE{
ECHO "image does not exist";
}
bro check for white spaces in your filepath. I recently had this issue while i was tring to include a file from a module i was creating for an app. Other modules included well when called but one didnt. It turned out that there was a white space in the filepath. I suggest u try php trim() function. If this works holla.