anyway to edit dd-wrt nvram .bin backup ( settings backup) file? - binary

is there any way to edit the .bin backup ? i found program by nirosoft called "routerpassview" and it decrypted it very well but don't know how to encrypt it again to .bin file and restore settings
DECIMAL HEXADECIMAL DESCRIPTION
84 0x54 Zlib compressed data, default compression
it seems pointless but i need it to disable sim lock

Here's a little php script i use for these things. Hope it helps:
#!/usr/bin/php
<?PHP
/*
* phpnvram - command line editor for DD-WRT nvram-backup
* Copyright (C) 2015 Markus Quint <markus#dd-wrt.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
**/
global $argc, $argv;
if (php_sapi_name() == "cli")
cli();
function cli()
{
global $argc, $argv;
$CMD = array(
// command => count parameter
"get" => 1,
"rget" => 1,
"fget" => 2, // get parameter to file
"set" => 1,
"fset" => 2, // set parameter from file
"unset" => 1,
"show" => 0,
"showkeys" => 0,
"diff" => 1, // diff bewtween two files
"vdiff" => 1, // verbose diff
"rdiff" => 2, // diff values matching a regualr expression
);
if ($argc < 3 || !file_exists($argv[1]))
cli_help();
if (!array_key_exists($argv[2], $CMD))
cli_help();
if ( ($argc - 3) < $CMD[$argv[2]] )
cli_help();
$nvrambak = new nvram($argv[1]);
if ($nvrambak->get_errno())
echo $nvrambak->get_errmsg($nvrambak->get_errno());
$nvram = $nvrambak->nvram_getconfig();
$count = $argc - (($argc - 3) - ($CMD[$argv[2]] - 1));
for ($i=$argc; $i>$count; $i--)
$pattern[] = $argv[$i-1];
switch ($argv[2]) {
case "get":
$nvrambak->cli_get($nvram, $argv[3]);
break;
case "rget":
$nvrambak->cli_rget($nvram, $pattern);
break;
case "fget":
$nvrambak->cli_fget($nvram, $argv[3], $argv[4]);
break;
case "set":
$nvrambak->cli_set($nvram, $argv[3]);
break;
case "fset":
$nvrambak->cli_fset($nvram, $argv[3], $argv[4]);
break;
case "unset":
$nvrambak->cli_unset($nvram, $argv[3]);
break;
case "show":
$nvrambak->cli_show($nvram);
break;
case "showkeys":
$nvrambak->cli_keys($nvram);
break;
case "diff":
$nvrambak->cli_diff($nvram, $argv[3]);
break;
case "vdiff":
$nvrambak->cli_diff($nvram, $argv[3], true);
break;
case "rdiff":
$nvrambak->cli_rdiff($nvram, $argv[3], $pattern);
break;
}
if ($nvrambak->get_errno())
echo $nvrambak->get_errmsg($nvrambak->get_errno());
}
function cli_help($cmd="")
{
global $argv;
printf("Usage:\n%s <nvrambak.bin> %s\n %37s%s\n %37s%s\n %37s%s\n %37s%s\n %37s%s\n %37s%s\n %37s%s\n %37s%s\n %37s%s\n %37s%s\n",
$argv[0],
"[get name]",
" ", "[rget regex]",
" ", "[fget name <target-file>]",
" ", "[set name=value]",
" ", "[fset name <source-file>]",
" ", "[unset name]",
" ", "[show]",
" ", "[showkeys]",
" ", "[diff <nvrambak.bin>]",
" ", "[vdiff <nvrambak.bin>]",
" ", "[rdiff <nvrambak.bin> regex]"
);
exit();
}
class nvram
{
const FILE_HEAD = "DD-WRT";
private $backup_fname;
private $backup_fhandle;
private $backup_config = array();
public function __construct($backup_fname="nvrambak.bin")
{
if ( !($handle = $this->backup_fread($backup_fname, $this->backup_config)) )
return;
$this->backup_fname = $backup_fname;
$this->backup_fhandle = $handle;
$this->backup_fclose();
$this->set_error($this->ERR_NO["SUCCESS"]);
}
/* core functions **********
*
*/
private function backup_fclose()
{
if ($this->backup_fhandle) {
fclose($this->backup_fhandle);
$this->backup_fhandle = NULL;
}
}
private function backup_fread($fname, &$config_buff)
{
if (!$fname || !is_array($config_buff) )
return 0;
if (!file_exists($fname)) {
$this->set_error($this->ERR_NO["DONT_EXISTS"]);
return 0;
}
$fhandle = fopen($fname, "rb");
if (!$fhandle) {
$this->set_error($this->ERR_NO["CANT_OPENR"]);
return 0;
}
$len = filesize($fname);
$fhead = fread($fhandle, strlen(self::FILE_HEAD));
if ($fhead != self::FILE_HEAD) {
$this->set_error($this->ERR_NO["NOT_VALID"]);
return 0;
}
$len -= 6;
$byte = fread($fhandle, 1);
$data = unpack("H*", $byte);
$byte = base_convert($data[1], 16, 10);
$count = $byte;
$byte = fread($fhandle, 1);
$data = unpack("H*", $byte);
$byte = base_convert($data[1], 16, 10);
$count += ($byte << 8);
$len -= 2;
for ($i=0; $i < $count && $len > 0; $i++)
{
$byte = fread($fhandle, 1);
$data = unpack("H*", $byte);
$slen = base_convert($data[1], 16, 10);
if ($slen == 0) { // workaround for buggy nvram format
$this->set_error($this->ERR_NO["SUCCESS_WERR"]);
fread($fhandle, 2);
$len -= 3;
continue;
}
$name = sprintf("%s", fread($fhandle, $slen));
$len -= ($slen + 1);
$byte = fread($fhandle, 1);
$data = unpack("H*", $byte);
$byte = base_convert($data[1], 16, 10);
$slen = $byte;
$byte = fread($fhandle, 1);
$data = unpack("H*", $byte);
$byte = base_convert($data[1], 16, 10);
$slen += ($byte << 8);
$len -= ($slen + 2);
if ($slen > 0)
$value = fread($fhandle, $slen);
else
$value = "";
$config_buff[$name] = $value;
}
if ($this->get_errno() != $this->ERR_NO["SUCCESS_WERR"])
$this->set_error($this->ERR_NO["SUCCESS"]);
return $fhandle;
}
private function backup_fwrite($fname, $config)
{
$fhandle = fopen($fname, "wb");
if (!$fhandle) {
$this->set_error($this->ERR_NO["CANT_OPENW"]);
return;
}
fwrite($fhandle, self::FILE_HEAD, strlen(self::FILE_HEAD));
$count = count($config);
$data = base_convert($count & 255, 10, 16);
fwrite($fhandle, pack("H" . 2, sprintf("%02s", $data)));
$data = base_convert($count >> 8, 10, 16);
fwrite($fhandle, pack("H" . 2, sprintf("%02s", $data)));
foreach ($config AS $name => $value) {
$len = strlen($name);
$data = base_convert($len, 10, 16);
fwrite($fhandle, pack("H" . 2, sprintf("%02s", $data)));
fwrite($fhandle, $name);
$len = strlen($value);
$data = base_convert($len & 255, 10, 16);
fwrite($fhandle, pack("H" . 2, sprintf("%02s", $data)));
$data = base_convert($len >> 8, 10, 16);
fwrite($fhandle, pack("H" . 2, sprintf("%02s", $data)));
fwrite($fhandle, $value);
}
fclose($fhandle);
$this->set_error($this->ERR_NO["SUCCESS"]);
}
private function shadow($password)
{
$hash = '';
for($i=0;$i<8;$i++)
{
$j = mt_rand(0,53);
if($j<26)$hash .= chr(rand(65,90));
else if($j<52)$hash .= chr(rand(97,122));
else if($j<53)$hash .= '.';
else $hash .= '/';
}
return crypt($password,'$1$'.$hash.'$');
}
/* programming interface **********
*
*/
public function nvram_writeconfig($config, $fname)
{
if(!$fname OR !$config OR !is_array($config))
return;
$this->backup_fwrite($fname, $config);
}
public function nvram_changevalues(&$nvram, $changes)
{
if (!$nvram OR !$changes)
return;
foreach ($changes AS $name => $value) {
if ($value === NULL)
unset($nvram[$name]);
else
$nvram[$name] = $value;
}
}
public function nvram_getconfig()
{
if (count($this->backup_config))
return $this->backup_config;
}
public function nvram_rget($nvram, $pattern)
{
if (!$nvram || !$pattern)
return;
$config = $this->nvram_getconfig();
foreach($config AS $name => $value) {
for ($i=0; $i<count($pattern); $i++)
if (preg_match($pattern[$i], $name))
$result[$name] = $value;
}
return $result;
}
public function nvram_diff($nvram, $diff_fname)
{
$diff_config = array();
$this->backup_fread($diff_fname, $diff_config);
if ($this->get_errno()) {
echo $this->get_errmsg($this->get_errno());
}
$result = array("identic" => array(),
"different" => array(),
"orig_only" => array(),
"diff_only" => array(),
);
foreach($nvram AS $name => $value)
{
if(!array_key_exists($name, $diff_config))
$result["orig_only"][$name] = $value;
else {
if ($nvram[$name] == $diff_config[$name])
$result["identic"][$name] = $value;
else {
$result["different"][$name][$this->backup_fname] = $value;
$result["different"][$name][$diff_fname] = $diff_config[$name];
}
}
}
foreach ($diff_config AS $name => $value) {
if (!array_key_exists($name, $nvram))
$result["diff_only"][$name] = $value;
}
return $result;
}
public function nvram_rdiff($nvram, $diff_fname, $pattern)
{
if (!$nvram || !$diff_fname || !$pattern)
return;
$full_diff = $this->nvram_diff($nvram, $diff_fname);
foreach($full_diff AS $class => $list) {
foreach($list AS $name => $value) {
for ($i=0; $i<count($pattern); $i++)
if (preg_match($pattern[$i], $name))
$result[$class][$name] = $value;
}
}
return $result;
}
public function nvram_fromfile($fname)
{
if (!$fname)
return;
if (!file_exists($fname)) {
$this->set_error($this->ERR_NO["FILE_EXISTS"]);
return;
}
$fhandle = fopen($fname, "rb");
if (!$fhandle) {
$this->set_error($this->ERR_NO["CANT_OPENR"]);
return;
}
$value = fread($fhandle, filesize($fname));
$this->set_error($this->ERR_NO["SUCCESS"]);
fclose($fhandle);
return $value;
}
/* commandline functions **********
*
*/
public function cli_get($nvram, $name)
{
if (!$nvram OR !$name)
return;
if (count($nvram))
printf("%s\n", $nvram[$name]);
}
public function cli_rget($nvram, $pattern)
{
if (!$nvram || !$pattern)
return;
$result = $this->nvram_rget($nvram, $pattern);
print_r($result);
}
public function cli_fget($nvram, $name, $fname)
{
if (!$name || !$fname)
return;
if (file_exists($fname)) {
$this->set_error($this->ERR_NO["FILE_EXISTS"]);
return;
}
$fhandle = fopen($fname, "wb+");
if (!$fhandle) {
$this->set_error($this->ERR_NO["CANT_OPENW"]);
return;
}
if ( fwrite($fhandle, $nvram[$name], strlen($nvram[$name])) )
$this->set_error($this->ERR_NO["SUCCESS"]);
fclose($fhandle);
return;
}
public function cli_set(&$nvram, $namevalue)
{
if (!$nvram OR !$namevalue)
return;
if (count($nvram))
{
// gibts nicht mehr seit php7
// $set = split("=", $namevalue);
$set = explode("=", $namevalue,2);
$name = $set[0];
$value = substr($namevalue,strlen($set[0])+1);
if ($name == "http_username" || $name == "http_passwd")
$nvram[$name] = $this->shadow($value);
else
$nvram[$name] = $value;
}
$this->backup_fwrite($this->backup_fname, $nvram);
}
public function cli_unset(&$nvram, $name)
{
if (!$nvram OR !$name)
return;
if (count($nvram))
unset($nvram[$name]);
$this->backup_fwrite($this->backup_fname, $nvram);
}
public function cli_show($nvram)
{
if (count($nvram))
foreach ($nvram AS $name => $value)
printf ("%s=%s\n", $name, $value);
}
public function cli_keys($nvram)
{
if (count($nvram)) {
foreach ($nvram AS $name => $value)
printf ("%s\n", $name);
}
}
public function cli_diff($nvram, $d_fname, $full=false)
{
$result = $this->nvram_diff($nvram, $d_fname);
if ($full) {
echo "Identical:\n";
print_r ($result["identic"]);
echo "\n";
}
echo "Only in $this->backup_fname\n";
ksort($result["orig_only"]);
print_r($result["orig_only"]);
echo "\nOnly in $d_fname\n";
ksort($result["diff_only"]);
print_r($result["diff_only"]);
echo "\nDifferences:\n";
ksort($result["different"]);
print_r($result["different"]);
}
public function cli_rdiff($nvram, $d_fname, $pattern)
{
if (!$nvram || !$d_fname || !$pattern)
return;
$full_diff = $this->nvram_rdiff($nvram, $d_fname, $pattern);
print_r($full_diff);
}
/*
public function cli_fset($nvram, $name, $fname)
{
if (!$name || !$fname)
return;
if (!file_exists($fname)) {
$this->set_error($this->ERR_NO["DONT_EXISTS"]);
return;
}
$fhandle = fopen($fname, "rb");
if (!$fhandle) {
$this->set_error($this->ERR_NO["CANT_OPENR"]);
return;
}
$nvram[$name] = fread($fhandle, filesize($fname));
$this->backup_fwrite($this->backup_fname, $nvram);
$this->set_error($this->ERR_NO["SUCCESS"]);
fclose($fhandle);
return;
}
*/
/* misc **********
*
*/
public function strcrypt($passwd)
{
if ($passwd)
return $this->shadow($passwd);
return "";
}
/* error **********
*
*/
private $err_errno;
private $err_errmsg;
private $ERR_NO = array("SUCCESS" => 0,
"DONT_EXISTS" => 1,
"CANT_OPENR" => 2,
"NOT_VALID" => 3,
"SUCCESS_WERR" => 4,
"CANT_OPENW" => 5,
"FILE_EXISTS" => 6,
);
private $ERR_MSG = array(0 => "Success\n",
1 => "File not found\n",
2 => "Could not open file for reading\n",
3 => "File is not a valid nvram-backup\n",
4 => "Success, but skipped faulty null-param\n",
5 => "Could not open file for writing\n",
6 => "File already exists\n",
);
private function set_error($err_no)
{
$this->err_errno = $err_no;
$this->err_errmsg = $this->ERR_MSG[$err_no];
}
public function get_errno()
{
return $this->err_errno;
}
public function get_errmsg()
{
return $this->err_errmsg;
}
}
?>

