Codeigniter - Displaying page - php

I'm having a problem displaying my index.php in codeigniter. Can someone help me with this?
Here's my index.php:
<form id="myForm" action="<?php echo baseurl('controller/CreateUser'); ?>" method="post">
Name: <input type="text" name="name"/><br/>
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<button id="sub">Save</button>
</form>
<span id="result"></span>
And here's my controller:
public function index(){
$this->load->view( 'layouts/header', [ 'title' => 'Never Stop Learning!' ] );
$this->load->view( 'NeverStopLearning/index');
$this->load->view( 'layouts/footer' );
}
public function CreateUser(){
$data = array(
"name" => $this->input->post("name"),
"username" => $this->input->post("username"),
"password" => $this->input->post("password")
);
if($this->model->Insert('table_users', $data)){
echo "Successfully Inserted";
}else{
echo "Insertion Failed";
}
}

Related

Why does the validation for my codeigniter website fail everytime?

I have a controller code like so:
$validation=service('validation');
$validation->reset();
$data = [
'validation' => $validation,
];
if ($this->request->getMethod() === 'post'){
$validation->setRules( [ 'comment' => 'required',] );
if($validation->run()) {
$CommentsModel->save(['Comment' => $this->request->getPost('comment'),]);
return redirect()->to('/someplace...');
}
}
}
return view('templates/header', $data)
. view('templates/menu')
. view('addComment', $data)
. view('templates/footer');
}
Everytime my form is posted, the validation fails... even when I have something in comment! Any idea why this would be?
This is the form:
<form action="/Add/<?= esc($book)?>/<?= esc($chapter) ?>" method="post">
<?= csrf_field() ?>
<label for="comment">Comment</label>
<textarea name="comment" id="comment" ><?= set_value("comment")?></textarea><br />
<?php if($validation->hasError('comment')) echo '<p class="validationError">' . $validation->getError('comment') . '</p>'?>
<input type="submit" name="submit" value="Add Comment" />
</form>

Codeigniter: Cannot upload files, Undefined Index : avatar

I cannot seem to upload files in codeigniter. I don't know if the issue lies with the if ($_FILES['avatar']['name'] == "").
My controller
private function upload_avatar($file)
{
$newName = $file->getRandomName();
$upload = $file->move(ROOTPATH . 'public/assets/avatar', $newName);
if ($upload) {
return $newName;
} else {
return false;
}
}
public function change_data()
{
helper(['form', 'url']);
$userModel = new UserModel();
if ($this->request->getMethod() == 'post') {
if ($_FILES['avatar']['name'] == "")
{
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]'
];
} else {
$rules = [
'nama' => 'required|alpha_space|min_length[2]',
'email' => 'required|valid_email',
'nip' => 'required|min_length[2]',
'tempat_lahir' => 'required|alpha_space|min_length[2]',
'avatar' => [
'uploaded[avatar]',
'mime_in[avatar,image/jpg,image/jpeg,image/png]',
'max_size[avatar,4096]'
]
];
}
if ($this->validate($rules)) {
if ($_FILES['avatar']['name'] == "") {
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
];
} else {
//get data user by session email
$user = $userModel->where('email', session()->get('email'))
->first();
if ($user) {
$deleteFile = unlink('./assets/avatar/' . $$user['avatar']);
if ($deleteFile) {
$file = $this->request->getFile('avatar');
$uploadFile = $this->upload_avatar($file);
}
}
$params = [
'nama' => $userModel->escapeString(esc($this->request->getPost('nama'))),
'email' => $userModel->escapeString(esc($this->request->getPost('email'))),
'nip' => $userModel->escapeString(esc($this->request->getPost('nip'))),
'tempat_lahir' => $userModel->escapeString(esc($this->request->getPost('tempat_lahir'))),
'avatar' => $uploadFile,
];
}
$update = $userModel->update($user['id_user'], $params);
if ($update) {
session()->setFlashdata('success', 'Berhasil Update Data. Apabila Tampilan Data Belum Berubah, Silakan Lakukan Logout dan Login Kembali');
return redirect()->route('profile');
} else {
session()->setFlashdata('danger', 'Gagal Update Data');
return redirect()->route('edit')->withInput();
}
} else {
$data['validation'] = $this->validator;
}
}
$data['title'] = 'Edit Profile';
return view('admin/users/ubah_data', $data);
}
My view
<form action="<?= base_url('admin/user/change_data') ?>" method="POST">
<?= csrf_field(); ?>
<div class="form-group">
<label for="nama">Nama</label>
<input type="text" class="form-control" id="nama" name="nama" value="<?= session()->nama ?>">
</div>
<div class="form-group">
<label for="nip">NIP</label>
<input type="text" class="form-control" id="nip" name="nip" value="<?= session()->nip ?>">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="<?= session()->email ?>">
</div>
<div class="form-group">
<label for="tempat_lahir">Tempat Lahir</label>
<input type="text" class="form-control" id="tempat_lahir" name="tempat_lahir" value="<?= session()->tempat_lahir ?>">
</div>
<div class="form-group">
<label for="avatar">Foto <small>(Optional)</small></label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="avatar" name="avatar">
<label class="custom-file-label" for="avatar">Choose file</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-info" />
</div>
</form>
After i push the upload button Undefined index: avatar message appeared.
Any help will be greatly appreciated. I cannot seem to figure out why ($_FILES['avatar']['name'] == "") has problem
I think you miss to include enctype="multipart/form-data" in form tag
<form action="url-action" method="POST" enctype="multipart/form-data">
your form
</form>

