Webhook handling with PHP [closed] - php

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 4 years ago.
Improve this question
I'm trying to build a webhook receiver.
I created this simple PHP-Script and uploaded it to my webhost:
$raw_payload = file_get_contents('php://input', true);
$payload = json_decode($raw_payload, true);
if($payload){
$myfile = fopen("log.txt", "a+") or die("Unable to open file!");
fwrite(date('Y-m-d H:i:s', time()).PHP_EOL);
fclose($myfile);
}
then, in the App who sends the Webhook (actually Wekan) I entered the URL to the file:
http://myurl.com/dir/receiver.php
I sent some webhooks then, but nothing is written into the file.
The webhooks were sent correctly (I tested it with a webhook-tester and received some correct data there but not in my php-file).
The webhook data wich should be send looks like this (JSON):
{
text: '{{wekan-username}} moved "{{card-title}}" from "{{old-list-name}}" to "{{new-list-name}}"\nhttp://{{wekan-host}}/b/{{board-id}}/{{board-name}}/{{card-id}}',
cardId: '{{card-id}}',
listId: '{{new-list-id}}',
oldListId: '{{old-list-id}}',
boardId: '{{board-id}}',
user: '{{wekan-username}}',
card: '{{card-title}}',
description: 'act-moveCard'
}
What am I doing wrong here? (Can it be a problem with my webhost? The webhook-tester uses https, but for my php-file Im using http, does this cause the error?)

Your not passing the file resource handle to fwrite().
Then perhaps make your code more verbose, and keep an eye on the error log:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$raw_payload = file_get_contents('php://input');
$payload = json_decode($raw_payload, true);
if (is_array($payload)) {
$fh = fopen("log.txt", "a+");
if ($fh) {
fwrite($fh, date('Y-m-d H:i:s', time()).PHP_EOL);
fclose($fh);
} else {
trigger_error("Unable to open file!");
}
} else {
trigger_error("Invalid payload!");
}
} else {
trigger_error("Invalid request!");
}

Related

PHP - Trying to make a chatbot for my game server

Alright, so first of all, i'm still kind of a newbie in PHP.
I'm trying to make a chatbot that responds to the keyword "shut up" from people that tell that to the bot in my game server, but I can't seem to find a way how...
Here's the bot's original code...
<?php
$choosechar = "#43CC#1#35#ItsJustABot#%";
$fh = fopen('badtimetim.txt','r');
$word_array = array(fgets($fh));
$word = rand(0,58);
$lines = file("badtimetim.txt");
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
// echo($line);
// Connect to the AO Server
if (!($fp = fsockopen("127.0.0.1", "27017", $errno, $errstr, 15))) {
die("Failed to connect. Doesn't seem like the server is up anyway?");
}
// Set timeout to 1 second
if (!stream_set_timeout($fp, 1)) die("Could not set timeout.");
// Fetch first line of response and echo it
echo fgets($fp);
// Say line and repeat
fwrite($fp, $choosechar);
fwrite($fp, "#4D90#chat#(a)dolannormal#Dolan#dolannormal#".$lines[array_rand($lines)]."#jud#1#1#0#0#0#0#35#0#1#%");
sleep(120);
// Stuff
echo fgets($fp);
}
fclose($fh);
What i'm exactly trying to achieve here is when the bot detects this (asterisks should be wildcards or something):
#4D90#chat#*#*#*#shut up#*#*#*#*#*#*#*#*#*#*#%
I want the bot to send this data to the server in response using fwrite:
#4D90#chat#(a)dolanangry#Dolan#dolanangry#no#jud#1#1#0#0#0#0#35#0#1#%
How do I do this? Any help is appreciated, thanks.
EDIT: Forgot to mention, i'm using a .bat file to run PHP and the PHP code and not a website.
EDIT2: Made question more specific
$input_string_with_shut_up=$_POST['chat_msg']
$output=str_replace('%shut up%','#4D90#chat#(a)dolanangry#Dolan#dolanangry#no#jud#1#1#0#0#0#0#35#0#1#%',$input_string_with_shut_up)
echo $output;
This might do

