Refactoring smartrecruiter api - php

I'm currently implementing smartrecruiter api in my project. I'm using two endpoints namely /jobs-list and /job-details. The problem is that every time I'm extracting the details in the second endpoint which is the /job-details, the execution time is so slow.
Here's what I've done so far:
function getContext()
{
$opts = array(
'http'=> array(
'method' => 'GET',
'header' => 'X-SmartToken: xxxxxxxxxxxxxxxxx'
)
);
return $context = stream_context_create($opts);
}
function getSmartRecruitmentJob($city, $department)
{
$tmp = array();
$results= array();
$limit = 100; //max limit for smartrecruiter api is 100
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs?limit='.$limit.'&city='.$city.'&department='.$department, false, $this->getContext());
$lists= json_decode($file, true);
foreach($lists['content'] as $key => $list)
{
if ($list['status'] == 'SOURCING' || $list['status'] == 'INTERVIEW' || $list['status'] == 'OFFER')
{
$results['id'] = $list['id'];
$tmp[] = $this->getSmartRecruitmentJobDetails($results['id']);
}
}
return $tmp;
}
function getSmartRecruitmentJobDetails($id)
{
$results = array();
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}

Solved it by caching the function for extracting the data:
function getCache()
{
if ($this->cache === null)
{
$cache = \Zend\Cache\StorageFactory::factory(
array(
'adapter' => array(
'name' => 'filesystem',
'options' => array(
'ttl' => 3600 * 7, // 7 hours
'namespace' => 'some-namespace',
'cache_dir' => 'your/cache/directory'
),
),
'plugins' => array(
'clear_expired_by_factor' => array('clearing_factor' => 10),
),
)
);
$this->cache = $cache;
}
return $this->cache;
}
function getSmartRecruitmentJobDetails($id)
{
$cache = $this->getCache();
$key = md5('https://api.smartrecruiters.com/jobs/'.$id);
$lists = unserialize($cache->getItem($key, $success));
$results = array();
if($success && $lists)
{
header('Debug-cache-recruit: true');
}
else
{
header('Debug-cache-recruit: false');
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$cache->addItem($key, serialize($lists));
}
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country'] = isset($lists['location']['country']) ? $lists['location']['country'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}

Related

Problem of Curly Brackets in my controller Php Symfony

I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.

Insert limit in local WAMP or XAMPP server

I'm trying to import an excel file with 15,000 record in a local php and mysql system, but it's always stop inserting in after 3000 records and ignoring the rest of records.
Even in the hosted copy of the system it's insert only 3027 record.
Can I get some help please?
Import csv php script
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile'])) {
$this->load->library('upload');
$config['upload_path'] = $this->digital_upload_path;
$config['allowed_types'] = 'csv';
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = true;
$config['encrypt_name'] = true;
$config['max_filename'] = 25;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
admin_redirect('products/import_csv');
}
$csv = $this->upload->file_name;
$arrResult = [];
$handle = fopen($this->digital_upload_path . $csv, 'r');
if ($handle) {
while (($row = fgetcsv($handle, 15000, ',')) !== false) {
$arrResult[] = $row;
}
fclose($handle);
}
$titles = array_shift($arrResult);
$updated = 0;
$items = [];
foreach ($arrResult as $key => $value) {
$supplier_name = isset($value[24]) ? trim($value[24]) : '';
$supplier = $supplier_name ? $this->products_model->getSupplierByName($supplier_name) : false;
$item = [
'name' => isset($value[0]) ? trim($value[0]) : '',
'code' => isset($value[1]) ? trim($value[1]) : '',
'barcode_symbology' => isset($value[2]) ? mb_strtolower(trim($value[2]), 'UTF-8') : '',
'brand' => isset($value[3]) ? trim($value[3]) : '',
'category_code' => isset($value[4]) ? trim($value[4]) : '',
'unit' => isset($value[5]) ? trim($value[5]) : '',
'sale_unit' => isset($value[6]) ? trim($value[6]) : '',
'purchase_unit' => isset($value[7]) ? trim($value[7]) : '',
'cost' => isset($value[8]) ? trim($value[8]) : '',
'price' => isset($value[9]) ? trim($value[9]) : '',
'alert_quantity' => isset($value[10]) ? trim($value[10]) : '',
'tax_rate' => isset($value[11]) ? trim($value[11]) : '',
'tax_method' => isset($value[12]) ? (trim($value[12]) == 'exclusive' ? 1 : 0) : '',
'image' => isset($value[13]) ? trim($value[13]) : '',
'subcategory_code' => isset($value[14]) ? trim($value[14]) : '',
'variants' => isset($value[15]) ? trim($value[15]) : '',
'cf1' => isset($value[16]) ? trim($value[16]) : '',
'cf2' => isset($value[17]) ? trim($value[17]) : '',
'cf3' => isset($value[18]) ? trim($value[18]) : '',
'cf4' => isset($value[19]) ? trim($value[19]) : '',
'cf5' => isset($value[20]) ? trim($value[20]) : '',
'cf6' => isset($value[21]) ? trim($value[21]) : '',
'hsn_code' => isset($value[22]) ? trim($value[22]) : '',
'second_name' => isset($value[23]) ? trim($value[23]) : '',
'supplier1' => $supplier ? $supplier->id : null,
'supplier1_part_no' => isset($value[25]) ? trim($value[25]) : '',
'supplier1price' => isset($value[26]) ? trim($value[26]) : '',
'slug' => $this->sma->slug($value[0]),
];
if ($catd = $this->products_model->getCategoryByCode($item['category_code'])) {
$tax_details = $this->products_model->getTaxRateByName($item['tax_rate']);
$prsubcat = $this->products_model->getCategoryByCode($item['subcategory_code']);
$brand = $this->products_model->getBrandByName($item['brand']);
$unit = $this->products_model->getUnitByCode($item['unit']);
$base_unit = $unit ? $unit->id : null;
$sale_unit = $base_unit;
$purcahse_unit = $base_unit;
if ($base_unit) {
$units = $this->site->getUnitsByBUID($base_unit);
foreach ($units as $u) {
if ($u->code == $item['sale_unit']) {
$sale_unit = $u->id;
}
if ($u->code == $item['purchase_unit']) {
$purcahse_unit = $u->id;
}
}
} else {
$this->session->set_flashdata('error', lang('check_unit') . ' (' . $item['unit'] . '). ' . lang('unit_code_x_exist') . ' ' . lang('line_no') . ' ' . ($key + 1));
admin_redirect('products/import_csv');
}
unset($item['category_code'], $item['subcategory_code']);
$item['unit'] = $base_unit;
$item['sale_unit'] = $sale_unit;
$item['category_id'] = $catd->id;
$item['purchase_unit'] = $purcahse_unit;
$item['brand'] = $brand ? $brand->id : null;
$item['tax_rate'] = $tax_details ? $tax_details->id : null;
$item['subcategory_id'] = $prsubcat ? $prsubcat->id : null;
if ($product = $this->products_model->getProductByCode($item['code'])) {
if ($product->type == 'standard') {
if ($item['variants']) {
$vs = explode('|', $item['variants']);
foreach ($vs as $v) {
if (!empty(trim($v))) {
$variants[] = ['product_id' => $product->id, 'name' => trim($v)];
}
}
}
unset($item['variants']);
if ($this->products_model->updateProduct($product->id, $item, null, null, null, null, $variants)) {
$updated++;
}
}
$item = false;
}
} else {
$this->session->set_flashdata('error', lang('check_category_code') . ' (' . $item['category_code'] . '). ' . lang('category_code_x_exist') . ' ' . lang('line_no') . ' ' . ($key + 1));
admin_redirect('products/import_csv');
}
if ($item) {
$items[] = $item;
}
}
}
// $this->sma->print_arrays($items);
}
Insert script
public function add_products($products = [])
{
if (!empty($products)) {
foreach ($products as $product) {
$variants = explode('|', $product['variants']);
unset($product['variants']);
if ($this->db->insert('products', $product)) {
$product_id = $this->db->insert_id();
foreach ($variants as $variant) {
if ($variant && trim($variant) != '') {
$vat = ['product_id' => $product_id, 'name' => trim($variant)];
$this->db->insert('product_variants', $vat);
}
}
}
}
return true;
}
return false;
}
I think you're using codeigniter, so i recommend you to use yield (generator in php) and insert_bulk to handle some big data or some huge records to optimize your code and keep your cpu/memory not to leaks or timeout.
Here's some logic :
Import your csv and store it in generator.
Process your titles, key values from csv in one process,DO NOT store it in array variable except your titles only.
Convert the generator to array, and do your another process.
Do your logic to insert the data and Store your inserted data to generator.
Convert the generator to array and insert it using insert_batch function from codeigniter.
Actually you can combine poin 4 to the poin 2 so you have one process do all the logic and the result is the data you want to insert to the database.
Here's my simple code how you implement the logic :
<?php
// I think you're using codeigniter as your framework here, so i recommend you using yield and insert_bulk to insert the data
$filename = "testdata.csv";
$titles = [];
$readcsv = function($filename)use(&$titles){
$keys = ['name','code','barcode_symbology','brand','category_code','unit','sale_unit','purchase_unit','cost','price','alert_quantity','tax_rate','tax_method','image','subcategory_code','variants','cf1','cf2','cf3','cf4','cf5','cf6','hsn_code','second_name','supplier1','supplier1_part_no','supplier1price','slug'];
$handle = fopen($filename,"r");
$first = true;
while (($data = fgetcsv($handle, 15000, ",")) !== FALSE) {
if($first){
$titles = $data;
$first = false;
}else{
if(count($keys) == count($data)){
yield array_combine($keys,$data);
}
}
}
fclose($handle);
};
// Your csv data will be in this variable and your $titles now have value
$yourdata = iterator_to_array($readcsv($filename));
// This function store your inserted data to the yield (generator in php) if the conditions true
$list_insert_data = function($yourdata){
// Loop your csv data and do your logic here...
$break = false;
$cnt = 1;
foreach($yourdata as $v){
if(!empty($v) && !$break){
yield $v;
}
// Just simple logic to store 3 records from the csv
if($cnt == 3){
$break = true;
}else if($break){
break;
}
$cnt++;
}
};
// This variable contains 3 array from the csv data
$inserted = iterator_to_array($list_insert_data($yourdata));
// Then insert the data to the database.
$this->db->insert_batch('product_variants', $inserted);
UPDATED:
If you're using mysql, you need to check your max_allowed_packet and check it in your mysql SHOW VARIABLES WHERE Variable_name LIKE '%max_allowed_packet%' and increase or double the value.
Change in the my.ini file by including the single line under [mysqld] or [client] section in your file:
max_allowed_packet=1024M
then restart the MySQL service and you are done. Hope this simple logic help you out of trouble.
You need to change the max_execution_time on php.ini
max_execution_time = 5000
Or on top of your script, add the following line.
ini_set('max_execution_time', 5000);

