I'm new to PHP. I planned to create folder, sub folder, into that file depends on user Input.
Folder and sub folders has been created successfully.
Finally I try to create a file its showing bellow error.
fopen(upload/localhost/hrms): failed to open stream: Permission denied
in C:\xampp\htdocs\ssspider\index.php on line 205
My code is:
$dir = "http://localhost:8080/hrms/index.php";
//make directory
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
mkdir($directoryForClient);
$splitePath = explode("/", $folderPath);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>";
mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen($dir,"w");
if($myFile)
{
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}
Please help me to find out my problem?
Edit: Thanks. I got an error. In fopen I didn't mention file name . Now its working fine. Thanks
because you open a directory , fopen function just open file. your code is fill with error , just Refer to the following:
<?php
//make directory
$host = "aa"; //define $host variable
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
#mkdir($directoryForClient);
$splitePath = explode("/", $directoryForClient);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>2";
#mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen("upload/aa.txt","w");
if($myFile)
{
$returned_content = "hello world"; //define variable and his content before write to file.
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}
Related
I currently have a working script that counts the number of views and stores them in a .txt file.
It's working fine but how do I make it so that it limits to your IP Address?
I tried this but it's not counting.
// Get filename of Page
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php');
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
// Remove .php extension
$counterName = basename($pageName, ".php").".txt";
// Open the file for reading
// "a+" Read & write the file. Create file if not exist.
$fp = fopen($counterName, "a+");
$fpIP = fopen("ip_".$counterName, "a+");
fwrite($fpIP, $ip."-");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Reopen the file and erase the contents
$fp = fopen($counterName, "w");
$ipRead = file_get_contents('ip_index.txt');
if(strpos($ipRead, "$ip") !== FALSE) {
echo $count;
}
else {
fwrite($fp1, $count);
echo $count;
}
fclose($fp);
Below is my updated code with Barmar's code (fully working) which will show each individual visitor how many times they have been to your page based on their IP address.
// Get filename of Page
$pageName = basename($_SERVER["SCRIPT_FILENAME"], '.php');
// Remove .php extension
$counterName = basename($pageName, ".php").".counter";
// Get IP
$ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
$count_text = #file_get_contents($counterName);
$counters = $count_text ? json_decode($count_text, true) : array();
if (isset($counters[$ip])) {
$counters[$ip]++;
} else {
$counters[$ip] = 1;
}
file_put_contents($counterName, json_encode($counters));
echo $counters[$ip];
Store an associative array that's keyed off $ip in the counter file.
$count_text = #file_get_contents($counterName);
$counters = $count_text ? json_decode($count_text, true) : array();
if (isset($counters[$ip])) {
$counters[$ip]++;
} else {
$counters[$ip] = 1;
}
file_put_contents($counterName, json_encode($counters));
echo $counters[$ip];
You don't need the ip_XXX.txt file in this design.
I am using pdftk library for modify the pdf files. but i am getting the chmod(): Invalid argument error.
Following is my code :
include('fillpdf/createXFDF.php');
$fdf_file = 'fillpdf/acord.fdf';
$acord = array();
$acord['******'] = 'a';
$acord['******'] = 'a';
$pdf_file_url = 'http://localhost/******/fillpdf/Cancellation.pdf';
$fdf = createXFDF( $pdf_file_url, $acord );
// print_r($fdf); die;
if ($fp = fopen($fdf_file, 'w')) {
chmod($fdf, 777);
fwrite($fp, $fdf, strlen($fdf));
$CREATED = TRUE;
} else {
echo 'Unable to create file: ' . $fdf_file . '<br><br>';
$CREATED = FALSE;
}
// var_dump($CREATED); die;
fclose($fp);
$command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
exec($command);
I have given all the necessary permission to folder and files. but don't know what is wrong??
Thanks in advance!!!
Why you need to give chmod($fdf,0777); to $fdf. It's not even the file. as per your code the $fdf = createXFDF( $pdf_file_url, $acord ); is calling function and it's not file. so just comment the chmod($fdf,0777); line and check your code is working or not??
Hope it helps!!!
Try like this...For chmod() function first number is always zero.
chmod(file,mode);
The mode parameter consists of four numbers:
1.The first number is always zero
2.The second number specifies permissions for the owner
3.The third number specifies permissions for the owner's user group
4.The fourth number specifies permissions for everybody else
include('fillpdf/createXFDF.php');
$fdf_file = 'fillpdf/acord.fdf';
$acord = array();
$acord['******'] = 'a';
$acord['******'] = 'a';
$pdf_file_url = 'http://localhost/******/fillpdf/Cancellation.pdf';
$fdf = createXFDF( $pdf_file_url, $acord );
// print_r($fdf); die;
if ($fp = fopen($fdf_file, 'w')) {
chmod($fdf,0777);
fwrite($fp, $fdf, strlen($fdf));
$CREATED = TRUE;
} else {
echo 'Unable to create file: ' . $fdf_file . '<br><br>';
$CREATED = FALSE;
}
// var_dump($CREATED); die;
fclose($fp);
$command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
exec($command);
I am trying to find the WAV file duration using the following code.
if ( !file_exists($location_wmv.$name_wmv) ) {
echo "<BR> File Does not Exist<BR>";
} else {
echo "<BR> File Exist<BR>";
}
$file = $location_wmv.$name_wmv;
$fp = fopen($file, ‘r’);
$size_in_bytes = filesize($file);
fseek($fp, 20);
$rawheader = fread($fp, 16);
$header = unpack(‘vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits’,
$rawheader);
$sec = ceil($size_in_bytes/$header['bytespersec']);
$duration_wmv = $sec;
echo "<BR> Raw Suration.". $duration_wmv . "<BR>";
$duration_wmv = gmdate("H:i:s", $demo_song_duration_sec);
echo "<BR>WAV Duration".$duration_wmv;
Here the file_exists function says that file Exist. But the fopen says failed to open stream: Undefined error: 0
The file is actually present in the folder. But still I get this error.
This:
$fp = fopen($file, ‘r’);
looks iffy. Are those backticks?
Maybe try:
$fp = fopen($file, 'r');
(simple quotes)
I'm having a problem trying to figure out a way to check for a file and if it exists check the next and so on.
I'm not familiar enough with loops so looking for help.
I'm putting together a small set of php forms to help me do rental inspections. The form will create a page for each area/item for the inspection with a photo and description of the problem if any. The form for the photo's is already working and not part of this.
I'm matching the paper form they will have me use. This could save me an hour or so on the windoze spreadsheet they would want me to put everything in and then print to PDF.
My laptop/PC is Linux. Would also save me having to get a Win machine or tablet.
I have everything else working. Just the page creation is giving me fits. I understand a loop should be the easiest to save having to write the file_exists search for each page up to 40 pages.
Here is a snip of were I'm at. The location this is sitting is not publicly accessible.
Thanks in advance
Bob
<?php
// This will be accessed for each area/item inspected
$dirpath = "/localhost/rent.inspect/";
// Get POST info from form page
$a1 = $_POST["a1"];
$a2 = $_POST["a2"];
$a3 = $_POST["a3"];
$a4 = $_POST["a4"];
…...
$a40 = &_POST[“a40”];
// File names we write to can be any name
$FileName1 = "$dirPath/page1.php";
$FileName2 = "$dirPath/page2.php";
$FileName3 = "$dirPath/page3.php";
$FileName4 = "$dirPath/page4.php";
…...
$FileName3 = "$dirPath/page39.php";
$FileName4 = "$dirPath/page40.php";
// Check if the first file is already created.
// If not create it and write, if is does exist check for the
// next file. Keep checking until one not created is found.
// Should never get to the 40th file at this time.
// Check if first file has already been created.
if(file_exists("$FileNam1"))
{
if(file_exists("$FileNam2"))
{
if(file_exists("$FileNam3"))
{
// Check for next one.... Should never see 40
// but keep checking to it just in case something is added
}
else
{
$myfile = fopen("$dirPath/$filename3", "w") or die("Unable to open file!");
$txt = "<font size=\"2\">$a1 $a2 $a3</font></b><br /><br />";
fwrite($myfile, $txt);
fclose($myfile);
}
}
else
{
$myfile = fopen("$dirPath/$filename2", "w") or die("Unable to open file!");
$txt = "<font size=\"2\">$a1 $a2 $a3</font></b><br /><br />";
fwrite($myfile, $txt);
fclose($myfile);
}
}
else
{
$myfile = fopen("$dirPath/$filename1", "w") or die("Unable to open file!");
$txt = "<font size=\"2\">$a1 $a2 $a3</font></b><br /><br />";
fwrite($myfile, $txt);
fclose($myfile);
}
?>
Several ways to do so, an easy one fitting your current problem could be :
for ($i = 1; $i < 41; ++$i) {
if (!file_exists($dirPath . '/page' . $i . '.php')) {
// fopen, fwrite, fclose ...
break;
}
}
You could also improve your variable initializations using an array to store your variables, even more when it's all about changing an increment integer.
Here is an example, not really useful, but explaining how you could do :
for ($i = 0; $i < 41; ++$i) {
$myVar['a' . $i] = $_POST['a' . $i];
}
you can check till the file exixts and increment the counter
$filepath = "/somepath/";
$filename = "FileNam"
$i=1;
$pathtocheck = $filepath + $filename + $i;
while ( file_exists ($pathtocheck ))
{
$i++
$pathtocheck = $filepath + $filename + $i;
}
// your code for file write will be here
// this code will check is there file exist if not while will break otherwise it will continue till no file like FileNam1 ,FileNam2 and so on ...
I use newrelic to keep track of anything on my website and I always get this error:
Error message: E_WARNING: fclose() expects parameter 1 to be resource, boolean given
Stack trace: in fclose called at /etc/snmp/bfd-stats.php (68)
This is how /etc/snmp/bfd-stats.php looks like
<?php
$a = 0;
$ptr = 0;
$any = 0;
$mx = 0;
$ns = 0;
$cname = 0;
$soa = 0;
$srv = 0;
$aaaa = 0;
$txt = 0;
$total = 0;
if(file_exists('/etc/snmp/bfd-log-pos.stat')) {
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','r');
$string = fread($lfh,2087);
$res = explode(',',$string);
fclose($lfh);
}
else {
$res = array();
$res[0] = 0;
$res[1] = 0;
}
if(file_exists("/var/log/bfd_log.1")) {
$stats = stat('/var/log/bfd_log.1');
if($stats[10] > $res[0]) {
$res[0] = 0;
$res[1] = 0;
}
}
$fh = fopen('/var/log/bfd_log', 'r');
fseek($fh,$res[1]);
$blocks = 0;
if(!$fh) {
echo "Error! Couldn't open the file.";
} else {
while (!feof($fh)) {
$data = fgets($fh);
if(preg_match('/executed\sban/',$data)) {
$blocks++;
}
}
}
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','w');
$timestamp = time();
$pos = ftell($fh);
fwrite($lfh,"$timestamp,$pos");
fclose($lfh);
if(!fclose($fh)) {
echo "Error! Couldn't close the file.";
}
print("bfd_blocks\n$blocks");
?>
On line 40: $fh = fopen('/var/log/bfd_log', 'r'); I looked at the directory /var/log and there is no file called bfd_log, I dont know if I have to create it by myself or it is automatically created.
Can anyone help me on fixing this error, Thanks in advance.
The error indicates that you are trying to pass a variable with a boolean value (true/false) to a function that needs a resource instead of a boolean value.
Please make sure that before you use resources from variables, the function that returns the resource has not run into trouble. Only on success perform the other functions that use this resource/variable.
$fh = fopen('/var/log/bfd_log', 'r');
// check fh before other functions use this variable
if (!$fh) {
echo "Error! Couldn't open the file.";
} else {
// perform task with resource $fh
fseek($fh, $res[1]);
[...]
$lfh = fopen('/etc/snmp/bfd-log-pos.stat', 'w');
// check before other code block is executed and use this variable
if( $lfh )
{
// perform task with resource $lfh
$pos = ftell($fh);
fwrite($lfh, "$timestamp,$pos");
fclose($lfh);
fclose($fh);
[...]
} else {
// lfh error
}
}
If you always check before using variables, you won't run into this error anymore.
I wrestled with this problem and could not find the answer until I separated my write check (put it first) from the actual file write code. So before I would open the file fopen/fwrite then do the is_writable check and then do the fclose and i would get this error.
To resolve I moved the is_writable and variable declaration before the fopen/fwrite and the error went away. Shown below (former php code position shown in comments) The first comment did help me realize this... Thank you.
$myfile = "/var/www/html/newfile.txt";
if (is_writable($myfile)) {
echo "The file is writable";
}
else {
echo "The file is not writable";
}
$txt = "$name, $email, $command, $searchtype, $keyword \n";
$myfile = fopen('/var/www/html/newfile.txt', 'w') or die("Unable to open file!");
fwrite($myfile, $txt);
// $myfile = "/var/www/html/newfile.txt";
// if (is_writable($myfile)) {
// echo "The file is writable";
// }
// else {
// echo "The file is not writable";
// }
fclose($myfile);
Try
$fh = fopen('/var/log/bfd_log', 'a+');
a+ mode will create the file if it does not exists