How to read IP addresses from a .txt file using preg_match in php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a ip.txt file which contains
127.0.0.1
I need to get the text file from a form and to display the ping details in the new window using php. how to read ip from a text file so as to ping it from the read information.
Try this code
$ips = array();
$file = #fopen("ip.txt", "r");
if ($file) {
while (($buffer = fgets($file, 4096)) !== false) {
$ips[] = $buffer;
}
if (!feof($file)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($file);
echo '<pre>'; print_r($ips); echo '</pre>';
}

error in creating a file in PHP using file handling functions? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
someone could please tell why this code does not work? it does not create data.txt. and the file does not save anything.
<?php
$txt = "data.txt";
if(isset($_POST['info1']) && isset($_POST['info2']) && isset($_POST['info3']) && isset($_POST['info4']) && isset($_POST['info5']) && isset($_POST['info6'])) {
// check if both fields are set
//open file in read mode to get number of lines
$handle = fopen($txt, 'r');
//check file opened
if($handle) {
//get number of lines
$count = 1;
while(fgets($handle) !== false) {
$count++;
}
fclose($handle);
//open in append mode.
$handle = fopen($txt, 'a');
//prepare data to be writen
$txt = $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n";
//write data to file
fwrite($handle,$txt);
fclose($handle);
}
}
?>
In fopen function mode param with value r doesn't make file being created.
See fopen documentation.
Also the issue could be write permissions for user that runs that PHP script.
These is only my guesses. Anyway you should configure your PHP (in dev environment) to show you every error/warning in order to debug such issues. You can do that in php.ini file or straight in PHP file with this code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
You are first trying to open the file read only, and if that succeeds you close it and open it again with write access.
This will only work if the file already exists.
If the file doesn't exist, your text will not get written to it.
Move the closing bracket if if ($handle) { in front of the second fopen call.
if($handle) {
//get number of lines
$count = 1;
while(fgets($handle) !== false) {
$count++;
}
fclose($handle);
}
//open in append mode.
$handle = fopen($txt, 'a');
//prepare data to be writen
$txt = $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n";
//write data to file
fwrite($handle,$txt);
fclose($handle);
by the way, you can reduce this to three lines of code.
$lines = file($txt);
$count = sizeof($lines);
file_put_contents($txt, $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n", FILE_APPEND);
to check for multiple variables in isset create only one isset to check all veriables
change this
if(isset($_POST['info1']) && isset($_POST['info2']) && isset($_POST['info3']) && isset($_POST['info4']) && isset($_POST['info5']) && isset($_POST['info6']))
to
if(isset($_POST['info1'],$_POST['info2'],$_POST['info3'],$_POST['info4'],$_POST['info5'],$_POST['info6']))

Generate CSV file using PHP Codeigniter Framework [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?
Take a look at this answer of mine and you will know exactly how you can do it.
Reports in Codeigniter
You need to use Codeigniter Database Utility Class
And need to return query instead of result_array or result
function query_to_csv( $query, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysql_query($query);
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
exit;
}

PHP: Missing records when writing to file

My telecom vendor is sending me a report each time a message goes out. I have written a very simple PHP script that receive values via HTTP GET. Using fwrite I write the query parameter to a CSV file.The filename is report.csv with the current date as a prefix.
Here is the code :
<?php
error_reporting(E_ALL ^ E_NOTICE);
date_default_timezone_set('America/New_York');
//setting a the CSV File
$fileDate = date("m-d-Y") ;
$filename = $fileDate."_Report.csv";
$directory = "./csv_archive/";
//Creating handle
$handle = fopen($filename, "a");
//These are the main data field
$item1 = $_GET['item1'];
$item2 = $_GET['item2'];
$item3 = $_GET['item3'];
$mydate = date("Y-m-d H:i:s") ;
$pass = $_GET['pass'];
//testing the pass
if (isset($_GET['pass']) AND $_GET['pass'] == "password")
{
echo 'Login successful';
// just making sure the function could write to it
if (!$handle = fopen($directory.$filename, 'a')){
echo "Cannot open file ($filename)";
exit;
}
//writing the data I receive through query string
if (fwrite($handle, "$item1,$item2,$item3,$mydate \n") === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
}
else{
echo 'Login Failure please add the right pass to URL';
}
?>
The script does what I want, but the only problem is inconsistency, meaning that a good portion of the records are missing (about half the report). When I log to my account I can get the complete report.
I have no clue of what I need to do to fix this, please advice.
I have a couple of suggestions for this script.
To address Andrew Rhyne's suggestion, change your code that reads from each $GET variable to:
$item1 = (isset($_GET['item1']) && $_GET['item1']) ? $_GET['item1'] : 'empty';
This will tell you if all your fields are being populated.
I suspect you problem is something else. It sounds like you are getting a seperate request for each record that you want to save. Perhaps some of these requests are happening to close together and are messing up each other's ability to open and write to the file. To check if this is happening, you might try using the following code check if you opened the file correctly. (Note that your first use of 'fopen' in your script does nothing, because you are overwriting $handle with your second use of 'fopen', it is also opening the wrong file...)
if (!$handle = fopen($directory.$filename, 'a')){
$handle = fopen($directory.date("Y-m-d H:i:s:u").'_Record_Error.txt', 'a');
exit;
}
This will make sure that you don't ever lose data because of concurrent write attempts. If you find that this is indeed you issue, you can delay subsequent write attempts until the file is not busy.
$tries = 0;
while ($tries < 50 && !$handle = fopen($directory.$filename, 'a')){
sleep(.5);//wait half a second
$tries++;
}
if($handle){
flock($handle);//lock the file to prevent other requests from opening the file until you are done.
} else {
$handle = fopen($directory.date("Y-m-d H:i:s:u").'_Record_Error.txt', 'a');//the 'u' is for milliseconds
exit;
}
This will spend 25 seconds, trying to open the file once every half second and will still output your record to a unique file every time you are still unable to open the file to write to. You can then safely fwrite() and fclose() $handle as you were.

Categories