How to execute a specific php script method giving parameters from url

I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.

how can set counter limit?

Hi i have a counter code. I want to stop when (example) 11 result. how can i stop curl when script count 11 result?
<?php
class instaAuth
{
public function _userlistesi() {
$klasor = opendir("cookieboq/");
while(false !== ($veriler = readdir($klasor))) {
if(strstr($veriler,'selco')) {
$bir_veri = str_replace('.selco','',$veriler);
$user_ekle .= "$bir_veri,";
}
}
$userler = substr($user_ekle,0,-1);
$users_arr = explode(",",$userler);
return $users_arr;
}
public function _authLike($_ID,$userlist, $DELETE = NULL)
{
if ( !empty($userlist) )
{
$type = ($DELETE == TRUE) ? 'unlike' : 'like';
$members = array();
$params = array();
foreach ( $userlist as $username )
{
$_cookie = $this->_cookieFolder . $username . $this->_cookieExtension;
$randomProxy = ( count($this->_proxy) > 0 ) ? $this->_proxy[rand(0, (count($this->_proxy) - 1))] : NULL;
if ( !file_exists($_cookie) )
{
continue;
}
$members[] = $username;
$fake_ip = $this->fakeIP();
$header = array(
"Accept: */*",
"Accept-Language: tr;q=1",
"HTTP_CLIENT_IP" => $fake_ip,
"HTTP_FORWARDED" => $fake_ip,
"HTTP_PRAGMA" => $fake_ip,
"HTTP_XONNECTION" => $fake_ip,);
$options = array(
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $this->signed(json_encode(array())),
CURLOPT_HTTPHEADER => $header,
CURLOPT_COOKIEJAR => $_cookie,
CURLOPT_COOKIEFILE => $_cookie,
CURLOPT_USERAGENT => $this->_useragent,
);
$params[] = array(
'url' => "https://i.instagram.com/api/v1/media/{$_ID}/{$type}/",
'options' => $options
);
}
} else {
throw new Exception('Error: _authLike() - Beğeni yaptırabilmeniz için {cookies} tanımlamalısınız.');
}
$multiCURL = new \RollingCurl\RollingCurl();
foreach ($params as $param) {
$request = new \RollingCurl\Request($param['url'], 'POST');
$request->setOptions($param['options']);
$multiCURL->add($request);
}
$this->_result = 0;
$multiCURL
->setCallback(function(\RollingCurl\Request $request, \RollingCurl\RollingCurl $rollingCurl) {
$result = $request->getResponseText();
if ( is_string($result) )
{
$result = json_decode($result);
if ( is_object($result) )
{
if ($result->status == 'ok') $this->_result++;
}
}
})
->setSimultaneousLimit(100)
->execute()
;
$result = array(
'success' => $this->_result,
'errors' => NULL
);
return json_decode(json_encode($result));
}
}
and this insterested other code page
<form action="" method="POST">
Pictures ID : <input type="text" name="apifotoId">
<br>
Limits : <input type="text" name="limit">
<br>
<input type="submit" value="Like Send">
</form>
<?php
include("class.php")
if(isset($_POST['apifotoId'])) {
$start = time();
$y = new instaAuth();
$user_list = $y->_userlistesi();
$limit = $_POST["limit"];
$_ID = $_POST['apifotoId'];
$y->_authLike($_ID,$user_list);
$fark = round(time()-$start)/60;
echo "Likes Complete (".$fark." dk.)";
}
?>
I want to stop when (example) 11 result. how can i stop curl when script count 11 result?
you can make an if statement only in function "authLike" condition if(result ==11) break;
and you if you clear your answer to help you more .

