PHP error_log writes in one folder, not another - php

I have a simple PHP script that writes errors to an error log file, and also prints part of the error to the screen.
I first developed it in my "sandbox" project inside Aptana Studio (but really, they're just directories) where it worked beautifully. However, when I copied it over to my "production project" (again, it's really just a different directory on the webserver), it no longer logs messages to the errorlog.log file. All permissions are the same, and in fact I made the script executable (it was not in the other directory), and gave the directory full permissions (chmod 777). The errorlog.log file already exists as an empty file and is writable, just as it was in the sandbox.
Here is the code:
<?php
/* logerrors.inc.php - Prints a "formatted" error message which will be displayed
* within a handler (i.e. the notification bar) on the front end and writes
* the error to a text log.
*/
date_default_timezone_set('America/New_York'); // Required to avoid errors.
define("LOG_LOCATION", "errorlog.log"); // The location of the log file
function writeError($error_string, $technical_info_string = ""){
$tech_log_entry = ""; // We should only log techinical information
// if it's provided
if($technical_info_string != ""){
$tech_log_entry = "\n- Technical Info Provided: ". $technical_info_string;
}
// Writes a log entry with full details.
error_log("[ERROR: ".date('Y-m-d H:i:s') . "]\n- Error Displayed: ". $error_string .
$tech_log_entry ."\n\n",
3, LOG_LOCATION);
echo "error: " . $error_string; // Emits the $error_string as output
exit();
}
?>
Interestingly, the echo command at the bottom of the script is working just fine, so it's obviously not erroring out on the error_log function. It just isn't working.
Any thoughts as to where to look next or what else could be causing this?

Related

PHP rename() function not working properly. Alternative access is denied (code: 5)

I am facing a strange situation with php rename() function. I download a file using API and then moved that file to destination folder.
$download_path =
C:\Users\JOHN\AppData\Local\Temp/downloaded_folder/downloaded_file.png
$moving_path = C:\xampp\htdocs\project-1/images/downloaded_file.png
Every time downloading is working perfectly and file downloaded
The rename() function is working alternatively. ie on first time it works second time fails. 3rd time ITS works 4th time fails etc.
ie first time file moved . and second time i am getting warning
Warning:
rename(C:\Users\JOHN\AppData\Local\Temp/downloaded_folder/downloaded_file.png,C:\xampp\htdocs\project-1/images/downloaded_file.png):
Access is denied (code: 5)
Warning: copy(C:\xampp\htdocs\project-1/images/downloaded_file.png):
Failed to open stream: Permission denied
Please see my code below.
if (file_exists($moving_path)) {
#unlink($moving_path);
}
if (file_exists($download_path) && !file_exists($moving_path)) {
if (!rename($download_path, $moving_path)) {
if (copy ($download_path, $moving_path)) {
echo 'no rename but copied';
} else {
echo 'not moved';
}
} else {
echo 'moved';
}
#rmdir(dirname($download_path))
}
Here what happen is first time it's moved and downloaded_file.png coming inside project-1/images folder & echo moved and second time there is no file coming and echo not moved .
Third time downloaded_file.png coming inside project-1/images folder & echo moved and 4th time there is no file coming and echo not moved.
How to solve this issue. Please help. I seen a similar question but that answer also not working for me
It seems that you do not have the correct folder permissions for:
C:\xampp\htdocs\project-1/images/
As you have this directory showing up in your error for the rename and the copy functions. Set this directory's permissions to 750, for your basic needs.
Since you're using windows:
Right Click>Properties>Security Tab
Change the permissions for your user the script is running under to "Read & execute" and "Write".

Email Piping - working but emails return errors

