Counter won't work when I move it to another server - php

I set up a hitcounter so that each time someone goes to my site, one of 7 different sidebars loads up. There is a file called counter.php that writes to a text file called hitcounter.txt. All the references to files seem to be relative but when I moved them to a new directory at my new host I got this error instead of a happy hit counter:
Warning: fopen(hitcounter.txt) [function.fopen]: failed to open stream: Permission denied in /usr/local/apache/sites/MY-SITE/counter.php on line 5
Counter.php is pasted in its entirety below, line 5 is the first reference to fopen, both counter.php and hitcounter.txt have 775 permissions, same as they did on the old host.
What am I doing wrong? I'm obviously missing something really simple and embarrassing, so feel free to give me any scorn or abuse with while helping me out.
counter.php:
<?php
$count_my_page = ("hitcounter.txt");
$hits = file($count_my_page);
$hits[0]++;
$fp = fopen($count_my_page , "w");
if ($fp) {
fputs($fp , "$hits[0]");
fclose($fp);
}
if($hits[0]<=1)
$random_number=0;
else if($hits[0]>1 && $hits[0]<=2)
$random_number=1;
else if($hits[0]>2 && $hits[0]<=3)
$random_number=2;
else if($hits[0]>3 && $hits[0]<=4)
$random_number=3;
else if($hits[0]>4 && $hits[0]<=5)
$random_number=4;
else if($hits[0]>5 && $hits[0]<=6)
$random_number=5;
else if($hits[0]>6 && $hits[0]<=7)
$random_number=6;
else if($hits[0]>7 && $hits[0]<=8)
$random_number=7;
else if($hits[0]>8 && $hits[0]<=9) {
$random_number=8;
if($hits[0]==9) {
$count_my_page=("hitcounter.txt");
$fp = fopen($count_my_page , "w");
$hits[0]=0;
fputs($fp , "$hits[0]");
fclose($fp);
}
}
?>

It probably has something to do with permissions. Set it to 777 and see what happens. If apache runs with own permissions and is not part of your this might be the reason, but I have a couple of suggestions:
use file_put_contents/file_ get_ contents for simple read/writes!
please use $random_number = rand(0,8) OR mt_rand(0,8) if possible instead of these countless lines and as a bonus get rid of all the file reading/writing
Good luck!
Update
Nothing beats a nice example:
<?php
$random_number = mt_rand(0,8);
file_put_contents("hitcounter.txt", $random_number); /* dont know if you still need it */
?>
If you really want to (btw. NOT random!):
<?php
$file = "hitcounter.txt";
$number = (int)file_get_contents($file);
$number = ++$number % 9;
file_put_contents($file, $number);
?>

First, you don't need 775 permissions. You need 666 permissions on the hitcounter.txt. The PHP file can be 644.
The web server probably isn't a member of the group, depending on the host, so you'd need to give the 'Everyone' group write permissions.
The "Execute" bit is needed for folders but not for individual files, since they are not being executed by the OS.
So you know, the 775 is : Owner, Group, Everyone
Owner = Read + Write + Execute
Group = Read + Write + Execute
Everyone = Read + Execute
666 means
Owner = Read + Write
Group = Read + Write
Everyone = Read + Write
644 means
Owner = Read + Write
Group = Read
Everyone = Read

Try setting permissions to 777. If that doesnt work, could be your host doesnt allow file manipulation on the server

Check your include_path to make sure it has a period (current directory) in it. Not sure why it wouldn't, but you never know if your host is wonkey. You can print out your include path from a PHP script using ini_get:
ini_get('include_path');
Other than that, you probably need different file permissions. Here's a useful site describing a lot of information on file permissions.

Related

permission denied when i try to unlink an image in the folder using php [duplicate]

