I am running a PHP code on docker container hosted in Bluemix. The PHP code calls a python script which is a MQTT based subscribe code. My idea was everytime the subscribed code gets MQTT message it will write the values to a text file. The PHP code will keep on checking every 10 seconds for new values in the file.
The VCAP_ENV variables are getting written correctly. However, the site does not load.
The python script executes successfully when i try it locally. So no errors there too.
My code is as follows:
PHP CODE:
<?php
if( getenv("VCAP_SERVICES") ) {
// get IoT service configuration from Bluemix
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services, true);
$mysql_config = $services_json["iotf-service"][0]["credentials"];
$org_id = $mysql_config["org"];
$port = $mysql_config["mqtt_u_port"];
$username = $mysql_config["apiKey"];
$password = $mysql_config["apiToken"];
}
// set configuration values
$config = array(
'org_id' => $org_id,
'port' => $port,
'app_id' => 'mymqttfinalservice',
'iotf_api_key' => $username,
'iotf_api_secret' => $password,
'device_id' => '007',
'qos' => 1
);
$file = fopen("VCAP_CONFIG.ini","w");
#fwrite($file,"[config]" . PHP_EOL );
#fwrite($file,"org =" . $org_id . PHP_EOL );
#fwrite($file,"apikey =" . $username . PHP_EOL );
#fwrite($file,"authkey =" . $password . PHP_EOL );
fwrite($file,"[config]" . "\n" );
fwrite($file,"org =" . $org_id . "\n" );
fwrite($file,"apikey =" . $username . "\n" );
fwrite($file,"authkey =" . $password . "\n" );
fclose($file);
$file = file_get_contents('VCAP_CONFIG.ini', true);
echo $file;
$command = 'chmod 777 /app/PythonSubscribeCode.py';
$output = '';
exec ( $command);
$command = 'python3 /app/PythonSubscribeCode.py 2>&1';
$output = exec ($command);
print_r($output);
$x = 1;
while($x == 1)
{
$config = parse_ini_file('Data.ini');
echo json_encode($config);
sleep(5);
}
?>
Python Script:
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import os, json
import time
import configparser
# This is the Subscriber
settings = configparser.ConfigParser()
settings.read('VCAP_CONFIG.ini')
organization = settings['config']['org']
username = settings['config']['apikey']
password = settings['config']['authkey']
#Set the variables for connecting to the iot service
broker = ""
devicename = "007"
topic = "iot-2/type/DesktopApplication/id/007/evt/status/fmt/json"
#topic = 'iot-2/evt/status/fmt/json'
deviceType = "DesktopApplication"
clientID = "a:" + organization + ":appId"
print (clientID)
broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)
if username is not "":
mqttc.username_pw_set(username, password=password)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_message(mosq, obj, msg):
global message
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
def on_message(client, userdata, msg):
writeData = msg.payload.decode('utf-8')
parsed_json = json.loads(writeData)
UDD = parsed_json['UDD']
DDD = parsed_json['DDD']
PH = parsed_json['PH']
Ignition = parsed_json['Ignition']
# add the settings to the structure of the file, and lets write it out...
config = configparser.ConfigParser()
config['Data'] = {'UDD': UDD,
'DDD': DDD,
'PH': PH,
'Ignition':Ignition}
with open('Data.ini', 'w') as configfile:
config.write(configfile)
mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)
#print (test)
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message
mqttc.loop_forever()
Can someone please guide on this?
Do you get any useful error messages from cf ic logs containerid to see what might be failing? As an alternate, you could also try execing into the container (either cf ic exec -ti containerid bash or docker exec...) and run the python script directly to see if that's giving you other errors when running there.
Related
I'm trying to write a basic JSON interpreter in PowerShell for a scheduled external port scanner which outputs open ports via JSON, but I'm having a lot of trouble getting it to display the data as a comma separated string. The reason for the comma separated string is so that it can be passed to my documentation tool to make notes of client networks.
My PHP Code (working fine, just for reference):
<?php
$host = $_SERVER['REMOTE_ADDR'];
$ports = array(
20,
443,
49371
);
echo "[";
foreach ($ports as $port)
{
$connection = #fsockopen($host, $port, $errno, $errstr, 2);
if (is_resource($connection))
{
echo '{' . '"Port":' . $port . ',' . '"status" : "open"' . "},";
fclose($connection);
}
else
{
echo '{' . '"Port":' . $port . ', "status" : "closed"},';
}
} ?> { "result": "done" } ]
Sample HTML Output when invoking that PHP script:
[{"Port":20, "status" : "open"},{"Port":443, "status" : "open"},{"Port":49731, "status" : "closed"}, { "result": "done" } ]
String (as a variable) that I'm trying to achieve in Powershell:
Open Ports = 20, 443
My Powershell code so far:
$Results = invoke-restmethod -uri "https://mywebsite.com/portscan.php"
$OpenPorts = $Results | Where-Object { $_.status -eq "open"} | ConvertFrom-Json
$Message = "Open Ports: $OpenPorts"
Write-host $Message
The error I can't figure out how to resolve:
ConvertFrom-Json : Invalid JSON primitive: .
At line:2 char:64
+ ... = $Results | Where-Object { $_.status -eq "open"} | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
Any help would be sincerely appreciated, I'm not familiar with PowerShell and it's doing my head in!
# Invoke-RestMethod automatically parses the JSON result into
# a [pscustomobject] graph.
# In a manner of speaking, *ConvertFrom-Json is built in*.
$Results = Invoke-RestMethod -Uri "https://mywebsite.com/portscan.php"
# Get the objects representing open ports.
# Note: `Where-Object Status -eq open` is the equivalent of:
# `Where-Object { $_.Status -eq 'open' }`
$OpenPorts = $Results | Where-Object Status -eq open
# Synthesize the output string.
$Message = "Open ports = " + ($OpenPorts.Port -join ', ')
# Output (echo) it.
# Output that isn't redirected or captured is *implicitly* echoed in PowerShell.
$Message
I try to sign test bitcoin-cash transaction, and then broadcast.
For bitwasp version 0.0.35.0, the code is:
$utxoOwnerPrivateKey = 'MyPrIvAtEKey';//public key is "16Dbmp13CqdLVwjXrd6amF48t7L8gYSGBj", note - the real private key is another
$utxo = '5e44cdab9cb4a4f1871f2137ab568bf9ef2760e52816971fbaf0198f19e28378';
$utxoAmount = 598558;
$reciverPublicKey = '1EjCxux1FcohsBNGzY9KdF59Dz7MYHQyPN';
$fee = 1000;
$addressCreator = new \Btccom\BitcoinCash\Address\AddressCreator();
$networkObject = \Btccom\BitcoinCash\Network\NetworkFactory::bitcoinCash();
$keyPairInput = \BitWasp\Bitcoin\Key\PrivateKeyFactory::fromWif($utxoOwnerPrivateKey, null, $networkObject);
$outpoint = new \BitWasp\Bitcoin\Transaction\OutPoint(\BitWasp\Buffertools\Buffer::hex($utxo, 32), 0);
$transaction = \BitWasp\Bitcoin\Transaction\TransactionFactory::build()
->spendOutPoint($outpoint)
->payToAddress($utxoAmount - $fee, $addressCreator->fromString($reciverPublicKey, $networkObject) )
->get();
echo "Unsigned transaction: " . $transaction->getHex() . '<BR><BR>';
$signScript = \BitWasp\Bitcoin\Script\ScriptFactory::scriptPubKey()->payToPubKeyHash($keyPairInput->getPublicKey()->getPubKeyHash());
$txOut = new \BitWasp\Bitcoin\Transaction\TransactionOutput($utxoAmount - $fee, $signScript);
$signer = new \BitWasp\Bitcoin\Transaction\Factory\Signer($transaction);
$signatureChecker = \Btccom\BitcoinCash\Transaction\Factory\Checker\CheckerCreator::fromEcAdapter( \BitWasp\Bitcoin\Bitcoin::getEcAdapter() ); // for version 0.0.35
$signer->setCheckerCreator( $signatureChecker ); // for version 0.0.35
$input = $signer->input(0, $txOut);
$signatureType = \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::ALL | \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::BITCOINCASH;
$input->sign($keyPairInput, $signatureType);
$signed = $signer->get();
echo "Witness serialized transaction: " . $signed->getHex() . '<BR><BR>';
echo "Base serialized transaction: " . $signed->getBaseSerialization()->getHex() . '<BR><BR>';
echo "Script validation result: " . ($input->verify() ? "yes\n" : "no\n"). '<BR><BR>';
die();
In this case I get the result:
Script validation result: no
Trying to broadcast the BCH transaction gives an error:
An error occured:
16: mandatory-script-verify-flag-failed (Signature must be zero for failed CHECK(MULTI)SIG operation). Code:-26
I think, it means, that signature is wrong. If we remove the flag $signatureType (keep this default), then Script validation result will be yes, but broadcasting will give an error:
16: mandatory-script-verify-flag-failed (Signature must use SIGHASH_FORKID). Code:-26
I think, it means - transaction signed as in bitcoin network, must to be signed by bitcoin-cash rules. Maybe I'm wrong. But bitcoin transaction signing is fine. Bitwasp has no manuals, how to sign a bitcoin-cash transactions, I have the same code for bitwasp v.0.0.34.2 (without addon "btccom/bitwasp-bitcoin-bch-addon", using $signer->redeemBitcoinCash(true); function) but it gives the same result.
It is interesting that in code of bitcoin-cash signer it takes the inner variable amount and include it in hash:
$hasher = new V1Hasher($this->transaction, $this->amount);
But for bitcoin bitwasp doesn't take the amount, presumably it takes an amount from the transaction.
Help me please to sign the transaction, bitwasp has only bitcoin examples, not bitcoin-cash. It is very difficult to find any informaion about php altcoins signing without third-party software. Regards.
This code to sign a bitcoin-cash transaction with PHP bitwasp v.0.0.35 library is works!
$unspendedTx = '49343e0a4ef29b819f87df1371c6f8eafa1f235074a27fb6aa5f4ab4c48e5c16';
$utxOutputIndex = 0;
$utxoPrivateKey = 'MyPrIvAtEKey';
$utxoAmount = 300000;
$reciverPublicKey = '1E8XaWNsCWyVaZaWTLh8uBdAZjLQqwWmzM';
$fee = 1000;
$networkObject = \Btccom\BitcoinCash\Network\NetworkFactory::bitcoinCash();
$outpoint = new \BitWasp\Bitcoin\Transaction\OutPoint(\BitWasp\Buffertools\Buffer::hex($unspendedTx, 32), $utxOutputIndex /* index of utxo in transaction, generated it */);
$destination = \BitWasp\Bitcoin\Script\ScriptFactory::scriptPubKey()->payToPubKeyHash( (new \Btccom\BitcoinCash\Address\AddressCreator())->fromString($reciverPublicKey)->getHash() );
$transaction = \BitWasp\Bitcoin\Transaction\TransactionFactory::build()
->spendOutPoint($outpoint)
->output($utxoAmount - $fee, $destination)
->get();
echo "Unsigned transaction: " . $transaction->getHex() . '<BR><BR>';
$keyPairInput = \BitWasp\Bitcoin\Key\PrivateKeyFactory::fromWif($utxoPrivateKey, null, $networkObject);
$txOut = new \BitWasp\Bitcoin\Transaction\TransactionOutput($utxoAmount, \BitWasp\Bitcoin\Script\ScriptFactory::scriptPubKey()->payToPubKeyHash( $keyPairInput->getPubKeyHash() ) );
$signer = new \BitWasp\Bitcoin\Transaction\Factory\Signer($transaction);
$signatureChecker = \Btccom\BitcoinCash\Transaction\Factory\Checker\CheckerCreator::fromEcAdapter( \BitWasp\Bitcoin\Bitcoin::getEcAdapter() ); // for version 0.0.35
$signer->setCheckerCreator( $signatureChecker ); // for version 0.0.35
$input = $signer->input(0, $txOut);
$signatureType = \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::ALL | \Btccom\BitcoinCash\Transaction\SignatureHash\SigHash::BITCOINCASH;
$input->sign($keyPairInput, $signatureType);
$signed = $signer->get();
echo "Transaction: " . $signed->getHex() . '<BR><BR>';
die();
I had broadcasted this PHP-generated test transaction, see link to tx. Problaly the problem was in
->payToAddress($utxoAmount - $fee, $addressCreator->fromString($reciverPublicKey, $networkObject) )
Maybe payToAddress has a bug, because "hand" script creation gives another transaction. Second:
$txOut = new \BitWasp\Bitcoin\Transaction\TransactionOutput($utxoAmount - $fee, $signScript);
We must to create tx input(previous output) without the fee.
Used libraries ( composer.json ):
{
"require" : {
"php" : ">=7.0",
"bitwasp/bitcoin": "0.0.35.0",
"btccom/bitwasp-bitcoin-bch-addon" : "0.0.2"
}
}
Hope, this will help for all altcoin api creators on PHP.
I am trying to pass data from my PHP script to my Python script in order to write the data from Python to an XML file.
PHP Script:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit']))
{
#--Fetching data from the Form
$fserverId = $_POST['field1'];
$finsname = $_POST['field2'];
$fhost = $_POST['field3'];
$fport = $_POST['field4'];
$fproto = $_POST['field5'];
$fuserName = $_POST['field6'];
$fpassword = $_POST['field7'];
$fkey = $_POST['field8'];
$fcompanyName = $_POST['field9'];
$fofficeAddress = $_POST['field10'];
$fstate = $_POST['field11'];
$fcountry = $_POST['field12'];
$fladmin = $_POST['field13'];
$fphone = $_POST['field14'];
$fmobile = $_POST['field15'];
$femail = $_POST['field16'];
$fdesignation = $_POST['field17'];
$frManager = $_POST['field18'];
$data = " --serverId ".$fserverId." --name ".$finsname." --host ".$fhost." --port ".$fport." --proto ".$fproto." --username ".$fuserName." --password ".$fpassword." --key ".$fkey." --companyName ".$fcompanyName." --officeAddress ".$fofficeAddress." --state ".$fstate." --country ".$fcountry." --ladmin ".$fladmin." --phone ".$fphone." --mobile ".$fmobile." --email ".$femail." --designation ".$fdesignation." --rManager ".$frManager;
#--Parsing the data from PHPscript to CGI
echo "Firewall Creation:: ".$data;
$output = exec('python3 /var/www/cgi-bin/dscr.cgi' .$data);
echo "<pre>hello -------</pre>";
echo "<pre>$output</pre>";
}
?>
Python Script:
import cgi, cgitb
import xml.etree.ElementTree as et
import os
from xml.dom import minidom
import sys
import argparse
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings()
#--ADDING THE XML FILE HERE
base_path = os.path.dirname(os.path.realpath(__file__))
xml_file = os.path.join(base_path, "company.xml")
form = cgi.FieldStorage()
print (xml_file)
#--PARSING THE ARGUMENTS
#--To be used to get arguments from Command Line or Php Script
parser = argparse.ArgumentParser(description ='parser script')
parser.add_argument('--serverId', required=True, help='Server ID to find device info')
parser.add_argument('--name', required=True, help='Name Of the Policy')
parser.add_argument('--host', default='any', help='Host of the IP Address')
parser.add_argument('--port', default='any', help='Port used')
parser.add_argument('--proto', default='any', help='Protocol used')
parser.add_argument('--username', default='any', help='Username')
parser.add_argument('--password', default='any', help='Password')
parser.add_argument('--key', default='any', help='')
parser.add_argument('--companyName', default='any', help='Name of the Company')
parser.add_argument('--officeAddress', default='any', help='Address of the Company')
parser.add_argument('--state', default='any', help='State')
parser.add_argument('--country', default='any', help='Country')
parser.add_argument('--ladmin', default='any', help='Local Admin')
parser.add_argument('--phone', default='any', help='Phone Number')
parser.add_argument('--mobile', default='any', help='Mobile Number')
parser.add_argument('--email', default='any', help='Email Address')
parser.add_argument('--designation', default='any', help='Designation of the concerned')
parser.add_argument('--rManager', default='any', help='Reporting Manager of the concerned Person')
args = parser.parse_args()
#--Associating variables to parsed arguments
name = args.name
host = args.host
port = args.port
proto = args.proto
user = args.username
password = args.password
key = args.key
company = args.companyName
officeAddr = args.officeAddress
state = args.state
country = args.country
ladmin = args.ladmin
phone = args.phone
mobile = args.mobile
email = args.email
designation = args.designation
reportingMgr = args.rManager
#--Retrieving the element tree from XML file
tree = et.parse(xml_file)
root = tree.getroot()
#--Creating Elements and input value
new_name = et.Element("name")
new_name.text = name
new_host = et.Element("host")
new_host.text = host
new_port = et.Element("port")
new_port.text = port
new_proto = et.Element("proto")
new_proto.text = proto
new_user = et.Element("user")
new_user.text = user
new_password = et.Element("password")
new_password.text = password
new_key = et.Element("key")
new_key.text = key
new_companyName = et.Element("companyName")
new_companyName.text = company
new_address = et.Element("address")
new_officeAddr = et.Element("officeAddr")
new_officeAddr.text = officeAddr
new_state = et.Element("state")
new_state.text = state
new_country = et.Element("country")
new_country.text = country
new_contact = et.Element("contact")
new_ladmin = et.Element("ladmin")
new_ladmin.text = ladmin
new_phone = et.Element("phone")
new_phone.text = phone
new_mobile = et.Element("mobile")
new_mobile.text = mobile
new_email = et.Element("email")
new_email.text = email
new_designation = et.Element("designation")
new_designation.text = designation
new_reportingMgr = et.Element("reportingManager")
new_reportingMgr.text = reportingMgr
new_address.append(new_officeAddr)
new_address.append(new_state)
new_address.append(new_country)
new_contact.append(new_ladmin)
new_contact.append(new_phone)
new_contact.append(new_mobile)
new_contact.append(new_email)
new_contact.append(new_designation)
new_contact.append(new_reportingMgr)
new_server = et.Element("server")
new_server.append(new_name)
new_server.append(new_host)
new_server.append(new_port)
new_server.append(new_proto)
new_server.append(new_user)
new_server.append(new_password)
new_server.append(new_key)
new_server.append(new_companyName)
new_server.append(new_address)
new_server.append(new_contact)
root.append(new_server)
str = et.tostring(root)
reparsed = minidom.parseString(str)
tree.write(xml_file)
with open(xml_file, 'w') as output:
output.write(reparsed.toprettyxml(indent="\t"))
On trying to execute, the data does not get written on the XML file but when I pass the arguments through Command Line in the python script, it does get written. So there must be a problem in the call/bridge between the two scripts due to which the data I'm trying to send from PHP to Python is not getting parsed.
I am trying to create 2 separate pdf files with different content. I have the following code which creates the 2 files.
$invoice = Invoices::model()->findByPk($_GET['id']);
$invoicedetail = InvoicesDetail::model()->findAll(array("condition"=>"invoiceno=".$invoice->INVOICENO . " && biditems_id is null"));
$client = $invoice->pROJ->oRDERNO->addressesinvoices;
$invoices = Invoices::model()->findAll(array("condition"=>"PROJID=".$invoice->PROJID . " && INVOICENO != ".$invoice->INVOICENO));
/*$this->renderPartial("partialInvoice",
array(
"invoice"=>$invoice,
"client"=>$client,
//"lookupprocesstotalArr"=>$lookupprocesstotalArr,
"adjustments"=>$invoices,
"invoicedetail"=>$invoicedetail[0]
),true);
*/
$html = $this->renderPartial("partialInvoice",
array(
"invoice"=>$invoice,
"client"=>$client,
//"lookupprocesstotalArr"=>$lookupprocesstotalArr,
"adjustments"=>$invoices,
"invoicedetail"=>$invoicedetail[0]),true);
$filename_invoice = 'invoice_'.$invoice->INVOICENO.'.pdf';
Yii::import('application.extensions.pdfable.WkHtmlToPdf');
$pdf = new WkHtmlToPdf(array(
'no-outline', // Make Chrome not complain
'margin-top' => 10,
'margin-right' => 10,
'margin-bottom' => 10,
'margin-left' => 10,
));
$pdf->setOptions(array(
'orientation' => 'portrait'
));
// Add a HTML file, a HTML string or a page from a URL
$pdf->addPage($html);
// Save the PDF
$pdf->saveAs("/tmp/$filename_invoice");
// ... or send to client as file download
/*if(!$pdf->send($filename)){
throw new Exception('Could not create PDF: '.$pdf->getError());
}*/
$globalController = new GlobalController;
//$project = Projects::model()->findAll(array("condition"=>"PROJID=".$_GET['PROJID']));
//$projid = $_GET['PROJID'];
$pdfDetail = new WkHtmlToPdf();
$orientation = "Landscape";
$pdfDetail->setOptions(array('orientation'=>$orientation,
'no-outline', // Make Chrome not complain
'margin-right' => 10,
'margin-bottom' => 5,
'margin-left' => 10,
));
//$this->layout = 'pdf';
//get list of process stages for this project
$lastrun = $globalController->lastRun($invoice->PROJID);
$processstages = ExtHtml::listData($lastrun, 'ID',array('cumulative','ITEM'));
$lookupprocesstotalArr = $globalController->lookupprocesstotal($invoice->PROJID,$processstages);
// get all lines
$connection = Yii::app()->db;
$sql = "SELECT jobs.JOBNO, jobs.NAME, FSP, LSP, SHOTS, KM
FROM hdb.jobs
join detailsseismic on jobs.JOBNO = detailsseismic.JOBNO
where jobs.PROJID = :pid";
$command=$connection->createCommand($sql);
$command->bindValue(":pid",$invoice->PROJID,PDO::PARAM_INT);
$command->execute();
$lines = $command->queryAll();
$dates = array();
foreach ($lines as $arr) {
$sql = "SELECT jobsprocesscomplete.datedone, ITEM_fk
FROM hdb.jobsprocesscomplete
left join lookupprocess on jobsprocesscomplete.lookupprocess_id = lookupprocess.ID
left join biditems on lookupprocess.biditems_id = biditems.ITEMID
where jobno = :jobno";
$command=$connection->createCommand($sql);
$command->bindValue(":jobno",$arr['JOBNO'],PDO::PARAM_INT);
$command->execute();
$dates[$arr['JOBNO']] = $command->queryAll();
}
/*echo $this->renderPartial('pdf_'.$_GET['type'],array(
'lookupprocesstotalArr'=>$lookupprocesstotalArr,
"currency"=>$project[0]->currency0->currency,
"projectpercent"=>$project[0]->PERCENT,
"name"=>$project[0]->PROJECT . " - " . $project[0]->oRDERNO->cONTACTsugar->first_name . " " . $project[0]->oRDERNO->cONTACTsugar->last_name,
"lines"=>$lines,
"dates"=>$dates,
"project"=>$project[0]));
*/
$detail = $this->renderPartial('/lookupprocess/pdf_detail',array(
'lookupprocesstotalArr'=>$lookupprocesstotalArr,
"currency"=>$invoice->pROJ->currency0->currency,
"projectpercent"=>$invoice->pROJ->PERCENT,
"name"=>$invoice->pROJ->PROJECT . " - " . $invoice->pROJ->oRDERNO->cONTACTsugar->first_name . " " . $invoice->pROJ->oRDERNO->cONTACTsugar->last_name,
"lines"=>$lines,
"dates"=>$dates,
"project"=>$invoice->pROJ
),true);
$filename_detail = $invoice->PROJID . "_" . date("ymd-his") . ".pdf";
// Add a HTML file, a HTML string or a page from a URL
$pdfDetail->addPage($detail);
// Save the PDF
$pdfDetail->saveAs("/tmp/$filename_detail");
shell_exec("gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=/tmp/$filename_invoice /tmp/$filename_invoice /tmp/$filename_detail");
echo "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=/tmp/$filename_invoice /tmp/$filename_invoice /tmp/$filename_detail";
exit();
/*
// ... or send to client as file download
if(!$pdf->send($filename_invoice)){
throw new Exception('Could not create PDF: '.$pdf->getError());
}
The problem i have is the 1st pdf that gets created is overwritten by the content of the 2nd pdf which makes no sense.
I do not know the class you are using but this code seems suspicios:
-sOutputFile=/tmp/$filename_invoice /tmp/$filename_invoice /tmp/$filename_detail
For me it seems that you convert 2 files into 1 output files, so logically you overwrite it!?
I can now send an SMS via kannel. However this is done via headers eg:
header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
I want to send an sms via a php function and I got the code below online but it doesn't work. (Kannel smsbox log shows no request):
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&coding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
$results = file('http://'
. CONFIG_KANNEL_HOST . ':'
. CONFIG_KANNEL_PORT . $url);
}
Is there something wrong? I tried replacing the CONFIG_KANNEL_USER_NAME and the rest with the actual values but it still doesn't work. Open to suggestions.
I used cURL and it works 100% okay. file_get_contents does not work for me because I want to pass variables to the kannel url and file_get_contents does not process variables coz it insists on using single quotes(php treats it as a string value) instead of double quotes(php will parse the string checking for variables etc).
Here is what i am currently doing assuming you already have your variables initialized somewhere:
$textmsg="Hello Stackoverflow Users!";
$cellphone_number = "+254xxxxxxx"
$encmsg=urlencode($textmsg);
$ch= curl_init();
curl_setopt($ch, "http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=$cellphone_number&text=$encmsg");
curl_exec($ch);
curl_close($ch);
This will work for the simple task of telling kannel to send an sms to a number. Took me a while to realize curl does not recognize spaces and special characters :-).
My friend and I from Ndola, Zambia are using ubuntu 11.04 to run kannel_1.4.3. It works perfectly way in sending and receiving sms. The code below had to be edited for it to send more that 70 characters. My friend and I struggled to figure out that there was a small error in the line '&charset=UCS-2&coding=2'. The correct line should be '&charset=UCS-2&encoding=2'. So the code should appear as below:
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&encoding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
Using curl:
curl_init("http://$gw_host:$gw_port/cgi-bin/sendsms?username=$gw_user&password=$gw_pass&to=$to&from=$shortcode&smsc=$smsc&dlr-mask=$dlrmask&binfo=$shortcode&text=$message");
Replace the various variables/parameters with your values such as:
$gw_host=127.0.0.1
$gw_port=13xx3
etc.
If you're attempting to trigger a URL loading in the background (rather than by re-directing the user to the URL), you need to use something like cURL or perhaps even file_get_contents.
For example, if your set up has fopen URL wrappers enabled, you could simply use:
$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
Irrespective, it's hard to know why the function you found won't work without some additional debug information. (If CONFIG_KANNEL_HOST is defined as "localhost" and CONFIG_KANNEL_PORT is defined as 13013 then it's effectively doing the same thing, albeit with additional character set operations.)
Not to ressucitate an ancient question, but for posteriority and others searching for the same thing:
[root#sat2 tools]# cat kannel-send.php
<?php
function send_sms($msgid, $numto, $msgtext, $smsc = "smsc-default", $dlrmask = 63)
{
$sendsmsurl_prefix = "http://localhost:13013/cgi-bin/sendsms";
$dlrurl_prefix = "http://localhost/tools/kannel-receive.php";
$username = "user";
$password = "pass";
# fix number to what carriers expect
$numto = preg_replace('/^0/', '', $numto);
$numto = preg_replace('/^\+55/', '', $numto);
$numto = "0" . $numto;
if (!$msgid) $dlrmask = 0;
$dlrurl_params = array(
"type" => "dlr",
"timesent" => "%t",
"smsc" => "%i",
"uuid" => "%I",
"fid" => "%F",
"dlr-cod" => "%d",
"reply" => "%A",
"msgid" => $msgid,
"text" => "%a",
"to" => "%P",
"from" => "%p",
"origsmsc" => "%f",
);
$dlrurl = $dlrurl_prefix . "?" . urldecode(http_build_query($dlrurl_params));
$sendsmsurl_params = array(
"username" => $username,
"password" => $password,
"to" => $numto,
"dlr-mask" => $dlrmask,
"dlr-url" => $dlrurl,
"smsc"=> $smsc,
"text" => $msgtext,
);
$sendsmsurl = $sendsmsurl_prefix . "?" . http_build_query($sendsmsurl_params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sendsmsurl);
$bogus = curl_exec($ch);
$ret = curl_error($ch);
curl_close($ch);
return $ret == "";
}
?>
And you could have this other one to receive sms and store it to mysql:
[root#sat2 tools]# cat kannel-receive.php
<?php
$debug = false;
$link = null;
function dbconnect()
{
global $link, $debug;
if ($link && mysql_ping($link))
return;
if ($debug) echo "Conectando ao banco de dados\n";
// TODO: criar um usuario de banco especifico pra isso
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'dbname';
$link = mysql_connect($host, $user, $pass, true);
if (!$link){
if ($debug) echo "Can't connect to mysql: " . mysql_error() . "\n";
} else {
mysql_select_db($db, $link);
}
return;
}
function esc($str)
{
global $link;
return mysql_real_escape_string($str, $link);
}
if ($debug) {
echo "<br>Kannel inbound sms event:<br>\n";
var_dump($_GET);
}
dbconnect();
if ($_GET['type'] == "inbsms") {
$_GET['from'] = preg_replace('/^(\+55|0)/', '', $_GET['from']);
$sql = "INSERT INTO notificacao (tipo, endereco, mensagem, device,
dataEvento, situacao)
VALUES ('%s', '%s','%s','%s','%s','%s')";
$sql = sprintf($sql, 'sms', esc($_GET['from']), esc($_GET['text']),
esc($_GET['smsc']), esc($_GET['timesent']), "received");
} elseif ($_GET['type'] == "dlr") {
switch (esc($_GET['dlr-cod'])) {
case "1":
$sql = "UPDATE notificacao SET
situacao = 'confirmed',
dataConfirmacao = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "8":
$sql = "UPDATE notificacao SET
situacao = 'sent',
device = '{$_GET['smsc']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "16":
$sql = "UPDATE notificacao SET
situacao = 'failed',
device = '{$_GET['smsc']}',
razaofalha = '{$_GET['reply']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
}
}
if ($debug) echo "sql: $sql\n";
$result = mysql_query($sql, $link);
if (!$result) {
if ($debug) echo "Erro sql: " . mysql_error() . "\n";
}
?>
This one doubles as a SMS receiver and a SMS-Delivery-Notification receiver (in that case it updates a record on the database that was put there when sending the sms, to confirm it was received).
It's used for DLR because I send the URL for that when sending the SMS (and set the DLR mask asking for confirmation), but for inbound SMS you have to configure your kannel.conf to use it (you can have many sms-service, this is just an example of a catch-all one:
[...]
group = sms-service
keyword = default
get-url = "http://localhost/tools/kannel-receive.php?type=inbsms&text=%a×ent=%t&from=%p&to=%P&smsc=%i&uuid=%I&delivery=%d&service=%n&encoding=%c&class=%m&mwi=%M&charset=%C&udh=%u&dcs=%O&origsmsc=%f"
catch-all = yes
max-messages = 0
accept-x-kannel-headers = true
concatenation = yes
omit-empty = yes
[...]
Sorry for some texts in portuguese, but you can get the picture.
//php code file name is test2.php.before that,you must install php5-curl on ubuntu14