Related

convert csv file to json object with Laravel

I am doing a project with Laravel 7. I have to read a csv file and through a controller passing the data in json format to a view.
Unfortunately I don't know how to do that.
These are my controller methods:
public function index($source)
{
$source = strtolower($source);
switch ($source) {
case "csv":
$file_csv = base_path('transactions.csv');
$transactions = $this->csvToJson($file_csv);
dd(gettype($transactions));
return view('transactions', ['source' => $source, 'transactions' => $transactions]);
break;
case "db":
$transactions = Transaction::all();
dd(gettype($transactions));
return view('transactions', ['source' => $source, 'transactions' => $transactions]);
break;
default:
abort(400, 'Bad sintax error.');
}
}
function csvToJson($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename)) {
return false;
}
$header = null;
$data = array();
if (($handle = fopen($filename, 'r')) !== false)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== false)
{
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
As you can see, under the two cases I put a dd with a gettype function inside. In the first case I receive uncorrectly the response array, in the second one I receive correctly the response object.
The converted csv file should have this format:
[{"id":1,"code":"T_218_ljydmgebx","amount":"8617.19","user_id":375,"created_at":"2020-01-19T16:08:59.000000Z","updated_at":"2020-01-19T16:08:59.000000Z"},
{"id":2,"code":"T_335_wmhrbjxld","amount":"6502.72","user_id":1847,"created_at":"2020-01-19T16:08:59.000000Z","updated_at":"2020-01-19T16:08:59.000000Z"}]
Do you know how to convert the array transactions into a json object in the first case?
I don't know if there is any build-in solution on Laravel, but it can be done by PHP.
I didn't test my code. So it might not work, or contain some typos, but I'm sure it will give you some directions.
$cols = ["id","code","amount","user_id","created_at","updated_at"];
$csv = file('folder/name.csv');
$output = [];
foreach ($csv as $line_index => $line) {
if ($line_index > 0) { // I assume the the first line contains the column names.
$newLine = [];
$values = explode(',', $line);
foreach ($values as $col_index => $value) {
$newLine[$cols[$col_index]] = $value;
}
$output[] = $newLine;
}
}
$json_output = json_encode($output);
You can just do this :
$csv= file_get_contents($file);
$array = array_map('str_getcsv', explode(PHP_EOL, $csv));
$json json_encode($array);
If you want to return json object
return $json;
If you want to create a .json file
// Pure PHP
$file = fopen('results.json', 'w');
fwrite($file, $json);
fclose($file);
// Laravel using Storage
Storage::disk('local')->put('public/result.json', $json);
I hope this helps somone.
I have an email marketing application where I made bulk importers. So here is their CSV TO JSON code.
function convert_csv_to_json($csv_data){
// CSV to JSON process 1
$context = array(
'http'=>array(
'follow_location' => false,
'max_redirects' => 1000000
)
);
$context = stream_context_create($context);
if (($handle = fopen($csv_data, "r", false, $context)) !== FALSE) {
$csvs = [];
while(! feof($handle)) {
$csvs[] = fgetcsv($handle);
}
$datas = [];
$column_names = [];
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
foreach ($csvs as $key => $csv) {
if ($key === 0) {
continue;
}
foreach ($column_names as $column_key => $column_name) {
$datas[$key-1][$column_name] = $csv[$column_key];
}
}
return $json = json_encode($datas);
}
// OR
// CSV to JSON process 1
$cols = ['id',
'owner_id',
'name',
'email',
'country_code',
'phone',
'favourites',
'blocked',
'trashed',
'is_subscribed',
'deleted_at',
'created_at',
'updated_at.'];
$csv = file($csv_data);
$output = [];
foreach ($csv as $line_index => $line) {
if ($line_index > 0) { // I assume the the first line contains the column names.
$newLine = [];
$values = explode(',', $line);
foreach ($values as $col_index => $value) {
$newLine[$cols[$col_index]] = $value;
}
$output[] = $newLine;
}
}
return $json_output = json_encode($output);
}

Getting json_encode(): type is unsupported, encoded as null

I am working on web services where am using json_encode() to send my response .
It is working fine for every ther web service but I am getting json_encode(): type is unsupported, encoded as null for the following code only.
public function getjobdetailsAction()
{
$this->_helper->layout ()->disableLayout ();
$this->_helper->viewRenderer->setNoRender ( true );
$handle = fopen ( 'php://input', 'r' );
$jsonInput = fgets ( $handle );
$params = Zend_Json::decode ( $jsonInput );
if($params['user_id'] != "" && $params["job_id"] != "")
{
$job_id = $params["job_id"];
$jobObj=Extended\job::getRowObject( $job_id );
//check if job obj exist only then send job array to view.
if($jobObj)
{
$job_detail_r = array();
$job_detail_r['job_id'] = $job_id;
$job_detail_r['job_created_by'] = $jobObj->getIlookUser()->getId();
$job_detail_r['job_title'] = $jobObj->getJob_title();
$job_detail_r['url_fields'] = $jobObj->getUrl_fields();
$job_detail_r['job_reference'] = $jobObj->getJob_reference();
$job_detail_r['company_name'] = $jobObj->getCompany()->getName();
$job_detail_r['responsibilities'] = $jobObj->getResponsibilities();
$job_detail_r['industry_name'] = $jobObj->getIndustryRef()->getTitle();
$job_detail_r['skills_expertise'] = $jobObj->getSkills_n_expertise();
$job_detail_r['country'] = $jobObj->getCountryRef()->getName();
if( $jobObj->getState() )
{
$job_detail_r['state'] = $jobObj->getState()->getName();
}
else
{
$job_detail_r['state'] = "";
}
if($jobObj->getCity())
{
$job_detail_r['city'] = $jobObj->getCity()->getName();
}
else
{
$job_detail_r['city'] = "";
}
//$job_detail_r['job_function'] = $jobObj->getJobFunction()->getDescription();
$job_detail_r['job_description'] = $jobObj->getJob_description();
$job_detail_r['company_description'] = $jobObj->getCompany_desc();
if($jobObj->getSalaryRange())
{
$job_detail_r['salaryRange'] = $jobObj->getSalaryRange()->getCountryRef()->getCurrency_symbol()." ".$jobObj->getSalaryRange()->getMin_salary()." - ".$jobObj->getSalaryRange()->getMax_salary();
}
else
{
$job_detail_r['salaryRange'] = "";
}
$job_detail_r['jobType'] = $jobObj->getJobType()->getName();
//$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getMin_experience()." - ".$jobObj->getExperieneceLevel()->getMax_experience()." Years";
if($jobObj->getExperieneceLevel())
{
$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getDescription();
}
else
{
$job_detail_r['experienceLevel'] = "";
}
$job_detail_r['job_creator_image'] = Helper_common::getUserProfessionalPhoto( $jobObj->getIlookUser()->getId() );
$job_detail_r['time_of_post'] =$jobObj->getCreated_at()->format("Y-m-d H:i:s");
$job_detail_r['job_posted_by'] = $jobObj->getJob_posted_by();
$job_detail_r['apply_from'] = $jobObj->getApply_from();
if($jobObj->getJob_image() != "")
{
$job_detail_r['company_image'] = IMAGE_PATH."/jobs/".$jobObj->getJob_image();
}
else
{
$job_detail_r['company_image'] = IMAGE_PATH.'/no_image.png';
}
$job_detail_r['is_saved'] = Extended\saved_jobs::isJobSavedByMe($job_id,$params['user_id']);
$code = 200;
$msg = "Job details retrieved successfully";
$result = array("jobdetails"=>$job_detail_r);
}
else
{
$code = 301;
$msg = "Error in retrieving details";
}
}
else
{
$code = 301;
$msg = "Missing parameters";
}
echo Helper_common::successFailureMsgs($code,$msg,$result);
exit();
public static function successFailureMsgs( $code, $message, $result = array())
{
if($code == 200)
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"OK","Message"=>$message,"result"=>$result));
}
else
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"Error","Message"=>$message));
}
return Zend_Json::encode($result1);
}
In response I am getting correct response but the above error as well .
Please assist.
Thanks in advance.
For json_encode(), and therefore Zend_Json(), all types are accepted except resource.
So you have debbuger your table to see where the resource is located.
You can try something like this:
foreach ($job_detail_r as $k => $v){
if (is_resource($v))
echo $k . ' => ressource type = ' . get_resource_type($v);
}