I make a site and it has this feature to upload a file and that file is uploaded to a server
Im just a newbie to php I download xampp and I run this site that i made in my local machine.
My site is like this you upload a file then that file will be uploaded to a server, but when i tried unlink() because when i try to remove the filename to a database I also want to remove that pic on the server, but instead I got an error and it says "Permission denied".
question:
How can I got permission to use unlink();?
I only run this on my localmachine using xampp
Permission denied error happens because you're trying to delete a file without having enough/right permissions for doing that.
To do this you must be using superuser account or be the same user that have uploaded the file.
You can go to the directory from your command line and check the permissions that are set to the file.
The easiest solution is to loggin as administrator/root and delete the file.
Here is another work around:
// define if we under Windows
$tmp = dirname(__FILE__);
if (strpos($tmp, '/', 0)!==false) {
define('WINDOWS_SERVER', false);
} else {
define('WINDOWS_SERVER', true);
}
$deleteError = 0;
if (!WINDOWS_SERVER) {
if (!unlink($fileName)) {
$deleteError = 1;
}
} else {
$lines = array();
exec("DEL /F/Q \"$fileName\"", $lines, $deleteError);
}
if ($deleteError) {
echo 'file delete error';
}
And some more: PHP Manual, unlink(), Post 106952
I would recommend, always first to check PHP Manual (in case your question concerns PHP), just go to the page with function that you have problems with and just click search CTRL+F in your browser and enter, for example, Windows, and as a result, in your case, you would find at least 7 related posts to that or very close to that what you were looking for.
Read this URL
How to use Unlink() function
I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual error to unlink file. To delete file you must to change file's owern. An example:
<?php
chown($TempDirectory."/".$FileName,666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($TempDirectory."/".$FileName);
?>
So try something like this:
$Path = './doc/stuffs/sample.docx';
chown($Path, 666);
if ( unlink($Path) )
echo "success";
else
echo "fail";
EDIT 1
Try to use this in the path:
$Path = '.'.DIRECTORY_SEPARATOR.'doc'.DIRECTORY_SEPARATOR.'stuffs'.DIRECTORY_SEPARATOR.'sample.docx';

PHP - Creating .txt document in Ubuntu

I am having trouble using fopen() to create a text document for later use as a cookie file.
I have read the documentation for this function, but to no avail.
Notes:
Ubuntu
read / writable ("w+")
I have tried several storage locations including:
/home/jack/Desktop/cookie
/var/www/cookie
/home/jack/Documents/cookie
PHP
echo "debug";
echo "\r\n";
$cookie = fopen("/home/jack/Documents/cookie", "w+");
fclose($cookie);
if(!file_exists($cookie) || !is_writable($cookie))
{
if(!file_exists($cookie))
{
echo 'Cookie file does not exist.';
}
if(!is_writable($cookie))
{
echo 'Cookie file is not writable.';
}
exit;
}
Result
file is not created
Output to browser: debug Cookie file does not exist.Cookie file is not writable.
Other Fun Facts
I have tried using fopen(realpath("/home/jack/Documents/cookie"), "w+")
echo "\r\n" gives a space. Why not a newline?
I believe the problem must be something to do with my permissions to create the file, but I have no problem "right-click" creating the text document on the Desktop.
THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS
echo "debug";
echo "\n";
$jack = "jack";
$cookie = "/home/jack/Documents/cookie";
touch($cookie);
chmod($cookie, 0760);
if(!file_exists($cookie) || !is_writable($cookie))
{
if(!file_exists($cookie))
{
echo 'Cookie file does not exist.';
}
if(!is_writable($cookie))
{
echo 'Cookie file is not writable.';
}
exit;
}
fclose($cookie);
THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS THIS WORKS
Instead of fopen()..
touch() to create
chmod() for permissions
I also added user name jack to www-data group.
chmod($path, 0760) group read / write
Reference
chmod() octal values here.
Look at the documentation for file_exists again. It does not take a file handle as an argument, it takes a string filename. The same is true for is_writable. Even if it did, you are opening the file handle and then immediately closing it, so I'm not sure why you're trying to use the file pointer at all after it's been closed.
You may be correct in that you have improper permissions set, but I would start here, first.
Also, if you're only trying to create the file, you may look into using the touch method, instead:
if( touch( $filename ) ) {
// It worked!
} else {
// It didn't work...
}
The web server is not executing as your user. touch /home/jack/Documents/cookie && chmod 777 /home/jack/Documents/cookie to allow the web server user to access the file.
Note this is BAD in production environments.
It looks like a permission issue. What user is PHP running as? It's likely running as www-data or something similar. You should make sure that the folders you are trying to write to are writable by either the user or group that PHP is running as. If you created those folders while logged in a jack, they probably belong to jack:jack and are not accessible by www-data:www-data.
You can also add jack to the www-data group, to make things a bit easier for development.

PHP mkdir() failing to work

Here's my code; I've renamed the directories, obviously. ;)
$thepath = "/var/www/vhosts/sub.domain.co.uk/web/apps/storage/".$userclient."/evidence/".$scid."/".$doctype."/";
$testdir = is_dir($thepath);
if ($testdir == false) {
mkdir($thepath, 0777);
}
In this case, the following variables apply;
$userclient = '000';
$scid = '9263';
$doctype = 'Insurance Policy';
So, the path should be;
/var/www/vhosts/sub.domain.co.uk/web/apps/storage/000/evidence/9263/Insurance Policy/
I know this works, EVERYWHERE else in my code, I have other applications using an almost identical setup. But the one above, appears to be tripping up on /evidence/ - it sets the permissions to 755, but will then create the directories per time I run the code, if I set evidence to 777 (Octal).
I get the following error message using;
if (!#mkdir($thepath)) {
$error = error_get_last();
echo $error['message'];
}
mkdir(): No such file or directory
Any help would be greatly appreciated, I have to finish this application by Thursday - and this file upload part is the last bit!
Thank you!
PHP can't find directory in which you want to create other directory.
You need to set $recursive param as true:
mkdir($thepath, 0777, true);
Maybe you want to try mkdir($path,$mode,true) to create missing links as well?

