PHP - Creating .txt document in Ubuntu - php

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.

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 file_exists() only works once in the same function

I have a php function that renames two separate image files from a temporary to permanent path after first confirming that the temporary path exists.
When it checks for the fist file it works fine but, for some reason, the second file never passes the if(file_exists()) even though I can confirm with 100% certainty that the file path being checked does, in fact, exist.
The image files have different names but the codes are otherwise structured exactly the same so I can't see why one would work and the other wouldn't.
if(file_exists('temp/'.strtolower($option['image1']))){
$path1 = 'images/'.strtolower($option['image1']); // upload directory
$tmp1 = 'temp/'.strtolower($option['image1']);
if(rename($tmp1, $path1)){
$error = 0;
}else{
$error = 4;
}
}
if(file_exists('temp/'.strtolower($option['image2']))){
$path2 = 'images/'.strtolower($option['image2']); // upload directory
$tmp2 = 'temp/'.strtolower($option['image2']);
if(rename($tmp2, $path2)){
$error = 0;
}else{
$error = 5;
}
}
Is there an issue with calling file_exists() twice? How else can I check for both paths?
Edit
As per Marco-A's suggestion, I added clearstatcache(); between the two if/then blocks and it worked like a charm.
The only two possibilities (if you're absolutely sure the file path exists) I'm seeing are either 1.) a stat cache problem (you can clear the cache with clearstatcache) or 2.) a permission issue. Consider this:
$ touch /tmp/locked/file
$ php is_file_test.php
$ bool(true)
$ chmod -x /tmp/locked
$ php is_file_test.php
$ bool(false)
So it might be, that the parent directory of that file doesn't have the x (executable) permission bit set. This prevents any process from iterating and accessing the directory's content.
The uploaded file names can have uppercase characters. If you use strtolower in the file_exists function, you probably wouldn't be looking for the original file path.
if(file_exists('temp/' . strtolower($option['image']))){
// ...
}
Should be changed to:
if(file_exists('temp/' . $option['image'])){
// ...
}

Can PHP resolve a Mac alias?

I am running MAMP and using PHP to read the names of all the files in a given folder. I would like to create an alias for certain images in another folder, and have PHP resolve these to their actual path. I know how to create symlinks that will work this way, but I would like to allow non-tech savvy web owners to use the Mac OS features that they are familiar with.
I have created a PHP script in the same folder as a alias that I have named test:
<?php
if (is_link ("test")) {
echo "is link";
} else {
echo "is not link";
}
?>
This echoes "is not link". I have tried using the fread() command on the link, but PHP seems to hang. It neither logs an error nor responds. I have tried opening the alias in a hex editor to see what it contains... but the hex editor opens what seems to be a huge file (if the alias is to a file), or opens the target folder (if the alias is to a folder).
Is there a way to help PHP to resolve the path in the alias? Is there an AppleScript function that I can call?
Chances are you're not referring to an actual symbolic link. If you're dealing with Finder Aliases, you can use the workaround found in the comments for the is_link docs.
Here are the contents of the comment (to avoid a link-only answer for posterity):
if( getFinderAlias( $someFile , $target ) ) {
echo $target;
}
else {
echo "File is not an alias";
}
function getFinderAlias( $filename , &$target ) {
$getAliasTarget = <<< HEREDOC
-- BEGIN APPLESCRIPT --
set checkFileStr to "{$filename}"
set checkFile to checkFileStr as POSIX file
try
tell application "Finder"
if original item of file checkFile exists then
set targetFile to (original item of file checkFile) as alias
set posTargetFile to POSIX path of targetFile as text
get posTargetFile
end if
end tell
end try
-- END APPLESCRIPT --
HEREDOC;
$runText = "osascript << EOS\n{$getAliasTarget}\nEOS\n";
$target = trim( shell_exec( $runText ) );
return ( $target == "" ? false : true );
}
Here's some explanation about symlinks vs. aliases. Really though, you should avoid using Apple's abstractions and just create a symlink:
ln -s /path/to/file /path/to/symlink

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 to check if a file has access denied and how to give rights(777) to a file in php?

I am working in php on ubuntu. When I use any image on web page which has denied access, there is warning on page. I want to check it before displaying and if it does not have rights to open then give it access to open. As we do in terminal command.
chmod 777 myimage.jpg
How to check this and give full access to a file in php.
Thanks
Check the function is_readable() and is_writable().
Example:
$filename = '/home/myuser/example.txt';
if (is_readable($filename) && is_writable($filename))
{
echo "File has read and write permissions.";
}
Use is_readable() to check whether or not the file is readable by the PHP process.
Use chmod() to change the permissions of the file.
Also, you can use is_writable() to test if you can write to the file, and file_exists() to check to see if the file even exists.
One thing you can do is use the fileowner function (and posix_getpwuid) and compare to whatever your PHP user is (often www-data).
If the users are the same you will be able to change permissions if you need to. But first check if the file is writeable anyway.
UPDATE: the chmod and chown functions return TRUE on success and FALSE on failure, so it would be a good idea to put them in an if clause. You can suppress the error output by setting error_reporting(0); at the beginning of the script, or using the # symbol like this:
if ( #chmod($filename, 0666) ) {
// do whatever with file
}
else if ( #chown($filename, 1000) ) {
chmod($filename, 0666);
// do whatever with file
}
else {
// can't change permissions
}
Doing this on the fly from PHP every time a file is referenced is a very inefficient way to manage your files. It also requires all file access to be mediated via a PHP script. Also, allowing content to be world writeable is rather messy from a security point of view.
I'd go with running an admin script once to tidy up the permissions for your existing files, then fixing the problem when new files enter the system.
Sure, if you've not got shell access / shell access as someone other than the webserver uid, then you'll have to implement this using PHP (and therefore readdir/is_readable/is_writeable).
Without knowing how files appear on your webserver its hard to recommend a specific solution.
C.
One thing you can do to make the file readable / writable is to call this function upon file / folder creation without the second argument:
function AutoChmod($path, $chmod = null)
{
if (file_exists($path) === true)
{
if (is_null($chmod) === true)
{
$chmod = (is_file($path) === true) ? 644 : 755;
if (in_array(get_current_user(), array('apache', 'httpd', 'nobody', 'system', 'webdaemon', 'www', 'www-data')) === true)
{
$chmod += 22;
}
}
return chmod($path, octdec(intval($chmod)));
}
return false;
}
Example:
AutoChmod('/path/to/file/you/just/created.txt');
This function will give appropriate permission whether you are working with SuPHP / SuExecPHP or not.
To check permissions you just need to use the functions is_readable() and is_writable().

Categories