I'm trying to write a basic error form to a file, but when I submit the file my PHP always crashes. I've tried some basic error fixes such as whether or not the if statement is occurring, if all the variables I'm using are not null, etc...
In my code all the string variables are valid an I am 100% certain they are not causing the error.
I've reduced it down through error testing to be the lines
$destination = fopen($filename,"w");
and
$fclose($destination);
My code:
if(isset($_POST['submit']) && $_POST['name'] != "" && $_POST['email'] != ""){
$filename = "message_" . date('Y-m-d H:i:s') . ".txt";
$issueType = "Type of issue: " . $_POST["issues"] . "\r\n";
$submitter = "Submitted by: " . $_POST["name"];
$email = "Email ID: " . $_POST["email"];
$time = "Submitted at: " . date('Y-m-d H:i:s') . "\r\n";
$message = "Details: " . $_POST["details"];
$destination = fopen($filename,"w");
fwrite($destination,"Issue Alert!");
fwrite($destination,$issueType);
fwrite($destination,$submitter);
fwrite($destination,$email);
fwrite($destination,$time);
fwrite($destination,$message);
$fclose($destination);
}
Any other code I'm implementing is irrelevant as I've cut off those as being points of error.
When I try this with basic, hard-coded strings I don't get any errors. All help is appreciated, Thanks!
Try to change your $filename, as you wrote
$filename = "message_" . date('Y-m-d H:i:s') . ".txt";
because you can't use colon ( ':' from 'H:i:s') in file name.
maybe you can try this:
$filename = "message_" . date('U') . ".txt";
you still have date-time information in your file name
But remember, if you have big traffic on your site, maybe you will get same file name in one second, and the previous existing file will overwrited
Related
I have a project where I have to make a new log file if the current log file is larger than 50mb. I know that we have to test for the size of the file.
I am starting out with this $log variable:
$log =
"Branch: ".$branchDir . PHP_EOL.
"Phase: ". $phaseDir . PHP_EOL.
"Total number of results files deleted: ". count($folderCounter). PHP_EOL.
"File names: " . $filePathToDelete . PHP_EOL.
"Starting CustomerID directory name: " . $CustIDvalue . PHP_EOL;
// $log = 'this is a test' . $branch . PHP_EOL;
$dt = time();
$mysql_datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
$mysql_datetimes = preg_replace('/\s+/', '', $mysql_datetime);
$logFileName = "ResultsFileDeletion" . $mysql_datetimes . ".txt";
if (unlink($filePathToDelete)) {
//this echo string will be moved to a log file
echo "first unlink: {$filePathToDelete} was deleted <br>";
$myFile =
file_put_contents("c:\\sites\\EtonBio/sequencing/logs/{$logFileName}",
$log, FILE_APPEND);
echo 'my file: ' . $myFile . '<br>';
}
I found this code snippet:
$size = filesize($_FILES['foto']['tmp_name']);
I believe my if statement would look something like this:
if($size < 52428800) {
*creates another log file
}
I want to format the $size variable correctly and I am also not sure how to make a new log file.
$size = filesize($_FILES['foto']['tmp_name']); only works if you are uploading the file.
If you want to check a file already in you server ou can simply do
$size = filesize("path/to/file");
Also, there is a ' in your $log declaration that shouldn't be there
I'm running this code once the user submits a form. The idea is to save a new file called "message_timestamp" where timestamp is the current date and time. It need to be saved in the misc folder, which is located in the same directory as this php file.
My code:
if (isset($_POST['submitIssue'])) {
$type = $_POST['typeOfIssue'];
$prefName = $_POST['preferredName'];
$email = $_POST['userEmail'];
$details = $_POST['detailedReport'];
date_default_timezone_set('Atlantic/Bermuda');
$date = new DateTime('now');
$date = $date->format('Y-m-d_H:i:s');
$date = trim($date);
$fileName = "misc/message_" . $date;
$out = "Issue Alert!\nType of issue: " . $type . "\n\nSubmitted by " . $prefName . "\nEmail ID: " . $email . "\nSubmitted at: " . $date . "\n\nDetails: " . $details;
$myFile = fopen($fileName,"w") or die("Cannot open file!");
fwrite($myFile, $out);
fclose($myFile);
}
I've tried removing whitespaces and looking for escape characters. But as long as $date is appended to the filename, I get the error:
fopen(misc/message_2018-02-0210:47:41): failed to open stream: Invalid
argument in C:\MAMP\htdocs\A2\report.php on line 76
I can get it to work if I don't put the timestamp on it. Any suggestions?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Any idea what's wrong with this?
<h1>IP Logger</h1>
<?php
$file = 'ip/index.php';
$date = date('d/m/y');
$time = date('H:i:s');
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$log = ''. $ip . ' <br>';
$infofileloc = 'ip/' . $ip . '/index.php';
$infofile = 'Nothing here yet!';
$details = json_decode(file_get_contents("http://ipinfo.io/' . $ip . '/json"));
$city = $details->city;
$hostname = $details->hostname;
$region = $details->region;
$country = $details->country;
$loc = $details->loc;
$org = $details->org;
$data = "<h1>". $ip . "</h1><br>Date: " . $date . "<br>Time: " . $time . "<br>Hostname: " . $hostname . "<br>City: " . $city . "<br>Country: " . $country . "<br>Region: " . $region . "<br>Location: " . $loc . "<br>ISP Org: " . $org . "<br>"
echo("Writing IP to log...<br>");
file_put_contents($file, $log);
echo("Done.<br>");
echo("Writing information file to log...<br>");
if (!file_exists('ip/' . $ip)) {
mkdir('ip/'. $ip, 0777, true) or die("ERROR: Unable to create info directory in /ip/!<br>");
}
file_put_contents("ip/" . $ip . "/index.php", $data);
echo("Done.<br>");
echo($ip . "<br>");
?>
<br>
Access Logs
I just get this error:
Parse error: syntax error, unexpected T_ECHO in /home/u142114406/public_html/i/index.php on line 30
Any ideas? :S
I've no idea whats wrong here, I think it is something to do with the last file_put_contents but am unsure.
Thanks,
-Connor
You miss a semicolon at the end of line #28:
$data = "<h1>". $ip . "</h1>"...
This kind of error:
Parse error: syntax error, unexpected T_ECHO.. usually notifies a certain line number, but when it happens you should always look at the line PRIOR to the one you are getting an error on.
Please now consider seeing the Help -> Tour otherwise you're going to be considered off topic.
It has an echo where it isn't expecting one; you forgot the semi-colon at the end of the previous statement.
There is no semi-colon ";" end of line 28
Line with starting => $data = "". $ip . ...
Btw use this class : http://www.phpclasses.org/package/5680-PHP-Get-geographic-location-of-a-given-IP-address.html
or
http://community.sitepoint.com/t/simple-ip-logging-script/4042
I am creating a plugin for a WP site and I have to make an initial import of a huge amount of files from another directory. (The plugin is working well, etc etc.) I want to run the import using command line. Everything is OK if executing on local (Windows), but when I execute from Linux bash the defined constants are not evaluated but printed as a string.
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
Is there any setting I have to make to enable evaluation of PHP defined constants? My website is running on Dreamhost server.
When I execute the folowing line:
[myserver]$ /usr/local/php5/bin/php /home/path/to/import.php
I get:
WordPress database error Table 'db_ro.ASCOR_RECORDINGS_TBL' doesn't exist for query INSERT INTO `ASCOR_RECORDINGS_TBL` ...........
The content of the file I execute:
<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . "/wp-load.php";
require_once "class/AscorDbHelper.php";
$origin = realpath("/path/to/files");
$upload_dir = wp_upload_dir();
$subdir = $upload_dir['subdir'];
mkdir(ASCOR_UPLOAD_DIR . "/" . $subdir, 777, true);
require_once $origin . "/classes/PConfFiles.inc.php";
$db = new AscorDbHelper();
$cf = new PConfFiles('/^PC_([0-9\-]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
$catPC = $db->addCategory("Special");
$catOther = $db->addCategory("Other");
if($list){
$pc = $db->addAuthor("Ciprian V.");
foreach($list as $rec){
$fileUrl = $subdir . "/" . $rec[0];
$desc = str_replace("-", " ", $rec[2]);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catPC->id, $pc->id, $desc, null, $rec[1]);
echo "Added: " . $rec[0] . "\n";
}
}
$cf = new PConfFiles('/^([0-9\-]+)\_([^\_]+)_(.*)\.([a-z0-9]{2,4})$/i', $origin);
$list = $cf->getFilesList();
if($list){
foreach($list as $rec){
$authorName = str_replace("-", " ", $rec[2]);
$date = $rec[1];
$desc = str_replace("-", " ", $rec[3]);
$fileUrl = $subdir . "/" . $rec[0];
$authorId = $db->getAuthorIdOrSaveIt($authorName);
copy(realpath($origin . "/" . $rec[0]), ASCOR_UPLOAD_DIR . "/" . $fileUrl );
$db->addRecording($fileUrl, $catOther->id, $authorId, $desc, null, $date);
echo "Added: " . $rec[0] . "\n";
}
}
echo "done";
The constants are defined in the main file of the plugin:
define("ASCOR_RECORDINGS_TBL", $wpdb->prefix . "recordings");
define("ASCOR_RECORDINGS_AUTHORS_TBL", $wpdb->prefix . "recordings_authors");
define("ASCOR_RECORDINGS_CATEGORIES_TBL", $wpdb->prefix . "recordings_categories");
define("ASCOR_RECORDS_PER_PAGE", 50);
define("ASCOR_EXTEND_DIR", dirname(__FILE__));
define("ASCOR_EXTEND_URL", plugins_url("", __FILE__));
define("ASCOR_NOTIFY_UPDATED", "updated");
define("ASCOR_NOTIFY_ERROR", "error");
define("ASCOR_UPLOAD_DIR", ABSPATH . "/wp-content/uploads/recordings");
Is the file loaded? Introduce a parse error into it and see if it fails. And try it on Windows too.
I have written a very simple page counter and a logging script that increments a counter stored in a file and logs information about the client's operating system and which browser they use. It's a simple spare time project I've been working on, and as such it is extremely rudimentary, writing the counter and the logged information in a designated folder for each page on the site, in a new file for each day.
The thing is, I recently used blitz.io to test my site, and when I ran a "Rush" of 250 requests per second, the counters and the logs were completely flushed, except for the very last query.
I'm not perfectly sure what happened, but I suspect something along the lines of PHP not properly finishing up the previous query before taking on the next one.
I use file_get_contents()/file_put_contents() for the both of them, instead of file(). Would changing to file() solve the problem?
Here's the counter:
$filename = '.' . $_SERVER['PHP_SELF'];
$counterpath = '/Websites/inc/logs/counters/total/' . getCurrentFileName() . '-counter.txt';
$globalcounter = '/Websites/inc/logs/counters/total/global-counter.txt';
if (file_exists($counterpath)) {
$hit_count = file_get_contents($counterpath);
$hit_count++;
file_put_contents($counterpath,$hit_count);
}
else {
$hit_count = "1";
file_put_contents($counterpath, $hit_count);
}
And here's the logger:
$logdatefolder = '/Websites/inc/logs/ip/' . date('Y-m-d',$_SERVER['REQUEST_TIME_FLOAT']);
$logfile = $logdatefolder . "/" . getCurrentFileName() . '-iplog.html';
$ua = getbrowser();
if (false == (file_exists($logdatefolder))) {
mkdir($logdatefolder);
}
function checkRef() {
if (!isset($_SERVER['HTTP_REFERER'])) {
//If not isset -> set with dummy value
$_SERVER['HTTP_REFERER'] = 'N/A';
}
return $_SERVER['HTTP_REFERER'];
}
/* Main logger */
$logheader = "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en-US\"><head><title>" . getCurrentFileName() . " log</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body>";
$logentry = date("Y-m-d, H:i:s, O T") . ":" .
"<br />- Requesting: http://giphtbase.org" . $_SERVER['REQUEST_URI'] .
"<br />- Arriving from: " . checkRef() .
"<br />- Browser: " . $ua['browser'] .
"<br />- Full browser name: " . $ua['name'] .
"<br />- Operating system: " . $ua['platform'] .
"<br />- Full user agent: " . $ua['userAgent'] .
"<br />";
$logfooter = "<!-- Bottom --></body></html>";
if (file_exists($logfile)) {
$logPage = file_get_contents($logfile);
$logContents = str_replace("<!-- Bottom --></body></html>","",$logPage);
file_put_contents($logfile, $logContents . $logentry . $logfooter);
}
elseif (false == (file_exists($logfile))) {
file_put_contents($logfile, $logheader . $logentry . $logfooter);
}
You should use the FILE_APPEND flag in your file_put_contents() otherwise you will only ever see the last entry:
file_put_contents($logfile, $logContents . $logentry . $logfooter, FILE_APPEND);
As for the counter, it looks like the file is trying to be written to too many times by different threads, causing it to be inaccessible. You should either use a database, or create a file_lock, or create temporary files and run a cronjob to do the math.