How to get permission to use unlink()?

I make a site and it has this feature to upload a file and that file is uploaded to a server
Im just a newbie to php I download xampp and I run this site that i made in my local machine.
My site is like this you upload a file then that file will be uploaded to a server, but when i tried unlink() because when i try to remove the filename to a database I also want to remove that pic on the server, but instead I got an error and it says "Permission denied".
question:
How can I got permission to use unlink();?
I only run this on my localmachine using xampp
Permission denied error happens because you're trying to delete a file without having enough/right permissions for doing that.
To do this you must be using superuser account or be the same user that have uploaded the file.
You can go to the directory from your command line and check the permissions that are set to the file.
The easiest solution is to loggin as administrator/root and delete the file.
Here is another work around:
// define if we under Windows
$tmp = dirname(__FILE__);
if (strpos($tmp, '/', 0)!==false) {
define('WINDOWS_SERVER', false);
} else {
define('WINDOWS_SERVER', true);
}
$deleteError = 0;
if (!WINDOWS_SERVER) {
if (!unlink($fileName)) {
$deleteError = 1;
}
} else {
$lines = array();
exec("DEL /F/Q \"$fileName\"", $lines, $deleteError);
}
if ($deleteError) {
echo 'file delete error';
}
And some more: PHP Manual, unlink(), Post 106952
I would recommend, always first to check PHP Manual (in case your question concerns PHP), just go to the page with function that you have problems with and just click search CTRL+F in your browser and enter, for example, Windows, and as a result, in your case, you would find at least 7 related posts to that or very close to that what you were looking for.
Read this URL
How to use Unlink() function
I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual error to unlink file. To delete file you must to change file's owern. An example:
<?php
chown($TempDirectory."/".$FileName,666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($TempDirectory."/".$FileName);
?>
So try something like this:
$Path = './doc/stuffs/sample.docx';
chown($Path, 666);
if ( unlink($Path) )
echo "success";
else
echo "fail";
EDIT 1
Try to use this in the path:
$Path = '.'.DIRECTORY_SEPARATOR.'doc'.DIRECTORY_SEPARATOR.'stuffs'.DIRECTORY_SEPARATOR.'sample.docx';

How can I save a file in PHP to a directory higher than current?

The script is in myusername/public_html/item/index.php
code to save file:
$filename = $_SERVER['DOCUMENT_ROOT'].'/../data/guestbook.txt';
$filehandle = fopen($filename, 'ab+') or die("<p>Unable to create the file!</p>\n".$filename);
flock($filehandle, LOCK_EX) or die("<p>Unable to lock the file!</p>\n");
fwrite($filehandle, $new_entry) or die("<p>Unable to write to the file!</p>\n");
fclose($filehandle);
For some reason it fails on the fopen and the filename is actually ends up being literally with the /../ instead of navigating to the proper path.
What to do, what to do?
you can code like this if the php script is in the item folder and item and data are at the same level in the directory hierarchy
$savedir = '../data/';
$filename = $savedir.'guestbook.txt';
make sure apache user has the write access to the directory by "chown -R apache:apache" and "chmod 755".
Probably the " /../ " in your code is giving the error. Try removing the first forward slash.
For some reason it fails on the fopen
There is no "some reasons" in programming. There are always a certain reason.
And you have to know it.
filename is actually ends up being literally with the /../
That's exactly what you wrote, nothing to complain of.
How can I save a file in PHP to a directory higher than current?
Technically you are setting it correct.
But there can be another reason, other than wrong way of the path creation.
Yes, there always can be many reasons for the program to fail!
What to do, what to do?
Run this code and see what it says.
ini_set('display_errors',1);
error_reporting(E_ALL);
$filename = $_SERVER['DOCUMENT_ROOT'].'/../data/guestbook.txt';
file_put_contents($filename,$new_entry);
it will tell you the reason why it fails.

Categories