Include error in writing html file from php - php

I seem to have some problem with my code here. It creates a file from the php file, but I get an error on the include path.
include('../include/config.php');
$name = ($_GET['createname']) ? $_GET['createname'] : $_POST['createname'];
function buildhtml($strphpfile, $strhtmlfile) {
ob_start();
include($strphpfile);
$data = ob_get_contents();
$fp = fopen ($strhtmlfile, "w");
fwrite($fp, $data);
fclose($fp);
ob_end_clean();
}
buildhtml('portfolio.php?name='.$name, "../gallery/".$name.".html");
The problem seems to be here:
'portfolio.php?name='.$name
Any way I can replace this, and still send the variable over?
Here's the error I get when I put ?name after the php extension:
Warning: include(portfolio.php?name=hyundai) [function.include]: failed to open stream: No such file or directory in D:\Projects\Metro Web\Coding\admin\create.php on line 15
Warning: include(portfolio.php?name=hyundai) [function.include]: failed to open stream: No such file or directory in D:\Projects\Metro Web\Coding\admin\create.php on line 15
Warning: include() [function.include]: Failed opening 'portfolio.php?name=hyundai' for inclusion (include_path='.;C:\php\pear') in D:\Projects\Metro Web\Coding\admin\create.php on line 15

Now I saw your code in the comment to a previous answer I'd like to point few things out
function buildhtml($strhtmlfile) {
ob_start(); // redundant
$fp = fopen ($strhtmlfile, "w"); // redundant
file_put_contents($strhtmlfile,
file_get_contents("http://host/portfolio.php?name={$name}"));
// where does $name come from?? ---^
close($fp); // also redundant
ob_end_clean(); // also redundant
}
buildhtml('../gallery/'.$name.'.html');
In PHP as in many other languages you can do things in different ways. What you've done is you took three different ways and followed only one (which is absolutely enough). So when you use functions file_put_contents() and file_get_contents() you don't need the buffer, that is the ob_ family of functions, because you never read anything in the buffer which you should then get with ob_get_contents(). Nor you need the file handles created and used by fopen(), fclose(), because you've never written to or read from the file handle i.e. with fwrite() or fread().
If I'm guessing correctly that the purpose of your function is to copy html pages to local files, my proposal would be the following:
function buildhtml($dest_path, $name) {
file_put_contents($dest_path,
file_get_contents("http://host/portfolio.php?name={$name}"));
}
buildhtml('../gallery/'.$name.'.html', $name);

file_put_contents($strhtmlfile, file_get_contents("http://host/portfolio.php?name={$name}"))
Is it ok?

The output of:
'portfolio.php?name='.$name, "../gallery/".$name.".html";
is:
portfolio.php?name=[your name]../gallery/[your name].html
Are you sure that's what you want ?

include/require statements in PHP allow you to access the code contained in a file which is already stored on the server
What you are trying to achieve is including the output result of executing the code in that file with specific parameters
The suggested example offered by MrSil allows you to request the execution of the code in those files and offer parameters. The reason it shows you a blank page is because file_put_contents 'saves data to a file' and file_get_contents does not echo the result, it returns it. Remove the file_put_contents call, and add an echo at the beginning of the line before file_get_contents and it should work.
echo file_get_contents('http://domain.com/file.php?param=1');
As a warning this approach forces the execution of 2 separate PHP processes. An include would have executed the code of the second file within the first process.
To make the include approach work you need to include the file as you first did but without specifying parameters. Before including each file you need to setup the parameters it is expecting such as $_GET['name'] = $name

Related

PHP file_put_contents overwriting data

I'm attempting to write data to a .txt file using php file_put_contents with the following code.
file_put_contents($filevar, $userID, FILE_APPEND);
This successfully writes the $userID to $filevar, however even though FILE_APPEND is set, the file is overwritten on every execution.
I found my error,
I was working on getting the file to open earlier and was using some test statements. Opening problem was a permissions issue.
I was using fopen($filevar, 'w') to test if I could open the file, and this line was preventing the APPEND from working.

About PHP parallel file read/write