Token field json syntax error bootstrap

I have around 700 product list in my Databse table.
I am using bootstrap's tokenfield for auotcomplete, i have to use auto complete in search textbox.
I am getting syntax error :
SyntaxError: missing ] after element list
...B','Lino Perros Men's Leather Wallet - Pink','Lenovo A269i','Lenovo S660 - Tita**
in console.
<?php $t = $this->general_model->auto_complete_sug(); ?>
$( document ).ready(function() {
$('#tokenfield-2').tokenfield({
autocomplete: {
source: <?=$t?>,
delay : 100
},
limit: 1,
minLength: 1,
showAutocompleteOnFocus: true
});
});
<input type="text" class="span2" name="search" id="tokenfield-2" placeholder="Search...">
In my model: I have created this functions:
public function auto_complete_sug()
{
$data = $this->auto_complete_token_fun();
$data1 = explode(',', $data);
$data1 = array_unique($data1);
foreach ($data1 as $value1) {
$temparr[] = $value1;
}
$str = '[';
$c = count($temparr);
$counter = 0;
foreach ($temparr as $val) {
$counter++;
$str .= "'".$val."'";
if($counter < $c){
$str .= ",";
}
}
$str .= ']';
return $str;
}
public function auto_complete_token_fun()
{
// $this->db->query("SET GLOBAL group_concat_max_len = 10000000");
$q = $this->db->query("SELECT GROUP_CONCAT( sub_category_name ) AS scname
FROM `tbl_subcategory` WHERE status = 'Active' ");
if($q->num_rows() > 0)
{
$d = $q->row_array();
return $d['scname'];
}
else
{
return '';
}
}
Please help!!

Amazon Product Ads, is there an API to search for Categories?

I'm building a module that will help seller put their products catalogue in the Amazon Product Ads service. For that, I need to make a mapping between the client's category and the Amazon Product Ads categories.
Problem is, I can't find an API that will help me search for Categories, or a file containing all the existing categories for Amazon Product Ads.
I found that link http://docs.aws.amazon.com/AWSECommerceService/latest/DG/BrowseNodeIDs.html, that may be a start, but based on their API, it's not possible to search by text (like "Apparel") but by NodeId, which is not what I'm looking for :/
Can anyone of you help me please?
Thank you for your help :)
You have to use Browse Node Id of parent categories and bases on that you can search for sub categories.
Create a file named amazon_api_class.php
<?php
require_once 'aws_signed_request.php';
class AmazonProductAPI
{
/**
* Your Amazon Access Key Id
* #access private
* #var string
*/
private $public_key = "";
/**
* Your Amazon Secret Access Key
* #access private
* #var string
*/
private $private_key = "";
private $media_type = "";
private $region = "";
private $out_file_fp = "";
public function __construct($public, $private, $region) {
$this->public_key = $public;
$this->private_key = $private;
$this->region = $region;
}
public function getNode($node)
{
$parameters = array("Operation" => "BrowseNodeLookup",
"BrowseNodeId" => $node,
"ResponseGroup" => "BrowseNodeInfo");
$xml_response = aws_signed_request($parameters,
$this->public_key,
$this->private_key,
$this->region);
return ($xml_response);
}
public function setMedia($media, $file = "") {
$media_type = array("display", "csv");
if(!in_array($media,$media_type)) {
throw new Exception("Invalid Media Type");
exit();
}
$this->media_type = $media;
if($media == "csv") {
$this->out_file_fp = fopen($file,'a+');
}
}
private function writeOut($level, $name, $id, $parent) {
if($this->media_type == "display") {
$spaces = str_repeat( ' ', ( $level * 6 ) );
echo $spaces . $parent . ' : ' . $name . ' : ' . $id . "\n";
} elseif ($this->media_type == "csv") {
$csv_line = '"' . $parent . '","' . $name . '","' . $id . '"' . "\n";
fputs($this->out_file_fp, $csv_line);
} else {
throw new Exception("Invalid Media Type");
exit();
}
}
public function getBrowseNodes($nodeValue, $level = 0)
{
try {
$result = $this->getNode($nodeValue);
}
catch(Exception $e) {
echo $e->getMessage();
}
if(!isset($result->BrowseNodes->BrowseNode->Children->BrowseNode)) return;
if(count($result->BrowseNodes->BrowseNode->Children->BrowseNode) > 0) {
foreach($result->BrowseNodes->BrowseNode->Children->BrowseNode as $node) {
$this->writeOut($level, $node->Name,
$node->BrowseNodeId,
$result->BrowseNodes->BrowseNode->Name);
$this->getBrowseNodes($node->BrowseNodeId, $level+1);
}
} else {
return;
}
}
public function getNodeName($nodeValue)
{
try {
$result = $this->getNode($nodeValue);
}
catch(Exception $e) {
echo $e->getMessage();
}
if(!isset($result->BrowseNodes->BrowseNode->Name)) return;
return (string)$result->BrowseNodes->BrowseNode->Name;
}
public function getParentNode($nodeValue)
{
try {
$result = $this->getNode($nodeValue);
}
catch(Exception $e) {
echo $e->getMessage();
}
if(!isset($result->BrowseNodes->BrowseNode->Ancestors->BrowseNode->BrowseNodeId)) return;
$parent_node = array("id" => (string)$result->BrowseNodes->BrowseNode->Ancestors->BrowseNode->BrowseNodeId,
"name" => (string)$result->BrowseNodes->BrowseNode->Ancestors->BrowseNode->Name);
return $parent_node;
}}?>
Create file named as aws_signed_request.php
<?php
function aws_signed_request($params,$public_key,$private_key,$region)
{
$method = "GET";
$host = "ecs.amazonaws.".$region; // must be in small case
$uri = "/onca/xml";
$params["Service"] = "AWSECommerceService";
$params["AWSAccessKeyId"] = $public_key;
$params["AssociateTag"] = 'YOUR-ASSOCIATES-ID-HERE';
$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
$params["Version"] = "2009-03-31";
/* The params need to be sorted by the key, as Amazon does this at
their end and then generates the hash of the same. If the params
are not in order then the generated hash will be different thus
failing the authetication process.
*/
ksort($params);
$canonicalized_query = array();
foreach ($params as $param=>$value)
{
$param = str_replace("%7E", "~", rawurlencode($param));
$value = str_replace("%7E", "~", rawurlencode($value));
$canonicalized_query[] = $param."=".$value;
}
$canonicalized_query = implode("&", $canonicalized_query);
$string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query;
/* calculate the signature using HMAC with SHA256 and base64-encoding.
The 'hash_hmac' function is only available from PHP 5 >= 5.1.2.
*/
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
/* encode the signature for the request */
$signature = str_replace("%7E", "~", rawurlencode($signature));
/* create request */
$request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature;
/* I prefer using CURL */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$xml_response = curl_exec($ch);
if ($xml_response === False)
{
return False;
}
else
{
/* parse XML */
$parsed_xml = #simplexml_load_string($xml_response);
return ($parsed_xml === False) ? False : $parsed_xml;
}
}
?>
Create file named as index.php
<?php
/* Example usage of the Amazon Product Advertising API */
include("amazon_api_class.php");
$public_key = "YOUR-AMAZON-PUBLIC-KEY";
$private_key = "YOUR-AMAZON-SECRET-KEY";
$region = "com"; // or "CA" or "DE" etc.
$obj = new AmazonProductAPI($public_key, $private_key, $region);
$obj->setMedia("display");
$obj->getBrowseNodes("1036592"); //Apparel US store
?>
Dont forget to update your public and private key in index.php

