Hello i need some help with this code in the install.php which has to run first before the program but it brings an error pointing on the fflush i don't know what to do please help?
<?php
fflush();
authTableCreate();
announceTableCreate();
classTableCreate();
studentTableCreate();
classmembersTableCreate();
attendanceTableCreate();
assignmentTableCreate();
messageTableCreate();
supportTableCreate();
if (!authCheckUserExists('admin')) { // this is their first install probably
$randpass = 'admin' . mt_rand();
authAddUser('admin', $randpass, 100, 100); // create default superuser account
announceAddAnnouncement('Welcome', 'This is the default start page for IntraSchool. You should change this to something that describes how the system works within your school.');
?>
<p>Congratulations! You have successfully setup <em>IntraSchool</em>. You may now login with the username <em>admin</em> and password <em><?=$randpass?></em>. Please change the password to something you can remember.</p>
<?php
} else {
?>
<p>The installation script has reinitialized any deleted tables.</p>
<?php
}
page_footer();
?>
fflush() requires the handle of the file to be flushed. It is likely a typo for flush(), however as it's apparently at the start of the file that would do nothing at all. You should just delete the line.
It's only a warning though, so the rest of the script has probably been executed. If it's a once-only setup script then you probably do not need to run it again.
Here's the documentation - always a good place to start.
My understanding of your code is limited, so I'm not sure what you're trying to accomplish here (in particular, it looks like you're doing database operations, for which fflush should not be necessary). That said, here's a little background:
fflush flushes an open file to disk. You need to provide it with a file handle to flush.
When you're writing to a file on your disk, the operating system will often store up a bunch of your data and write it all to the disk at one time, rather than writing each byte as you send it. This is primarily for performance reasons. Sometimes, however, you need to get that data written at a particular point in your program. That's what fflush is for. But for fflush to work, you need to tell it what file you're talking about - that's the file handle mentioned in the documentation.
Related
I try to execute a command "wget" to download a file on my server A and then execute a python who will scrypt argument in this file.
My script:
switch ($_POST["parse"]) {
case 'parse1':
shell_exec("wget http://localhost/".$file_path);
shell_exec("python /opt/lampp/htdocs/mysite/api/scripts/script_parse.py ".$file_path." 1");
echo $file_path;
break;
default:
echo "no";
break;
}
However (I'm with local xampp under debian), the file is not downloaded and I have a page that loads into space when I try to execute the script (with or without file) but that does nothing .
So I'm looking since last night but I can not.
Besides, I like to avoid that the page load until the end of script execution.
Instead of shell_exec() and wget to download the file, use "file_get_contents()`. It supports both the HTTP and the HTTPS protocols, among many others, and it'll also give you an informative error message if downloading fails.
You will also need to add some error handling to your code, as stated in the comment by Arek. Since that is the only way you can properly handle the situations where something goes wrong, and they will. Not only for your sake, to make it easier to detect and debug, but also for your users.
Read the PHP manual, find out what values the different functions return in case of errors, and check against these. If any of the functions does return an erroneous value, then show an error message to the user and abort the rest of business logic (the stuff your code is really meant to do).
I have two php cli scripts. The first one pipes data into the second one.
I want the second one to prompt the user for a confirmation.
Is this possible?
I'm using wordpress' php-cli-tools, but my problem seem to be applicable to php in general, from what I see with my basic tests. (i.e. fgets(), readline, etc )
I can never get the prompt to work, since it looks like it will always read an EOT character from the previous input, even if I've already read it...
Then, later, when I prompt by using fwrite for output and then fgets() for input, nothing happens. Program is just waiting for something to happen... Not sure what...
If I use the library I get the error 'Caught ^D during input'. No luck with readline either...
Has anyone ever done this before?
Thank you so much!
The problem isn't really specific to PHP, it applies to any language. On Unix, you can read from /dev/tty instead of from standard input if you want to ignore input redirection and read from the terminal directly.
function prompt_user($prompt) {
$terminal = fopen("/dev/tty", "r+");
if ($terminal) {
fputs($terminal, $prompt);
return fgets($terminal);
}
}
I have a PHP page that should be accessible only by one user at a time. It's a kind of "poor man's cron": A "Javascript" file, that is requested in the background. At the moment I'm thinking of creating a lock file like this:
if(file_exists($lockfile) && filemtime($lockfile) + EXPIRES_AFTER > time() ) {
die("// Page is locked.");
}
touch($lockfile);
// do stuff
unlink($lockfile);
echo "// Cron stuff was run";
But I'm not sure if there could be a very short window of opportunity between the file_exists and the touch call where another page request could check for the file existence and see that it isn't there. We're probably talking microseconds here so I would like top know at which amount of requests I really need to start worrying.
If you want to do this really precisely, then use a different approach, because there IS some time between the check and the lock.
Two possible implementations:
Use flock:
https://secure.php.net/manual/en/function.flock.php
Use something like STM:
E.g. open the lockfile for append, write something into it, close the handle. Then read the file back, and if it only has what you wrote into it then you have acquired the lock.
Other than that, your original code would probably not cause any problems.
There is no atomicity in the code you wrote, so yes, there is a race condition.
Your code has a race condition. Instead, dio_open the file with O_EXCL. This will fail if the file already exists. Unlink it when you're done.
The only thing to watch out for is if the system or the script crashes while the file exists, the script will never run again. If you are worried about this, check the age of the file (if you fail to create it) and if it's older than the longest the script could ever take, unlink it.
Using flock is another option.
Given a simple code like :
$file = 'hugefile.jpg';
$bckp_file = 'hugeimage-backup.jpg';
// here comes some manipulation on $bckp_file.
The assumed problem is that if the file is big or huge - let´s say a jpg - One would think that it will take the server some time to copy it (by time I mean even a few milliseconds) - but one would also assume that the execution of the next line would be much faster ..
So in theory - I could end up with "no such file or directory" error when trying to manipulate file that has not yet created - or worse - start to manipulate a TRUNCATED file.
My question is how can I assure that $bckp_file was created (or in this case -copied) successfully before the NEXT line which manipulates it .
What are my options to "pause" , "delay" the next line execution until the file creation / copy was completed ?
right now I can only think of something like
if (!copy($file, $bckp_file)) {
echo "failed to copy $file...\n";
}
which will only alert me but will not resolve anything (same like having the php error)
or
if (copy($file, $bckp_file)) {
// move the manipulation to here ..
}
But this is also not so valid - because let´s say the copy was not executed - I will just go out of the loop without achieving my goal and without errors.
Is that even a problem or am I over-thinking it ?
Or is PHP has a bulit-in mechanism to ensure that ?
Any recommended practices ?
any thoughts on the issue ? ??
What are my options to "pause" , "delay" the next line execution until the file is creation / copy was completes
copy() is a synchronous function meaning that code will not continue after the call to copy() until copy() either completely finishes or fails.
In other words, there's no magic involved.
if (copy(...)) { echo 'success!'; } else { echo 'failure!'; }
Along with synchronous IO, there is also asynchronous IO. It's a bit complicated to explain in technical detail, but the general idea of it is that it runs in the background and your code hooks into it. Then, whenever a significant event happens, the background execution alerts your code. For example, if you were going to async copy a file, you would register a listener to the copying that would be notified when progress was made. That way, your code could do other things in the mean time, but you could also know what progress was being made on the file.
PHP handles file uploads by saving the whole file in a temporary directory on the server before executing any of script (so you can use $_FILES from the beginning), and it's safe to assume all functions are synchronous -- that is, PHP will wait for each line to execute before moving to the next line.
is there a way for me to check to see if a file is copied before continuing to execute a php loop?
i have a for loop, and within the loop it is going to copy a file. now, i want it so that it waits until the current file is copied before continuing the loop.
example:
for ($i = 1; $i <= 10; $i++)
{
$temp = $_FILES['tmp_name'];
$extension = '.jpg';
copy("$temp_$i_$extension", "$local_$i_$extension");
// not sure what to do here
if (FILE_DONE_COPYING())
{
CONTINUE_LOOP();
}
else
{
PAUSE_LOOP();
}
}
thats just an example. i have no clue how to do this...can anyone chime in?
That's what copy() does in PHP - it blocks until the file is copied. There's nothing you need to do, except checking the return value to see if the operation was successful.
PHP is taking it line by line, step by step, so it's waiting until copy() is completed
for ($i = 1; $i <= 10; $i++)
{
$temp = $_FILES['tmp_name'];
$extension = '.jpg';
$result = copy("$temp_$i_$extension", "$local_$i_$extension");
if($result){
//done
}
else{
//failed
}
}
copy returns true on success and false on failure. Check for that.
Unless you go through the trouble of using threading and have copy fired asynchronously, PHP will not move to the line after copy until after it has completed.
copy does wait for completion before continuing execution. It is a syncronous call. But, it can return false if it didn't work, and your copy wont work since $temp_ and $i_ are not defined variables. So maybe you are thinking the copy isn't finishing, when it actually just isn't working at all.
You should use:
copy("{$temp}_{$i}_$extension", "{$local}_{$i}_$extension");
OR
copy($temp.'_'.$i.'_'.$extension, $local.'_'.$i.'_'.$extension);
What makes you think that copy() will return before it has finished?
You could of course compare filesize of original file and copy to be sure the process is complete.
You could use a while loop with sleep calls to delay checking, and just exit the while loop once the file exists under the new name.
I know this is an ancient question but I feel I really need to talk about this problem. COPY is a great command - BUT - it does not work all of the time. I can honestly tell you this. Why? Why does it not always work? Simple - the Operating System is at fault. Here are two examples. One is using a standard disk drive and the second one deals with a Ram disk. The COPY command reads CHUNKS of a file and writes these chunks out to the destination. This means it really does NOT just do a File_get_contents but instead does the fopen(IN), fopen(OUT), while( !EOF(IN) ){ fread(IN), fwrite(OUT) } and then fclose(IN), and fclose(out). It should be noted that these commands try to make sure everything goes ok but if the disk drive buffers what it does - then the file might take a second or two to finish. This can be seen by having a file_exists() on the output file's name. It can come back as FALSE(it IS NOT there). This is because the disk drive's hardware has not caught up with the commands.
I even installed the AMD RamDisk software and ran a program using the above commands (both file_get_contents->file_put_contents and the fopen-fread/fwrite-fclose commands). The same thing happened then also. Every now and then (not always) the file_exists() function returned FALSE because the test got there before the file had finished being created. Don't ask me why - it just would do this.
So what do I suggest? Use the SLEEP() command. Maybe use three(3) seconds (so SLEEP(3);) -after- the COPY() command. I also determined that a CHMOD(, 0777); was a good idea also. With a SLEEP() command after it so it has time to apply the changes. (Which is probably closer to one second).
Now, remember - everyone's hardware is different. So some hardware might work better or faster than the one I am using. So - this is one of those - try it if you are having problems. Or don't - if you are not having problems. It is that simple. So - this is happening to me - I'm using it - it works now that the system gets three seconds to breath - but it might not do anything for you - who has an atomic powered Willy-Wonka mobile which does the impossible before breakfast.
Got it? Good. :-)