Have a file in a website. A PHP script modifies it like this:
$contents = file_get_contents("MyFile");
// ** Modify $contents **
// Now rewrite:
$file = fopen("MyFile","w+");
fwrite($file, $contents);
fclose($file);
The modification is pretty simple. It grabs the file's contents and adds a few lines. Then it overwrites the file.
I am aware that PHP has a function for appending contents to a file rather than overwriting it all over again. However, I want to keep using this method since I'll probably change the modification algorithm in the future (so appending may not be enough).
Anyway, I was testing this out, making like 100 requests. Each time I call the script, I add a new line to the file:
First call:
First!
Second call:
First!
Second!
Third call:
First!
Second!
Third!
Pretty cool. But then:
Fourth call:
Fourth!
Fifth call:
Fourth!
Fifth!
As you can see, the first, second and third lines simply disappeared.
I've determined that the problem isn't the contents string modification algorithm (I've tested it separately). Something is messed up either when reading or writing the file.
I think it is very likely that the issue is when the file's contents are read: if $contents, for some odd reason, is empty, then the behavior shown above makes sense.
I'm no expert with PHP, but perhaps the fact that I performed 100 calls almost simultaneously caused this issue. What if there are two processes, and one is writing the file while the other is reading it?
What is the recommended approach for this issue? How should I manage file modifications when several processes could be writing/reading the same file?
What you need to do is use flock() (file lock)
What I think is happening is your script is grabbing the file while the previous script is still writing to it. Since the file is still being written to, it doesn't exist at the moment when PHP grabs it, so php gets an empty string, and once the later processes is done it overwrites the previous file.
The solution is to have the script usleep() for a few milliseconds when the file is locked and then try again. Just be sure to put a limit on how many times your script can try.
NOTICE:
If another PHP script or application accesses the file, it may not necessarily use/check for file locks. This is because file locks are often seen as an optional extra, since in most cases they aren't needed.
So the issue is parallel accesses to the same file, while one is writing to the file another instance is reading before the file has been updated.
PHP luckily has a mechanisms for locking the file so no one can read from it until the lock is released and the file has been updated.
flock()
can be used and the documentation is here
You need to create a lock, so that any concurrent requests will have to wait their turn. This can be done using the flock() function. You will have to use fopen(), as opposed to file_get_contents(), but it should not be a problem:
$file = 'file.txt';
$fh = fopen($file, 'r+');
if (flock($fh, LOCK_EX)) { // Get an exclusive lock
$data = fread($fh, filesize($file)); // Get the contents of file
// Do something with data here...
ftruncate($fh, 0); // Empty the file
fwrite($fh, $newData); // Write new data to file
fclose($fh); // Close handle and release lock
} else {
die('Unable to get a lock on file: '.$file);
}

PHP parse_ini_file work on URL?

Does the PHP method parse_ini_file work on an INI file hosted in the cloud? Right now, I have a config file that sits in every single one of my App servers, which could be anywhere from 4-8 at any given time. Making a config change is brutally painful to do by hand for each server.
I've tried the following but to no avail:
$handle = fopen('https://blah.com/config.ini', 'r');
$ini = parse_ini_file($handle, true);
but I get this error:
Warning: parse_ini_file() expects parameter 1 to be a valid path, resource given
Is this even possible? Any ideas?
fopen() is not used like that. Try file_get_contents():
$content = file_get_contents('https://blah.com/config.ini');
$ini = parse_ini_string($content, true);
This may work instead (not tested):
$ini = parse_ini_file('https://blah.com/config.ini', true);
In either case allow_url_fopen needs to be enabled in php.ini.
Fopen returns a pointer to the file, and parse_ini_file accepts file path and opens the file itself.
You should try and use file_get_contents() to get data from the file, which you then pass to parse_ini_string() function which is the same as parse_ini_file() but it takes ini file in a string.

PHP - Failed to open stream: no such file or directory - for existing file

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.

problem with Create File dynamically in php

I want to create File that have Full permission dynamically, that means every change for ID of session create new file .
Unfortunately I faced some problem .
Warning: fopen(test.txt) [function.fopen]: failed to open stream: Permission denied in /home/teamroom/public_html/1/3.php on line 2
Warning: fwrite(): supplied argument is not a valid stream resource in /home/teamroom/public_html/1/3.php on line 3
Warning: fclose(): supplied argument is not a valid stream resource in /home/teamroom/public_html/1/3.php on line 4
code :
<?php
session();
$member_Id=$_SESSION['user_id'];
if (isset($member_Id)){
$file = fopen("test.txt","x+");
fwrite($file,"test");
fclose($file);
}
?>
can you help me ?
or can you tell another way to do this idea ?
It would appear that the process PHP is running as (often the web server, e.g. www-data) does not have write permissions for the folder you're trying to create the file in
(e.g. /home/teamroom/public_html/1/).
You also should be doing error checking on the fopen() call. Then there's the security assect to think of.
you have no permissions to access directory. Use php-function chmod ("/somedir/somefile", 755); or change directory permissions by ftp-client.
And why are you trying to open file with x+ if you need only writing:
Modes:
r - Reading only, beginning of file
r+ - Reading and writing, beginning of file
w - Writing only, beginning of file
w+ - Writing and reading, beginning of file
a - Writing only, end of file
a+ - Writing and reading, end of file
x - Create and open for writing only, beginning of file
x+ - Create and open for reading and writing, beginning of file
If the file does not exist and you use w, w+, a or a+ it will attempt to create the file.
I think you can use w+ or a+
And for your another problem:
<?php
$fp = fopen ('/path/to/file', "r");
while (!feof ($fp))
{
$value = fgets($fp);
if(!empty($value))
{
//Here do what you want with your value
}
}
?>
This was string-by-string reading code. Also you can use file_get_contents(); php-function and work with it lika string.
P.S> Sorry for my english

Categories