Registering user with PDO

I have a problem while processing the register
Here is the code for the function:
<?php
include $_SERVER['DOCUMENT_ROOT']. "/config/config.php";
$conn = new PDO('mysql:host=' . $ip . ';dbname=' . $database, $username, $password);
function registerUser($username, $password, $passwordagain, $email, $mcname)
{
$validusername= "/^[a-z0-9]+$/";
$validpassword= "/^[A-Za-z0-9]+$/";
$validemail= "/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
$validmcname= "/^[A-Za-z0-9]+$/";
$error = 0;
if(strlen($username)<4 || strlen($username)>24)
{
$error = 1;
}
if(strlen($password)<6 || strlen($password)>24)
{
$error = 1;
}
if(strlen($mcname)<4 || strlen($mcname)>24)
{
$error = 1;
}
if(!preg_match($validusername, $username))
{
$error = 1;
}
if(!preg_match($validpassword, $password))
{
$error = 1;
}
if(!preg_match($validemail, $email))
{
$error = 1;
}
if(!preg_match($validmcname, $mcname))
{
$error = 1;
}
if($password != $passwordagain)
{
$error = 1;
}
$userexistquery = $conn->query('SELECT * FROM users WHERE username=' . $username);
$userexist = $userexistquery->fetch();
if(count($userexist) != 0)
{
$error=1;
echo "<div class='erroralert'>Username already exists!</div>";
}
$emailexistquery = $conn->query('SELECT * FROM users WHERE email=' . $email);
$emailexist = $emailexistquery->fetch();
if($emailexist != 0)
{
$error=1;
echo "<div class='erroralert'>E-mail already exists!</div>";
}
if($error != 1)
{
$encryptedpassword = hash('sha512', $password);
$registeruser = $conn->query("INSERT INTO users(username, password, email, mcname) VALUES ('$username', '$encryptedpassword', '$email', '$mcname')");
echo "<div class='successalert'>Succesfully registred</div>";
}
else
{
echo "<div class='erroralert'>An error occured during registration.</div>";
}
}
?>
The error that gives me is:
Notice: Undefined variable: conn in C:\xampp\htdocs\functions\functions.php on line 45
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\functions\functions.php on line 45
You instantiate your variable $conn outside of the function. You have to pass it as an argument in order to use it inside.