SOAP web service not returning any value

This is my code :
require_once('library/nusoap/nusoap.php');
$NAMESPACE = 'http://domain.com/';
$server = new nusoap_server();
$server->configureWSDL('cm', $NAMESPACE, 'http://domain.com/webservice.php');
$server->wsdl->addComplexType(
'Contacts',
'complexType',
'struct',
'all',
'',
array(
'contact_pid' => array('name'=>'contact_pid','type'=>'xsd:int'),
'contact_pfname' => array('name'=>'contact_pfname','type'=>'xsd:string'),
'contact_plname' => array('name'=>'contact_plname','type'=>'xsd:string')
)
);
$server->wsdl->addComplexType(
'ContactsArray',
'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(
array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:Contacts[]')
),
'tns:Contacts'
);
$server->register(
'fetchAllContacts',
array('auth_user'=>'xsd:string','auth_pass'=>'xsd:string'),
array('return'=>'tns:ContactsArray'),
$NAMESPACE);
function fetchAllContacts($auth_user,$auth_pass)
{
$authenticate_query = "select * from users_master where user_email='".$auth_user."' and user_password='".md5($auth_pass)."' and user_status='1'";
$authenticate_user = mysql_query($authenticate_query) or die(mysql_error());
if(mysql_num_rows($authenticate_user) > 0)
{
$row_data = mysql_fetch_array($authenticate_user);
$select_all_contacts = mysql_query("select * from contacts_master where contact_userid='".$row_data['user_pid']."'") or die(mysql_error());
if(mysql_num_rows($select_all_contacts) > 0)
{
$contact_loop = 0;
while($row_contacts = mysql_fetch_array($select_all_contacts))
{
$contact_array[]['contact_pid'] = $row_contacts['contact_pid'];
$contact_array[]['contact_pfname'] = $row_contacts['contact_pfname'];
$contact_array[]['contact_plname'] = $row_contacts['contact_plname'];
$contact_loop++;
}
return $contact_array;
}
else
{
return array("error" => "No records found!");
}
}
else
{
return array("error" => "Error in authentication!");
}
}
if (!isset($HTTP_RAW_POST_DATA)){
$HTTP_RAW_POST_DATA = file_get_contents('php://input');
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
The problem i am having is that it is not returning anything.
When setting the array-values you arn't using the index.
Changing this:
$contact_array[]['contact_pid'] = $row_contacts['contact_pid'];
$contact_array[]['contact_pfname'] = $row_contacts['contact_pfname'];
$contact_array[]['contact_plname'] = $row_contacts['contact_plname'];
into:
$contact_array[$contact_loop]['contact_pid'] = $row_contacts['contact_pid'];
$contact_array[$contact_loop]['contact_pfname'] = $row_contacts['contact_pfname'];
$contact_array[$contact_loop]['contact_plname'] = $row_contacts['contact_plname'];
should do the trick.

Categories