I'm struggling to use a php function, fopen with multiple variables.
I have two variables: $language is the extension ( E.G. .php ) and $url is a random number generated at the start of the script.
Here is my code but it always throws the die statement and doesn't work
$filename = "tools/scripts/tool".$language."?id=".$url;
$fh = fopen($filename, "w") or die("There Was An Error With The Script.");
Thanks
fopen will open the files content itself. It doesn't parse the file.
You might use exec() or you can call the file over a webserver.
fopen('http://localhost/yourfile.php?param='.$param);
Not to mention, that you are trying to write to a file there... ,"w")
yourfile.php?param=123 <- is not a valid filename
Related
I have a simple PHP script to read a remote file line-by-line, and then JSON decode it. On the production server all works ok, but on my local machine (MAMP stack, OSX) the PHP hangs. It is very slow, and takes more than 2 minutes to produce the JSON file. I think it's the json_decode() that is freezing. Why only on MAMP?
I think it's stuck in while loop, because I can't show the final $str variable that is the result of all the lines.
In case you are wondering why I need to read the file line-by-line, it's because in the real scenario, the remote JSON file is a 40MB text file. My only good performance result is like this, but any good suggestion?
Is there a configuration in php.ini to help solve this?
// The path to the JSON File
$fileName = 'http://www.xxxx.xxx/response-single.json';
//Open the file in "reading only" mode.
$fileHandle = fopen($fileName, "r");
//If we failed to get a file handle, throw an Exception.
if($fileHandle === false){
error_log("erro handle");
throw new Exception('Could not get file handle for: ' . $fileName);
}
//While we haven't reach the end of the file.
$str = "";
while(!feof($fileHandle)) {
//Read the current line in.
$line = fgets($fileHandle);
$str .= $line;
}
//Finally, close the file handle.
fclose($fileHandle);
$json = json_decode($str, true); // decode the JSON into an associative array
Thanks for your time.
I found the cause. It is path protocol.
With
$filename = 'http://www.yyy/response.json';
It freezes the server for 1 to 2 minutes.
I changed the file to another server with https protocol, and used
$filename = 'https://www.yyy/response.json';
and it works.
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 write into text file without erase all the existing data?
I tried this
$txt = 'srge';
$file = fopen('text.txt','w');
fwrite($file,$txt);
but it's not working, it's earse everything
Note: This will only work when you have appropriate permission for test.txt else it will say
permission denied (un-appropriate will lead to this)
Here we are using:
1. a which is for append this will append text at the end of file.
2. instead of w, flag w is for write, which will write on file without caring about you existing data in that file.
PHP code:
<?php
ini_set('display_errors', 1);
$txt = 'srge';
$file = fopen('text.txt','a');
fwrite($file,$txt);
according to php documentation:
while you are using :
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
try instead:
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
Try with following code
$txt = 'srge';
$file = fopen('text.txt','a');
fwrite($file,$txt);
Writing or Appending to a File
The processes for writing to or appending to a file are the same. The difference lies in the fopen() call. When you write to a file, you should use the mode argument "w" when you call fopen():
$fp = fopen( "test.txt", "w" );
All subsequent writing will occur from the start of the file. If the file doesn't already exist, it will be created. If the file already exists, any prior content will be destroyed and replaced by the data you write.
When you append to a file, you should use mode "a" in your fopen() call:
$fp = fopen( "test.txt", "a" );
For more details please refer this : File operation example
Php Filesystem Functions
You can use this.
$content = 'any text';
$file = fopen('file.txt','a');
fwrite($file,$content);
Have you noticed i used mode a
"a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
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 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);