codeignigter use rest to pass data to external site - php

OK in plain PHP I use the following to pass data to a GET
file_get_contents('https://ws.mysite.com/some.svc/here?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
I now want to apply this same piece of code to my CI project.
This Is how I have tried.
private function getResults()
{
$score = $this->actions->getSentEmailCount();
$percentilescore = $percentile = $this->actions->getPercentile($score);
$testID = '134';
$percentile = $this->actions->getPercentile($score);
$time = $this->input->get('time');
$timemath = 60000;
$timeinmseconds = $time * $timemath;
$adddata = array(
'uniID' => '5',
'testName' => 'some',
'testID' => $testID,
'total' => '10',
'correct' => $score = $this->actions->getScore(),
'percent' => $score = $this->actions->getScore(),
'dateTaken' => date('Y-m-d H:i:s'),
'timeSpent' => $timeinmseconds,
'userID' => $session_id,
);
$this->actions->add_record($adddata);
return $this->load->view('client/results', $data);
file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
}
It is not posting the data any idea why and how I should do it in CI ?

return should be the last statement in the function because it's immediately ends execution of the current function. Just put file_get_contents before return:
file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');
$this->actions->add_record($adddata);
return $this->load->view('client/results', $data);

Related

How to transfer a variable from 1 function to another in the controller?

It is not possible to transfer data from one controller to another. There is such a controller for filling mp3 files via Dropzone.JS:
public function upload(Request $request)
{
if (!$request->has('file')) {
return response()->json(['message' => 'Missing file'], 422);
}
$file = $request->file('file');
$extension = !is_null($file->extension()) ? $file->extension() : 'mp3';
$fileName = !is_null($file->getClientOriginalName()) ? rtrim($file->getClientOriginalName(), '.') : 'Unknown - Unknown.mp3';
$tracksPath = 'public/tracks/';
$globalPath = storage_path('app/public/tracks/');
$globalTrackPath = $globalPath . $fileName;
$file->move(storage_path('app/public/tracks'), $fileName);
$fileHash = sha1_file($globalTrackPath);
rename($globalTrackPath, $globalPath . $fileHash . '.' . $extension);
$track = GetId3::fromDiskAndPath('storage', 'app/public/tracks/' . $fileHash . '.' . $extension);
$t = $track->extractInfo();
$title = !empty($t['tags']['id3v2']['title']['0']) ? $t['tags']['id3v2']['title']['0'] : 'Unknown';
$artist = !empty($t['tags']['id3v2']['artist']['0']) ? $t['tags']['id3v2']['artist']['0'] : 'Unknown';
$band = !empty($t['tags']['id3v2']['band']['0']) ? $t['tags']['id3v2']['band']['0'] : '';
$album = !empty($t['tags']['id3v2']['album']['0']) ? $t['tags']['id3v2']['album']['0'] : '';
$year = !empty($t['tags']['id3v2']['year']['0']) ? $t['tags']['id3v2']['year']['0'] : '';
$genre = !empty($t['tags']['id3v2']['genre']['0']) ? $t['tags']['id3v2']['genre']['0'] : '';
$url = Storage::url($tracksPath . $fileHash . '.mp3');
if(!empty($track->getArtwork(true))) {
$tmpCoverFile = $track->getArtwork(true)->getPathname();
$coverPath = 'public/tracks/covers/';
$cover64Path = 'cover.jpg';
Storage::disk('local')->put($coverPath . '/' . $fileHash . '/' . $cover64Path, File::get($tmpCoverFile));
$cover = Storage::url($coverPath . $fileHash . '/' . $cover64Path);
} else {
$cover = '/vendor/songs-crud/images/none.png';
}
DB::table('songs_tracks')->updateOrInsert(
['hash' => $fileHash],
[
'release_id' => $request->id,
'image' => $cover,
'name' => $title,
'artist' => $artist,
'band' => $band,
'album' => $album,
'year' => $year,
'genre' => $genre,
'url' => $url,
'hash' => $fileHash,
'sortable' => '',
'slug' => $fileHash
]
);
$getTrackId = DB::table('songs_tracks')
->where('hash', $fileHash)
->first();
$id = !empty($getTrackId->id) ? $getTrackId->id : 1;
return $id;
}
The function works fine, media files are uploaded to the server and records are added to the database table. I need to pass the id to another function that generates a JSON file:
public function getTrackListJson(Request $request): \Illuminate\Http\JsonResponse
{
dd($this->upload());
$tracks = DB::table('songs_tracks')->where('id', $id)->first();
return response()->json([$tracks]);
}
I'm trying to print this function via dd(), but it gives the following error:
ArgumentCountError
Too few arguments to function SequelONE\SongsCRUD\app\Http\Controllers\Admin\TrackCrudController::upload(), 0 passed in /home/site.com/packages/sequelone/songs-crud/src/app/Http/Controllers/Admin/TrackCrudController.php on line 229 and exactly 1 expected
I can't figure out how to pass an instance of $request and do I need to pass it at all? Can anyone help with this?
When you call a function that requires parameter, or uses injection like the Laravel Request, then you need to pass it in when you call the function manually. Since you're already injecting Request $request on your getTrackListJson call, you can just pass that along.
dd($this->upload($request));
That might help
public function getTrackListJson(Request $request): \Illuminate\Http\JsonResponse
{
$id = $this->upload($request);
$tracks = DB::table('songs_tracks')->where('id', $id)->first();
return response()->json([$tracks]);
}

Running PHP API call without Page Reloading

I have a multistep form (HTML / JS / PHP) and the form data gets sent to a backend after submitting, which results in a page reload.
Is it possible to pass the data live to the backend when the user gets to a new page of the form (clicks on the next button)?
<?php
require_once dirname(__FILE__) . '/MailWizzApi/Autoloader.php';
MailWizzApi_Autoloader::register();
// configuration object
$config = new MailWizzApi_Config(array(
'apiUrl' => 'http://email.mddasd.de/api/index.php',
'publicKey' => 'SAMPLEKEY',
'privateKey' => 'SAMPLEKEY',
// components
'components' => array(
'cache' => array(
'class' => 'MailWizzApi_Cache_File',
'filesPath' => dirname(__FILE__) . '/MailWizzApi/Cache/data/cache', // make sure it is writable by webserver
)
),
));
// now inject the configuration and we are ready to make api calls
MailWizzApi_Base::setConfig($config);
// start UTC
date_default_timezone_set('UTC');
$email = $_POST ['email'];
$name = $_POST['name'];
$phone = $_POST['telephone'];
if (isset($_POST['branch_0_answers']) && $_POST['branch_0_answers'] != "")
{
foreach($_POST['branch_0_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$grundflaeche .= $_POST['grundflaeche-grundstueck'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_1_answers']) && $_POST['branch_1_answers'] != "")
{
foreach($_POST['branch_1_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$wohnflaeche .= $_POST['wohnflaeche-haus'] . "\n";
$grundflaeche .= $_POST['grundflaeche-haus'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_2_answers']) && $_POST['branch_2_answers'] != "")
{
foreach($_POST['branch_2_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$wohnflaeche .= $_POST['wohnflaeche-wohnung'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_3_answers']) && $_POST['branch_3_answers'] != "")
{
foreach($_POST['branch_3_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$gewerbeflaeche .= $_POST['gewerbeflaeche'] . "\n";
$grundflaeche .= $_POST['grundflaeche-gewerbe'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
foreach($_POST['branch_1_1_answers'] as $value)
{
$stand.= trim(stripslashes($value)) . "\n";
};
$endpoint = new MailWizzApi_Endpoint_ListSubscribers();
$response = $endpoint->create('ma503j6m97b75', array(
'EMAIL' => $email,
'TELEFON' => $phone,
'NAME' => $name,
'ART' => $art,
'GEWERBEFLAECHE' => $gewerbeflaeche,
'WOHNFLAECHE' => $wohnflaeche,
'GRUNDFLAECHE' => $grundflaeche,
'BAUJAHR' => $baujahr,
'PLZ' => $plz,
'STAND' => $stand
));
?>
The .php gets executed with the final submit button.
Thanks for your answers.

How can I email myself the RAW SQL query that this php function is producing?

I want to run explain on a query that is slow but I don't know how to view the raw sql so I can run it in phpmyadmin and debug it. Here is the function.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->limit = $limit;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}
Anybody know how I can see the SQL query only that is produced by this function? email is better than echo as I want to grab query from live site.
You could var_dump($table) and write the result in an email using the native php mail function or write it in a log file (this option is better).
Is that framework open-source? Because I couldn't find any documentation about the class \IPS\Helpers\Table\Db. Probably there's a method in it to build the query, you could look for it at that class source code and put the result of that method into the email message or log file instead of var_dump the table.

eBay API SKU missing from response

I am trying to download all my listings from ebay into my database using following code:
$client = new eBaySOAP($session);
$ebay_items_array = array();
try {
$client = new eBaySOAP($session);
$params = array(
'Version' => $Version,
'GranularityLevel' => "Fine",
'OutputSelector' => "ItemID,SKU,Title",
'EndTimeFrom' => date("c", mktime(date("H"), date("i")+10, date("s"), date("n"), date("j"), date("Y"))),
'EndTimeTo' => date("c", mktime(date("H"), date("i"), date("s"), date("n"), date("j")+120, date("Y"))),
'Pagination' => array(
'PageNumber' => $_GET['linkebaynum'],
'EntriesPerPage' => "20"
)
);
$results = $client->GetSellerList($params);
if($results->Ack == "Success")
{
$c = 0;
if(is_array($results->ItemArray->Item))
{
foreach($results->ItemArray->Item as $key => $value)
{
array_push($ebay_items_array, $value->ItemID);
$Qcheck = tep_db_query('select ebay_productstoitems_items_id from ' . TABLE_EBAY_PRODUCTS_TO_ITEMS . ' where ebay_productstoitems_items_id = ' . $value->ItemID);
$check = tep_db_fetch_array($Qcheck);
if($check == 0) {
if($check['ebay_productstoitems_items_id'] = $value->ItemID) {
echo 'Not in Database - Inserting ' . $value->ItemID . '<br>';
tep_db_query("insert ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}else{
echo 'Found - ' . $value->ItemID . ' Nothing to Change<br>';
tep_db_query("update ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "' where ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}
$c++;
}
}
} catch (SOAPFault $f) {
print "error<br>";
}
print "Request:<br>".ebay_formatxmlstring($client->__getLastRequest())."<br><br>";
print "Response:<br>".ebay_formatxmlstring($client->__getLastResponse())."<br><br>";
But it will not recover the SKU (or CustomLabel).
Can anyone explain what I am missing to get the SKU into the database along with the ItemID.
Or would I have to recover lists of ItemID and then do a second call to recover the SKU or CustomLabel?
Found out what the problem was the Sandbox does not appear to pass the SKU back. I switched to the live site and hey presto the SKU is being retrieved along with the Itemid.

this json code is displaying no result

I am returning a json array and trying to receive it in controller but it displaying no results
Here is my model:
if ((!empty($_FILES["FlMediaImage"])) &&($_FILES["FlMediaImage"]["error"] == 0)) {
$mdImgName = $_FILES["FlMediaImage"]["name"];
$ext = substr($mdImgName, strpos($mdImgName, '.') + 1);
$mdImgName = 'adsmind_media_' . md5(uniqid(time(), true)) . '.' . $ext;
move_uploaded_file($_FILES["FlMediaImage"]["tmp_name"], ROOT . "/images/temp/" . $mdImgName);
}
$jsonArry = array(
"image_id" => 0,
"image_name" => $result->$mdImgName
);
return json_encode(array('result' => $jsonArry));
My controller is:
$imageJSON = json_decode($modObj->saveMediaImage());
$imageID = $imageJSON->result->image_id;
$imageName = $imageJSON->result->image_name;
its working
$arr= json_decode( '{"result":{"image_id":0,"image_name":null}}',FALSE);
echo $arr->result->image_id;
Can you try with it
$imageJSON = json_decode($modObj->saveMediaImage());
$imageID = $imageJSON->result->image_id;
$imageName = (isset($imageJSON->result->image_name) && !empty($imageJSON->result->image_name))?$imageJSON->result->image_name:'';
Your result is null in both vars.. $imageID and $imageName...
Change some values, like
$jsonArry = array("image_id" => '0', "image_name" => 'some_name');
and you will see result.

Categories