I want to dump request variables to a file for debugging. How's this possible?
<?php
$req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fclose($fp);
Untested but should do the job, just change request.log to the file you want to write to.
I think nowadays this method is easier and faster:
$req_dump = print_r($_REQUEST, true);
$fp = file_put_contents('request.log', $req_dump, FILE_APPEND);
Use serialize() function for dumping. Dump $_SERVER, $_COOKIE, $_POST and $_GET separately (may go to the same file). If you're planning on debugging with the data it helps to know if the data was part of a POST request or a GET request.
Dumping everything is good for debugging in development, but not so in production. If your application does not have many users, it can work in production too. If you anticipate many users, consider dumping just the $_POST data, or limit server variables to those starting with HTTP_.
/* may be late but he can help others.
it's not my code, I get it from :
https://gist.github.com/magnetikonline/650e30e485c0f91f2f40
*/
class DumpHTTPRequestToFile {
public function execute($targetFile) {
$data = sprintf(
"%s %s %s\n\nHTTP headers:\n",
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$_SERVER['SERVER_PROTOCOL']
);
foreach ($this->getHeaderList() as $name => $value) {
$data .= $name . ': ' . $value . "\n";
}
$data .= "\nRequest body:\n";
file_put_contents(
$targetFile,
$data . file_get_contents('php://input') . "\n"
);
echo("Done!\n\n");
}
private function getHeaderList() {
$headerList = [];
foreach ($_SERVER as $name => $value) {
if (preg_match('/^HTTP_/',$name)) {
// convert HTTP_HEADER_NAME to Header-Name
$name = strtr(substr($name,5),'_',' ');
$name = ucwords(strtolower($name));
$name = strtr($name,' ','-');
// add to list
$headerList[$name] = $value;
}
}
return $headerList;
}
}
(new DumpHTTPRequestToFile)->execute('./dumprequest.txt');
// add this line at the end to create a file for each request with timestamp
$date = new DateTime();
rename("dumprequest.txt", "dumprequest" . $date->format('Y-m-d H:i:sP') . ".txt");
<?php //log
$razdelitel = '--------------------------------------------'.PHP_EOL . date("Y-m-d H:i:s") .PHP_EOL.PHP_EOL;
$data_REQUEST = '$_REQUEST: ' . print_r($_REQUEST, true).PHP_EOL;
$data_POST = '$_POST: ' . print_r($_POST, true).PHP_EOL;
$data_GET = '$_GET: ' . print_r($_GET, true).PHP_EOL;
$data_all = $razdelitel . $data_REQUEST . $data_POST . $data_GET;
$name_txt = __DIR__ . '/log_' . date('m.Y') . '.txt'; //log_12.2021.txt
$chmod = '0244';
chmod($name_txt, $chmod);
file_put_contents($name_txt, $data_all, FILE_APPEND);
//var_dump($name_txt, $chmod); ?>
Related
I have got this code to open each file in a folder, decrease a value by 5 and then overwrite the existing content.
<?php
foreach (glob("users/*.php") as $filename) {
$array = file($filename);
$wallet = $array[0];
$time = $array[1];
$status = $array[2];
$steamid = $array[3];
$process = fopen($filename, "w") or die("Unable to open file!");
$time = $time - 5;
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
fwrite($process, $newdata);
fclose($process);
}
?>
Before I execute the script, the files that are opened look like this:
680
310
0
74892748232
After the script was executed, the file looks like this:
680
305
0
74892748232
If the script is executed again, it adds more lines and just breaks the files even more.
The string for the file is created here:
$newdata = $wallet . "\n" . $time . "\n" . $status . "\n" . $steamid;
Why does it add an empty line after $wallet and $status, but not after $time? How can I avoid this and instead write down:
$wallet
$time
$status
$steamid
Thanks a lot in advance.:)
Try with this solution
You can also use file_put_contents():
file_put_contents($filename, implode("\n", $array) . "\n", FILE_APPEND);
from this SO question
https://stackoverflow.com/a/3066811/1301180
I've got a form that I've been trying to rework. Essentially it was just interacting with a REST API provided by a third party to integrate with their software. On a separate form, I am able to create a csv file with data for import in to a server. I have been trying to re-work them so that on submit they both function but I am only able to get on or the other.
Here is my createCSV function
function createCSV(){
global $strnmbr, $Content, $hostname;
$ext = " - 'SOMETHING'.csv";
$FileName = "s" . $hostname . $ext;
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
}
Then follows
if(isset($_POST['submit'])){
if($_SESSION['Hostname']==""){$hostname = sprintf("%'.05d", $_SESSION['Store Number']);}
else{$hostname = $_SESSION['Hostname'];}
$hostname1 = "'info here'" . ".s" . $hostname . ".'info here'";
$resolve = "FALSE";
$IP = "0.0.0.0";
$mac= strtolower($_POST['mpMAC']);
$proxy = "";
$outproxy = "";
$opstate = "OPSTATE";
$audiodevserial1 = $_POST['assetSN'];
$type = "TYPE";
$brand = "BRAND";
$series = "SERIES";
$model = "MODEL";
$modvers = "";
$login = "";
$password = "";
$continent = "North America";
$country = "United States";
$stateabr = $_SESSION['State'];
$city = $_SESSION['City'];
$StAddress = $_SESSION['Street'];
$zip = $_SESSION['Zip'];
$lat = "0";
$long = "0";
$RCV = "TRUE";
$SEND = "FALSE";
$category = "";
$SecHostname = "";
$SecIP = "";
$SecMac = "";
$MODE = "1";
$ITEM = $_SESSION['Store Number'];
$strnmbr = $_SESSION['Store Number'];
$timezone = $_POST['TIME_ZONE'];
$ACTIVE= "FALSE";
$RESTART= "Yes";
$Content .= "$hostname1, $resolve, $IP, $MAC, $proxy, $outproxy, $opstate, $SN, $type, $brand, $series, $model, $modvers, $login, $password, $continent, $country, $stateabr, $city, $StAddress, $zip, $lat, $long, $SEND, $RCV, $category, $SecHostname, $SecIP, $SecMac, $MODE, $ITEM, $strnmbr, $timezone, ACTIVE, $RestartPlaylist\n";
createCSV();
}
And finally within a on the page further down I return the info made from the request for the web call to the API.
if(isset($_POST['submit'])){
include_once('../tools/createConErr.php');
$_SESSION['requestID'];
echo "<tr><td> "MORE INFO HERE' - Location " . $_SESSION['Store Number'] . " - Ticket # <a href=\"'link here'" . $_SESSION['requestID'] . "\"target='_blank'>" . $_SESSION['requestID'] . "</a></td></tr>";
}
Both sets of code work individually, but not together. I've tried moving the bottom up and the top to the bottom and just trying to make a mash of the two but I can't seem to get it to work. I've tried putting them both within the same if(isset($_POST['submit'])){code} as I'm sure that's what needs to happen but it still didn't work.
I've changed some of the variable names and text for this post but I think you can still get the idea.
Any help is much appreciated.
THANKS!
I think the culprit is here:
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $FileName . '"');
If you define content as attachment, then the API return part of code goes to that attachment. If you run the API return part of code before sending the header, the header command does not work, since you had an echo before it and it is no longer a header. Maybe rethink the approach to include an auto-refresh with a second parameter, to run the second part of code?
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 think I'm going crazy.
code:
<?
$meh = $_GET["q"];
echo ( ":" . $meh . ":" . strlen($meh) . PHP_EOL );
$fp = fopen("/tmp/wtf.log","w+");
fwrite($fp, ":" . $meh . ":" . strlen($meh) . PHP_EOL );
fclose($fp);
?>
request:
/search.php?q=meh123
This is in the response ( expected ):
:meh123:6
This is in the file:
me#host:/tmp# cat wtf.log
::0
Try this:
<?
$meh = $_GET["q"];
$writeline = ":{$meh}:{strlen($meh)}";
echo ( $writeline );
$fp = fopen("/tmp/wtf.log","w+");
fwrite($fp, $writeline );
fclose($fp);
?>
Also, as Jay said in the comment above:
try putting if(isset($_GET['q'])) { // code } around your code (something you should be doing anyway)
I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'