Update query for API in codeigniter is not working - php

i want to write a API for updating data in sql. I am using CI for it.I am new to this field.while i have written it is not working in localhost itself .Can anyone help me? I am attaching my controller and model here.it is showing an error like this page is not working
function editprofile($id,$data) {
$this->db->where(array('user_id' => $id));
$this->db->update('registrationdetails', $data);
if(!empty($id))
{
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$adminId = 1;
$AUTHENTIC_KEY = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$user_id=2;
$firstname ="aiswarya";
$lastname ="mathew";
$email ="aiswarya#gmail.com";
$password ="aiswarya";
$confirmpassword ="aiswarya";
$contactnumber ="999999999";
$gender ="female";
$address ="canada";
$department ="cse";
$designation ="swe";
$Admindetails = $this->common->CheckValidAdmin($adminId,$AUTHENTIC_KEY);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id
);
$data = array();
$data = array('firstname'=>$firstname,'lastname'=>$lastname,'email'=>$email,'password'=>$password,'confirmpassword'=>$confirmpassword,'contactnumber'=>$contactnumber,'gender'=>$gender,'address'=>$address,'department'=>$department,'designation'=>$designation);
$status = $this->user->editprofile($user_id,$data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}

function editprofile($data) {
if(!empty($data['user_id']))
{
$this->db->where(array('user_id' => $data['user_id']));
$this->db->update('registrationdetails', $data);
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$data['adminId'] = 1;
$data['AUTHENTIC_KEY'] = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$data['user_id']=2;
$data['firstname'] ="aiswarya";
$data['lastname'] ="mathew";
$data['email'] ="aiswarya#gmail.com";
$data['password'] ="aiswarya";
$data['confirmpassword'] ="aiswarya";
$data['contactnumber'] ="999999999";
$data['gender'] ="female";
$data['address'] ="canada";
$data['department'] ="cse";
$data['designation'] ="swe";
$Admindetails = $this->common->CheckValidAdmin($data['adminId'],$data['AUTHENTIC_KEY']);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id);
$status = $this->user->editprofile($data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}

Related

Getting Discord Authentication Error in Laravel

Client error: POST https://discordapp.com/api/oauth2/token resulted in a 429 Too Many Requests response: {"code": 0, "message": "You are being blocked from accessing our API temporarily due to exceeding our rate limits freque (truncated...)
I am getting this error when i am trying to login into my web apllication using discord,I know i am exceeding rate limits i want to increase my rate limit,after sometime it has started working again but i do not want this error again cause i have live customer on my site
<?php
namespace App\Http\Controllers\Auth;
include base_path('vendor/autoload.php');
use RestCord\DiscordClient;
use App\Http\Controllers\Controller;
use App\Models\User;
use Laravel\Socialite\Facades\Socialite;
use App\Notifications\SendCredentials;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class DiscordLoginController extends Controller
{
public function login(){
return Socialite::with('discord')->scopes(['guilds','guilds.join'])->redirect(); //redirect to generated 0auth link
}
public function callback(){
function getTotalMembers($last_id, $membrs_total)
{
$discord = new DiscordClient(['token' => getenv('DISCORD_BOT_TOKEN')]);
if ($last_id == 0) {
$members = $discord->guild->listGuildMembers(['guild.id' => 815031226699874334, 'limit' => 1000]);
} else {
$members = $discord->guild->listGuildMembers(['guild.id' => 815031226699874334, 'limit' => 1000, 'after' => $last_id]);
}
$end = end($members);
$last_id = $end->user->id;
$membrs_total = array_merge($membrs_total, $members);
if (count($members) <= 999) {
return $membrs_total;
} else {
return getTotalMembers($last_id, $membrs_total);
}
}
$membrs_total = array();
$membrs_totals = getTotalMembers(0, $membrs_total);
$current_guilds_ids=array();
foreach($membrs_totals as $member){
array_push($current_guilds_ids,$member->user->id);
}
$user = Socialite::driver('discord')->stateless()->user();
if(in_array($user->id,$current_guilds_ids))
{
$accessTokenResponseBody = $user->accessTokenResponseBody;
if (!Auth::user()) { //handle user login
$users = User::where(['discord_id' => $user->id])->first();
if ($users) {
if(in_array($users->discord_id,$current_guilds_ids)){
User::where(['id' => $users->id])->update([ 'is_binded' => true,'is_verified'=>true]);
}
Auth::login($users);
return redirect()->route('home');
} else {
$users = User::where('email', $user->email)->first();
if (!$users) {
$users = new User();
$users->name = $user->name;
$users->email = $user->email;
$password = uniqid();
$users->password = Hash::make($password);
$users->discord_id = $user->id;
$users->discord_email = $user->email;
$users->is_binded = 1;
if ($user->user['verified'] == 1) {
$users->is_verified = 1;
}
$users->save();
$notifyUsers = User::where('email', $users->email)->get();
foreach ($notifyUsers as $notifyUser) {
$notifyUser->notify(new SendCredentials($notifyUser, $password));
}
Auth::login($users);
return redirect()->route('home');
}
}
} else {
$user_id = auth()->user()->id;
$users = User::where(['discord_id' => $user->id])->count();
if ($users == 0) {
User::where(['id' => $user_id])->update(['discord_id' => $user->id, 'discord_email' => $user->email, 'is_binded' => true]);
return redirect()->route('home');
} else {
User::where(['id' => $user_id])->update(['discord_id' => $user->id, 'discord_email' => $user->email, 'is_verified' => false]);
$customer_status = User::where(['id' => $user_id])->value('is_customer');
$client = new \GuzzleHttp\Client();
$request = $client->get( //perform check
'https://discordapp.com/api/users/#me/guilds',
[
'headers' => [
'Authorization' => 'Bearer ' . $accessTokenResponseBody['access_token'],
],
]
);
$response = json_decode($request->getBody()->getContents(), true); //decode response
foreach ($response as $key => $value) { //traverse result
if ($value['id'] == 815031226699874334) {
User::where(['id' => $user_id])->update(['is_verified' => true]);
alert()->success('Nice One', 'You are in SMT Proxies Discord.');
if ($customer_status == true) {
$client = new Client([
'headers' => [
'Authorization' => 'Bot ' . getenv('DISCORD_BOT_TOKEN'),
"Content-Type" => "application/json"
]
]);
$client->put('https://discordapp.com/api/guilds/815031226699874334/members/' . $user->id . '/roles/815046198791503914', []);
alert()->success('Nice One', 'You are in SMT Proxies Discord & got customer role');
}
break;
}
}
return redirect()->route('home');
}
}
}
else{
alert()->warning('Sorry You have to join our server first');
return redirect()->route('login');
}
}
}

Error in save() after an function in Laravel

I am trying to implement the save() method after the self::restrictionMinimunBid($ request, $ karateka, $ bid) function, but I get the following error: "Method App\\Http\\Controllers\\BidController::save does not exist."
Here is my code:
$bid = Bid::where('id_participants', '=', $request->id_participant)
->where('id_karatekas', '=',$market->id_karatekas)
->where('bid', '=',$request->bid);
if(!$bid->count()){
$bid->id_market = $market->id;
$bid->id_group = $market->id_group;
$bid->id_karatekas = $market->id_karatekas;
$bid->id_participants = $request->id_participant;
self::restrictionMinimunBid($request, $karateka, $bid);
$bid->save();
$response = array('code' => 200, 'Bid' => $bid, 'msg' => 'Bid created');
}else{
$response = array('code' => 400, 'error_msg' => "Bid already registered.");
}
public function restrictionMinimunBid(Request & $request, $karateka, & $bid)
{
$allKaratekas = Karateka::all()
->map(function ($allKaratekas) use ($karateka, $request, $bid){
if($karateka->id == $allKaratekas->id ){
if($request->bid > $allKaratekas->value){
$bid->bid = $request->bid;
$msg ="The bid is more than the value of karateka";
var_dump($msg);
}
else{
$error ="The bid is less than the value ofmkarateka";
var_dump($error);
}
}
});
}
You can replace this one:
$bid = Bid::where('id_participants', '=', $request->id_participant)
->where('id_karatekas', '=',$market->id_karatekas)
->where('bid', '=',$request->bid);
To this:
$bid = Bid::where('id_participants', '=', $request->id_participant)
->where('id_karatekas', '=',$market->id_karatekas)
->where('bid', '=',$request->bid)->first();

Yii No data received in post method only on server

Created an API endpoint I which I am submitted data as the body in postman, but it is always empty on the server whereas it works fine on localhost.
Please look at the request
The same request works on localhost but not online. Here is code on the server side I am using Yii::$app->request->post() to dump the data, here is the full code of that endpoint. I had tried $_POST,$_REQUEST every request is empty on the server,
public function actionSocialcheck()
{
$data = [];
$model = new User();
var_dump(Yii::$app->request->post());
if ($model->load(Yii::$app->request->post(),'')) {
$social = User::findBySocialLogin($model->socialLogin);
if (empty($social)) {
$data['status'] = self::API_OK;
$data['check'] = false;
} else {
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
// $usercl=new User();
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
} else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}
When I try the same request on the local server it works fine here is the output of that
Can you please help me out in this case. Thanks
public function actionSocialcheck(){
if(Yii::$app->request->isPost){
$data = [];
$social = User::findBySocialLogin(Yii::$app->request->post('socialLogin'));
if (empty($social)){
$data['status'] = self::API_OK;
$data['check'] = false;
}else{
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
}else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}

Error:Dropbox Upload Function

Fatal Error: call to a member function uploadFile() on a non-object
Getting this error of upload file function on Uploading File to dropbox using PHP API On live Server. Same Code Working fine on localhost and doing it in codeigniter. start of code is**
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);
require_once(APPPATH . 'libraries/dropbox/vendor/autoload.php');
use \Dropbox as dbx;
class Knowledge extends CI_Controller
{
public $appInfoFile;
public $requestPath; **
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the models
$this->load->model('knowledge_model');
//$this->load->helper('messages');
//$this->load->model('messages_model');
$this->load->model('messages_model', 'send_messages');
// custom library in codeigniter
$this->appInfoFile = APPPATH.'libraries/dropbox/app-info.json';
$redirect_uri ='https://www.domainname.com/knowledge/add/';
$requestPath = $this->init();
session_start();
validate_user();
}
public function index($msg = NULL)
{
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['records'] = $this->knowledge_model->get_all_rec();
// echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function tag($msg = NULL)
{
$tagname = $this->uri->segment("3");
$tagnamehits = $this->uri->segment("4");
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['update_rec'] = $this->knowledge_model->update_hits($tagnamehits);
$data['records'] = $this->knowledge_model->get_notifyrec_bytags($tagname);
//echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function add()
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$seralizedtags = serialize($this->input->post('tagsar'));
//echo "<pre>".print_r($seralizedArray,true)."</pre>";exit;
// drop box upload filess
if (isset($_FILES['attached_file']['name']) && !empty($_FILES['attached_file']['name'])) {
$file_name= $_FILES['attached_file']['name'];
$return_result=$this->upload_to_dropbox($file_name);
$rev=$return_result['rev'];
$mime_type=$return_result['mime_type'];
$path=$return_result['path'];
$size=$return_result['size'];
$revision=$return_result['revision'];
}
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'user_id' => $user_id,
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description'),
'dropbox_rev'=>$rev,
'dropbox_mim_type'=>$mime_type,
'dropbox_path'=>$path,
'dropbox_filesize'=>$size,
'dropbox_revision'=>$revision,
);
$message=$this->input->post('subject');
//for slack call
if(isset($message)){
$message=$message;
$messageType = "Knowledge_center";
$this->send_messages->send_message_on_slack($messageType);
}
//echo "<pre>" . print_r($data, true) . "</pre>";
$insert_res = $this->knowledge_model->insert_rec($data);
if ($insert_res != "conf") {
if ($insert_res == "subject") {
$this->session->set_flashdata('message', "<p>Subject Name already exist.Please change Subject</p>");
} else {
$this->session->set_flashdata('message', "<p>Error in Insertion.</p>");
}
echo '<script>window.location.href = "' . base_url() . 'knowledge/add";</script>';
} else {
$this->session->set_flashdata('message', "<p>Record added successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $this->form_validation->set_value('subject'),
);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $this->form_validation->set_value('tagsar'),
);
$data['desc'] = $this->form_validation->set_value('description');
// $data['dropbox']=$this->dropbox->dp();
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('add_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function view($id)
{
$update_rec = $this->knowledge_model->get_rec_byid($id);
$data['dropbox_detail']=array(
"dropbox_rev"=> $update_rec[0]->dropbox_rev,
"dropbox_mim_type"=> $update_rec[0]->dropbox_mim_type,
"dropbox_path"=> $update_rec[0]->dropbox_path,
"dropbox_filesize"=> $update_rec[0]->dropbox_filesize,
"dropbox_revision"=> $update_rec[0]->dropbox_revision,
);
$data['subject_data'] = $update_rec[0]->subject;
$data['tags_data'] = unserialize($update_rec[0]->tags);
$data['desc'] = $update_rec[0]->description;
$data['title'] = 'Knowledge Center';
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('view_knowledge', $this->data);
$this->load->view('includes/footer');
}
public function manage_notify()
{
$notifyid = $_POST["elid"];
$notifytext = $_POST["notifytext"];
$notify_rec = $this->knowledge_model->get_notifyrec_byid($notifytext);
$ret_res = "<ul>";
foreach ($notify_rec as $notify_record) {
$ret_res .= "<li>" . $notify_record->subject . "</li>";
}
$ret_res .= "</ul>";
echo $ret_res;
exit;
}
public function update($id)
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$update_rec = $this->knowledge_model->get_rec_byid($id);
//echo "<pre>".print_r($update_rec[0],true)."</pre>";exit;
$seralizedtags = serialize($this->input->post('tagsar'));
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description')
);
$recid = $this->input->post('recid');
// echo "<pre>".print_r($data,true)."</pre>";exit;
$update_res = $this->knowledge_model->update_rec($recid, $data);
if ($update_res > 0) {
$this->session->set_flashdata('message', "<p>Record Updated successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
} else {
$this->session->set_flashdata('message', "<p>Error in Updation.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge/update/' . $recid . '";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
if (isset($update_rec)) {
$this->data['recid'] = array(
'name' => 'recid',
'class' => 'form-control',
'id' => 'recid',
'type' => 'hidden',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->id,
);
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->subject,
);
$tags_data = unserialize($update_rec[0]->tags);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $tags_data,
);
$data['desc'] = $update_rec[0]->description;
} else {
$this->session->set_flashdata('message', "<p>Update Record not found.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('edit_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function download_dbx_file(){
$file_path = $_POST['dropbox_path'];
$mime_type = $_POST['dropbox_mim_type'];
$this->download_file($file_path,$mime_type);
}
public function del($id)
{
$this->knowledge_model->del_rec($id);
$this->session->set_flashdata('message', "<p>Record Deleted successfully.</p>");
redirect(base_url() . 'knowledge');
}
// for upload to dropbox //
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($this->appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$this->appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if (!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale,$appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")\n".
"doesn't have a built-in web server. You need PHP 5.4 or newer.\n".
"\n".
"You can still run this example if you have a web server that supports PHP 5.3.\n".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.\n".
"Usage: php $argv[0] [server-port]\n");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:\n".
" $cmd\n");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
public function upload_to_dropbox($filename){
if($filename != ''){
try {
$dbxClient = $this->getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$filename;
$fp = fopen($_FILES['attached_file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
//$str = print_r($result, true);
return $result;
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "File does not exists";
exit;
}
}
public function download_file($file_path,$file_mime_type){
if($file_path != '' && $file_mime_type != '' ) {
try {
$dbxClient = $this->getClient();
$path = $file_path;
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "Invalid Request";
exit;
}
}
}

Advice on Php codeigniter insert query

I have a form and it's been bugging for a while now, when i have all the information filled up in the forms it seems to insert it very quick, however if one or more fields are empty it doesn't work at all
the query i am using to insert into the database is. i am trying to figure out if i can use Insert_delay and maybe it will solve the problem? any possible solutions or changes i need to do
function student($param1 = '', $param2 = '', $param3 = '')
{
if ($this->session->userdata('admin_login') != 1)
redirect('login', 'refresh');
if ($param1 == 'create') {
$data['name'] = $this->input->post('name');
$data['sex'] = $this->input->post('sex');
$data['address'] = $this->input->post('address');
$data['phone'] = $this->input->post('phone');
$data['email'] = $this->input->post('email');
$data['password'] = $this->input->post('password');
$data['year'] = $this->input->post('year');
$data['rate'] = $this->input->post('rate');
$data['class_id'] = $this->input->post('class_id');
$data['class_id2'] = $this->input->post('class_id2');
$data['class_id3'] = $this->input->post('class_id3');
$data['class_id4'] = $this->input->post('class_id4');
$data['parent_id'] = $this->input->post('parent_id');
$data['roll'] = $this->input->post('roll');
$this->db->insert_('student', $data);
$student_id = $this->db->insert_id();
$this->session->set_flashdata('flash_message' , get_phrase('Student_added_successfully'));
$this->email_model->account_opening_email('student', $data['email']); //SEND EMAIL ACCOUNT OPENING EMAIL
redirect(base_url() . 'index.php?admin/student_add/' . $data['class_id'], 'refresh');
In controller
function student($param1, $param2 $param3 )
{
if ($this->session->userdata('admin_login') != 1)
{
redirect('login', 'refresh');
}
else
{
if($param1 == 'create') {
$result = $this->model_name->insert_data();
if ($result != FALSE) {
$email => $this->input->post('email');
$confirm = $this->email_model->account_opening_email('student', $email); # do same as insert
if ($confirm != FALSE) {
$this->session->set_flashdata('flash_message' , get_phrase('Student_added_successfully'));
redirect(base_url() . 'index.php?admin/student_add/' . $data['class_id'], 'refresh');
}
else
{
echo "Mail send failed";
}
}
else
{
echo "param1 is not create";
}
}
}
}
In Model
public function insert_data()
{
# to isert data, I add them in to one array
$data = array(
'name' => $this->input->post('name'),
'sex' => $this->input->post('sex'),
'address' => $this->input->post('address'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'year' => $this->input->post('year'),
'rate' => $this->input->post('rate'),
'class_id' => $this->input->post('class_id'),
'class_id2' => $this->input->post('class_id2'),
'class_id3' => $this->input->post('class_id3'),
'class_id4' => $this->input->post('class_id4'),
'parent_id' => $this->input->post('parent_id'),
'roll' => $this->input->post('roll')
);
if (!$this->db->insert('student', $data)) {
# insert FAILED
return FALSE;
}
else{
# insert SUCCESS
$slast_id = $this->db->insert_id(); # get last insert ID
return = $slast_id;
}
}

Categories