I have setup my email forwarding to "Pipe to a program". The piping seems to be working because when an email is sent to my piped email address it returns an undelivered message with errors from my PHP script such as:
This message was created automatically by mail delivery software.
A message that you sent could not be delivered to one or more of its recipients. This is a permanent error. The following address(es) failed:
pipe to |/home/badihbar/public_html/handEmlTst.php
generated by badih#badihbarakat.com
local delivery failed
The following text was generated during the delivery attempt:
------ pipe to |/home/badihbar/public_html/handEmlTst.php
generated by badih#badihbarakat.com ------
/home/badihbar/public_html/handEmlTst.php: line 1: ?php: No such file or directory
/home/badihbar/public_html/handEmlTst.php: line 3: //: is a directory
/home/badihbar/public_html/handEmlTst.php: line 4: //: is a directory
/home/badihbar/public_html/handEmlTst.php: line 5: syntax error near unexpected token ('
/home/badihbar/public_html/handEmlTst.php: line 5: // date_default_timezone_set("Asia/Muscat");'
------ This is a copy of the message, including all the headers. ------
Apparently, for some reason, it is not recognizing the php file to have php scripts. What I'm suspecting is the first line itself. How can I know what path should i put after the "#!" ?
My php script from handEmlTst.php:
#!/usr/lib/php -q
<?php
// include_once "Libraries/connection.class.php";
// include_once "includes/readini.inc.php";
// date_default_timezone_set("Asia/Muscat");
$starttime = date("h:i:s");
// create the connection object...
$s = ini_get("mysql.default_host");
$conn = mysql_connect($s,'badihbar_badih','letmein2013');
$db = "badihbar_supportcenter";
$attachments = array();
if(mysql_error())
{
print "Error Occured: ".mysql_error()."<br>";
$err = true;
}
mysql_select_db($db,$conn);
$commString = "INSERT INTO scriptEmails (Message) VALUES ('From the Script - ".$starttime."')";
// , '".mysql_real_escape_string($email)."'
$result = mysql_query($commString, $conn);
if(mysql_error())
{
// echo "Error Occured Saving Data: ".mysql_error()."<br>";
// print $Conn->commString."<br>";
}
?>
I have checked phpinfo() for the path but honestly didn't know what I'm looking for. So, I supposed that the php interpreter would be in usr/lib/ or something. Should I substitute usr with my domain user or something? I appreciate if anybody can advise in this regard.
many Thanks
I managed to get it working after all. Below are the steps for all to benefit... :)
I used phpinfo() to get the path for the php interpreter. I used the "Configuration File (php.ini) Path" parameter value which was usr/lib/ for my server.
used #!/usr/lib/php -q as the first most line in my handling script.
This part was the issue in my case. UPLOAD THE FILE AS ASCII, NOT BINARY!
Made sure the chmod of the uploaded file was 755.
Set the forwarding of my email address to "Pipe to a program" in my cpanel and put the path of the php script file I've uploaded.
That's did it. As I mentioned, my problem was with the file being uploaded by the FTP application as binary instead of ASCII.
Thanks, all... :)
You can also use #!/usr/local/bin/php at the starting line on your PHP file, which is the cli binary instead of the cgi binary.
This works for me, If you Passed above case as said by #Badih Barakat

How to log errors for move_uploaded_file to a file

I have some code that uploads a file, its the exact same code i had working on another server but its not working on this new server
// Move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"]);
I know i can use:
if(move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"])){
echo "success";
} else{
echo "failure";
}
However i have 2 problems, the script is not ran directly from the page, another application which i dont have access to source code to calls that page and sends the image. So i cant do any in page errors i need to log the errors to a file.
The 2nd problem and the main issue is i am not sure how to find out what the error is. Is there an error code i can pull if the else statement is called. I have set it to 777 for the folders and subfolders just for testing purposes to rule out permission issues, ill fix that after getting the problem resolved before pushing to production.
Also i checked the apache server error.log file and it shows nothing
Here i would do something like this.
$debug_file = _DIR_.'/debug.txt';
$source = $_FILES["file"]["tmp_name"];
$dest = './img/myfolder/1/'. $_FILES["file"]["name"];
if(! #move_uploaded_file($source,$dest) ){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ]\n", FILE_APPEND);
exit();
}
Then when you have the source and dest paths you can make sure they actually exist in the right places.
-note- the # sign will suppress the normal PHP warning for failing to move the file, but as we are logging it our self, this just prevents it from getting in the way.
Also I put an exit in, I'm assuming its a requirement of this script to have the file to work properly, and that way it's enough just to fail, no need to check for success.
Most likely, the file path is wrong
Also you could even output buffer the php error as well like this,
ob_start();
$moved = move_uploaded_file($source,$dest);
$message = ob_get_clean();
if(!$moved){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ] PHP message[ $message ]", FILE_APPEND);
exit();
}
Output buffing works wonders on scripts ran in the background,
http://php.net/manual/en/function.ob-get-clean.php

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.

Cannot open file for reading PHP

I am trying to open a file but for some reason I cannot even though the file is there and even has 777 permission. The code is the following:
$fileatt = "/opt/lampp/htdocs/a.pdf";
echo "File size is ".filesize($fileatt)."<br>";
if (file_exists($fileatt)) {
echo "The file ".$fileatt." exist <br>";
$file = fopen($fileatt, ‘rb’);
if ($file == false) {
echo "Could not open the file !";
}
} else {
echo "The file ".$fileatt." does NOT exist <br>";
}
The result is:
File size is 1252121
The file /opt/lampp/htdocs/a.pdf exist
Could not open the file !
Why can't I open the file ? Where is my mistake ?
Thanks
Where is my mistake ?
You don't have error reporting properly set. there are 2 things to remember.
error reporting level. set by error_reporting ini directive or error_reporting() function. should ALWAYS be at E_ALL or higher.
error messages destination.
on a development server it should be display
on a live server it should be a log file
Thus, for a quick solution, put these 2 lines at the top of your script
error_reporting(E_ALL);
ini_set('display_errors',1);
but later set up these settings as a permanent ones for the whole site (according to the server state)
once you done it, you will have an answer to your question.
Note that you will have not a mere guess from the fellow stackoverflowers, but exact explanation of the matter from the system itself.

Categories