CodeIgniter not reacting to post

When I submit a form for the url example.com/index.php/topic/1/test-topic-test CodeIgniter does not recognize that a post form is submitted.
Routes:
$route["topic/(:num)/([a-z]+)"]["post"] = "forums/topic_post_reply/$1/$2";
Forums.php controller:
public function topic_post_reply($id, $name)
{
$message = $this->input->post("topic_reply_content");
if(!empty($message) && !empty($this->session->userdata('id')))
{
$data = [
"content" => $message,
"author" => $this->session->userdata('id'),
"reply_date" => time(),
"parent" => $id
];
$this->db->insert("forum_topics_replies", $data);
}
else
{
die("Something went wrong");
}
}
Form:
<form class="uk-form-stacked" action="<?php echo base_url(); ?>index.php/topic/<?php echo $this->uri->segment(2); ?>/<?php echo $this->forums_model->slug($this->uri->segment(3)); ?>" method="post">
<div class="uk-form-inline">
<textarea class="uk-textarea" name="topic_reply_content" rows="4" placeholder="Write a lovely reply..."></textarea>
</div>
<div class="laevis-reply-hidden">
<div class="uk-margin-small" style="margin-bottom:0">
<input type="submit" class="uk-button uk-button-primary uk-width-1-1" value="Post">
</div>
</div>
Why isn't this working?
I had to have the post route above all other routes for the same url or it would not work. I also had to change it to $route["topic/(:num)/:any"]["post"].

Paypal sandbox error: You have requested an outdated version of PayPal

You have requested an outdated version of PayPal. This error often
results from the use of bookmarks.
I get this error when I login via a buyer account in sandbox mode.
my view file:
<html>
<body>
<form method="post" action ="https://www.sandbox.paypal.com/cgi-bin/webscr">
<input type="hidden" name="upload" value="1" />
<input type="hidden" name="return" value="<?php echo $this->config->item('returnurl');?>" />
<input type="hidden" name="cmd" value=" " />
<input type="hidden" name="business" value="<?php echo $this->config->item('business');?>" />
<!--product 1-->
<input type="hidden" name="item_name_1" value="prod 1" />
<input type="hidden" name="item_number_1" value="p1" />
<input type="hidden" name="amount_1" value="2" />
<input type="hidden" name="quantity_1" value="1" />
<input type="submit" name="paypalbtn" value="buy with paypal">
</form>
</body>
</html>
my config file : paypal.php
<?php
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
$config['authtoken']='IDENTITY_TOKEN';
$config['posturl']='https://www.sandbox.paypal.com/cgi-bin/webscr';
$config['business']='DUMMY_FACILITATOR_EMAIL_ID';
$config['returnurl']='http://localhost/events/event_pay/success/';
$config['cancel_return']='http://localhost/events/event_pay/pay_fail';
?>
my controller file:
<?php
class event_pay extends MX_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('mdl_pay');
}
function index()
{
$this->load->view('demo');
}
function showplans()
{
$this->load->view('vw_header');
$this->load->view('vw_eventplans');
$this->load->view('vw_footer');
}
function check_events_by_user()
{
$u_id=37;
$numberofrows =$this->mdl_pay->has_paid($u_id);
echo $numberofrows;
}
function pay_success($data)
{
echo "return url function";
$this->load->view('success',$data);
}
function pay_fail()
{
echo "payment failed";
}
function success()
{
$res = $this->verifyWithPayPal($_GET['tx']);
$this->load->view('success_pay',$res);
}
function successdemo()
{
$this->load->view('vw_success_pay');
}
public function verifyWithPayPal($tx)
{
$token = $this->config->item('authtoken');
$paypal_url = $this->config->item('posturl').'?cmd=_notify-synch&tx='. $tx.'&at='.$token;
$curl= curl_init($paypal_url);
$data=array(
"cmd"=>"_notify-synch",
"tx"=>$tx,
"at"=>$token
);
$data_string=json_encode($data);
curl_setopt($curl,CURLOPT_HEADER, 0);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$headers= array(
'Content-Type:application/x-www-form-urlencoded',
'Host: www.sandbox.paypal.com',
'Connection: close'
);
curl_setopt($curl,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
$response= curl_exec($curl);
$lines= explode("\n", $response);
$keyarray = array();
if(strcmp($lines[0],"SUCCESS")==0){
for($i=1;$i<count($lines)-1; $i++){
list($key,$val)=explode("=",$lines[$i]);
$keyarray[urldecode($key)]=urldecode($val);
}
$this->getListProducts($keyarray);
}
}
public function getListProducts($result)
{
$i=1;
$data = array();
foreach($result as $key => $value)
{
if(0===strpos($key,'item_number')){
$product = array(
'buyer_firstname' => $result['first_name'],
'buyer_lastname' => $result['last_name'],
'buyer_street' => $result['address_street'],
'buyer_city' => $result['address_city'],
'buyer_zip' => $result['address_zip'],
'buyer_state' => $result['address_state'],
'buyer_country' => $result['address_country'],
'buyer_country_code' => $result['address_country_code'],
'buyer_address_status' => $result['address_status'],
'buyer_pp_email' => $result['payer_email'],
'receiver_pp_email' => $result['receiver_email'],
'transaction_id' => $result['txn_id'],
'transaction_type' => $result['txn_type'],
'buy_date' => $result['payment_date'],
'buyer_pp_id' => $result['payer_id'],
//'address_name' => $result['address_name'],
'receiver_pp_id' => $result['receiver_id'],
'receiver_pp_email' => $result['receiver_email'],
'itemnumber' => $result['item_number'],
'itemname' => $result['item_name'],
'itemquantity' => $result['quantity'],
'mc_currency' => $result['mc_currency'],
'mc_fee' => $result['mc_fee'],
'mc_gross' => $result['mc_gross'],
'payment_gross' => $result['payment_gross'] ,
'paypal_pay_time' => date('Y-m-d H:i:s'),
);
$this->mdl_pay->insert_record($product);
echo "<script>alert('Payment Successful!')</script>";
}
}
echo "return statement:at end of for loop ";
return $product;
}
}
?>
The problem was occuring due to this line:
<input type="hidden" name="cmd" value="" />
I replaced it with:
<input type="hidden" name="cmd" value="_xclick" />
Read: https://github.com/websharks/s2member/issues/826 , if this doesn't work contact paypal support, there's not much we can do here.

insert database nusoap-complexType

I want to create insert database a web service from :
http://www.discorganized.com/php/a-complete-nusoap-and-flex-example-part-1-the-nusoap-server/
Here's my script :
<?php
require_once 'lib/nusoap.php';
$client= new nusoap_client("http://127.0.0.1/test2/index.php", false);
$in_contact=array ('first_name'=>$_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'],);
$result = $client->call('insertContact', $in_contact);
if ($result){
echo "OK";
} else {
echo "Error";
}
?>
despite increasing ID, why the other columns remain empty ?
please help me, thank you.
The <form> code..
< form action="Contact.class.php" method="GET" > Nama Depan:<br> <input type="text" name="first_name"/><br> Nama Belakang:<br> <input type="text" name="last_name"/><br> Email:<br> <input type="text" name="email"/><br> Telepon:<br> <input type="text" name="phone_number"/><br><br> <input type="submit" value="Submit"/><br> < /form >
As you can see the method is GET , Change that to POST
Like this...
<form action="Contact.class.php" method="POST" >
The fixed <form> code.. You had a lot of indentations gone wrong..
<form action="Contact.class.php" method="POST" >
Nama Depan:<br> <input type="text" name="first_name"/><br>
Nama Belakang:<br> <input type="text" name="last_name"/><br>
Email:<br> <input type="text" name="email"/><br>
Telepon:<br> <input type="text" name="phone_number"/><br><br>
<input type="submit" value="Submit"/><br> </form>
<?php
require_once 'lib/nusoap.php';
$client= new nusoap_client("http://127.0.0.1/test2/index.php", false);
$in_contact=array ('first_name'=>$_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'],);
$result = $client->call('insertContact', array($in_contact));
if ($result){
echo "OK";
} else {
echo "Error";
}
?>

Categories