Im trying to send a POST request to an external website, from what iv read so far its not possible due to same origin policy. But i'v also read a proxy can bypass this.
Is this possible AT ALL if I don't have access to the external website? I can't seem to clarify this.
I just want to send an AJAX POST and get the response like when i use Chrome's Advanced REST Client.
Set your header with
Access-Control-Allow-Origin: http://foo.example
To any other noobies in the problem
Slightly modified this:
https://github.com/eslachance/php-transparent-proxy
Now accepts a posting url:
<?php
if(!function_exists('apache_request_headers')) {
// Function is from: http://www.electrictoolbox.com/php-get-headers-sent-from-browser/
function apache_request_headers() {
$headers = array();
foreach($_SERVER as $key => $value) {
if(substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
return $headers;
}
}
// Figure out requester's IP to shipt it to X-Forwarded-For
$ip = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
//echo "HTTP_CLIENT_IP: ".$ip;
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
//echo "HTTP_X_FORWARDED_FOR: ".$ip;
} else {
$ip = $_SERVER['REMOTE_ADDR'];
//echo "REMOTE_ADDR: ".$ip;
}
//
preg_match('#^(?:http://)?([^/]+)#i', $_SERVER['HTTP_REFERER'], $matches);
$host = $matches[1];
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
$domainName = "{$matches[0]}";
//
//writelog($_POST);
$method = $_SERVER['REQUEST_METHOD'];
$desturl;
// parse the given URL
if($method == "POST") {
$desturl = $_POST['url'];
unset($_POST['url']);
}
else if ($method == "GET") {
$desturl = $_GET['url'];
unset($_GET['url']);
}
$response = proxy_request($desturl, ($method == "GET" ? $_GET : $_POST), $method);
$headerArray = explode("\r\n", $response[header]);
foreach($headerArray as $headerLine) {
header($headerLine);
}
echo $response[content];
function proxy_request($url, $data, $method) {
// Based on post_request from http://www.jonasjohn.de/snippets/php/post-request.htm
global $ip;
// Convert the data array into URL Parameters like a=b&foo=bar etc.
//$data = http_build_query($data);
$data = json_encode($data, JSON_FORCE_OBJECT);
writelog($data);
$datalength = strlen($data);
$url = parse_url($url);
//echo $url;
if ($url['scheme'] != 'http') {
die('Error: Only HTTP request are supported !');
}
// extract host and path:
$host = $url['host'];
$path = $url['path'];
// open a socket connection on port 80 - timeout: 30 sec
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp){
$out="";
if($method == "POST") {
$out ="POST $path HTTP/1.1\r\n";
} else {
$out ="GET $path?$data HTTP/1.1\r\n";
}
//Todo Get headers and forward them...
$requestHeaders = apache_request_headers();
while ((list($header, $value) = each($requestHeaders))) {
/*if($header !== "Connection" && $header !== "Host" && $header !== "Content-Length"
&& $header !== "Content-Type"
&& $header !== "Origin"
&& $header !== "Referer"
&& $header !== "X-Requested-With"
&& $header !== "Accept-Encoding"
) {
// $out.= "$header: $value\r\n";
writelog("$header: $value\r\n");
}*/
if($header == "Cookie" && $header == "User-Agent" ) {
$out.= "$header: $value\r\n";
//writelog("$header: $value\r\n");
}
}
$out.= "Host: $host\r\n";
$out.= "Content-Type: application/json; charset=UTF-8\r\n";
$out.= "Content-Length: $datalength\r\n";
$out.= "Connection: Close\r\n\r\n";
$out.= $data;
fwrite($fp, $out);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
}
else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
// close the socket connection:
fclose($fp);
// split the result header from the content
$result = explode("\r\n\r\n", $result, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
// return as structured array:
return array(
'status' => 'ok',
'header' => $header,
'content' => $content
);
}
?>
Related
public function jobCandidateBreakdown($job_export_csv_id){
$fileName = 'Healthdaq - Admin Candidate Breakdown.csv';
$applied_jobs= AppliedJob::where('job_id',$job_export_csv_id)->with('job')->get();
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns = array('Company Name','Candidate', 'Email','MOBILE','Source','Job','Job type', 'Current Status', 'Department', 'Headline', 'Date Added','Stage','Question','Answer');
$callback = function() use($applied_jobs, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($applied_jobs as $applied_job) {
if($applied_job->candidate)
{
$row['Company_name'] = $applied_job->job->companies->company_name;
$row['Candidate'] = $applied_job->candidate->user_name;
$row['Email'] = $applied_job->candidate->users->email;
$row['phone_number'] = $applied_job->jobApplicantionFormData() ? $applied_job->jobApplicantionFormData()->phone_number : '';
$row['Source'] = $applied_job->source;
$row['Job'] = $applied_job->job->job_title;
$row['Job_type'] = $applied_job->job->getType() ;
$row['Current_Status'] = $applied_job->job->status;
$row['Department'] = $applied_job->job->departments->name;
$row['Headline'] = $applied_job->jobApplicantionFormData() ? $applied_job->jobApplicantionFormData()->heading : '';
$row['Date_Added'] = $applied_job->created_at->format('d/m/y h:s');
$row['Stage'] = $applied_job->workflow_stage;
$array = [
$row['Company_name'],
$row['Candidate'],
$row['Email'],
$row['phone_number'],
$row['Source'] ,
$row['Job'],
$row['Job_type'],
$row['Current_Status'],
$row['Department'] ,
$row['Headline'] ,
$row['Date_Added'],
$row['Stage'],
];
if($applied_job->jobApplicantionFormData()){
foreach($applied_job->jobApplicantionFormData()->jobApplicationCustomAnswers as $value){
$row['question'] = $value ? $value->question : '';
$row['answer'] = $value ? $value->answer : '';
array_push($array,$row['question'],$row['answer']);
}
}
fputcsv($file, $array);
}
}
fclose($file);
};
// dd("hello");
Auth::user()->createLog('Exported report (Candidate Breakdown Report)');
return response()->stream($callback, 200, $headers);
}
Try to use streamDownload method insted of stream method.
Can't Download File as CSV
I'm trying to export some data as CSV & every time i try to export data i got this error - Call to undefined method Symfony\Component\HttpFoundation\StreamedResponse::header()
I have tried different possible ways but they aren't working
My Function (Controller File)
public function exportd(Request $request)
{
$fileName = 'data.csv';
$data = json_decode($request->data);
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns = array('Name', 'Gender', 'experrience', 'location', 'Pref Location', 'Salary'
...
);
$callback = function() use($data, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($data as $da) {
$row['Name'] = $da->name;
$row['Gender'] = $da->gender;
$row['experrience'] = $task->experrience;
$row['Pref Location'] = $task->pref_loc;
$row['Salary'] = $task->salary;
...
fputcsv($file, array($row['Name'], $row['Gender'],$row['experrience'], $row['location'], $row['Pref Location'], $row['Salary']
...
));
}
fclose($file);
};
return Response()->stream($callback, 200, $headers);
}
My Middleware (AuthCheck)
public function handle(Request $request, Closure $next)
{
if(!session()->has('LoggedUser') && ($request->path() !='auth/login' && $request->path() !='auth/register' )){
return redirect('auth/login')->with('fail','You must be logged in');
}
if(session()->has('LoggedUser') && ($request->path() == 'auth/login' || $request->path() == 'auth/register' ) ){
return back();
}
return $next($request)->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','0');
}
$next($request) is an instance of Symfony\Component\HttpFoundation\StreamedResponse in your scenario.
StreamedResponse does not support ->header(...).
If you want to preserve your ->header(...) call, you must verify that the response is an instance of Illuminate\Http\Response
public function handle(Request $request, Closure $next)
{
if(!session()->has('LoggedUser') && ($request->path() !='auth/login' && $request->path() !='auth/register' )){
return redirect('auth/login')->with('fail','You must be logged in');
}
if(session()->has('LoggedUser') && ($request->path() == 'auth/login' || $request->path() == 'auth/register' ) ){
return back();
}
$response = $next($request);
if($response instanceof \Illuminate\Http\Response) {
return $response->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','0');
}
return $response;
}
I have written a code in the controller which is given below. This code is for login page. In this code, the if statement notification is properly working but the else part is not working. It is not redirect to the url given in the redirect() instead it is showing a blank page. Can anyone tell y it is like that and correct it for me ? I have used header() function but also it is not working.I have placed all the code inside the 'kw' folder. This code is properly working in the localhost but when uploaded the same code to the live server, its not working.Is it due to version of the CI ?
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('validation');
$this->load->model('studentsmodel');
}
public function index() {
if (isset($_POST['submit']))
{
$post_data = array('stud_cin' => $this->input->post('stud_cin'),'stud_password' => $this->input->post('stud_password'),
);
$this->validation->set_data($post_data);
$this->validation->set_rules('stud_cin','Cin','required|trim');
$this->validation->set_rules('stud_password','Password','required|trim');
if ($this->validation->run() === FALSE)
{
}
else
{
$this->load->model("studentsmodel");
$this->load->helper('url');
$result = $this->studentsmodel->loginCheck($post_data);
if (!$result){
$this->notifications->notify('Wrong username/password; Login Failed','error');
}
else{
$this->session->set_userdata('student_id', $result['id']);
$this->session->set_userdata('stud_cin', $result['stud_cin']);
$this->session->set_userdata('stud_photopath', $result['stud_photopath']);
redirect('student/profile/edit/id/'.$this->session->userdata('student_id'),'refresh');
//header('location:http://www.website.com/kw/application/controller/student/profile/edit/id/$this->session->userdata("student_id")');
}
}
} $this->load->view("login");
}
}
profile controller edit function
public function index()
{
$student_id=$this->session->userdata('student_id');
$data['profile_data'] =$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profileDetails.php", $data);
}
public function edit()
{
$uri = $this->uri->uri_to_assoc(4);
$student_id=$uri['id'];
if(isset($_POST['btn_submit']))
{
//echo "<pre>";print_r($_FILES);exit;
$img_val = $this->studentsmodel->getStudent_photo($student_id);
$photo_val = $img_val['stud_photopath'];
$photo_unlink = "";
if ($_FILES['stud_photopath']['name'] != "")
{
/*echo "in";exit;*/
$photo_chk = explode("photo/", $photo_val);
$photo_unlink = $photo_chk[1];
$photo_path = "";
$flag = "";
$f_type_chk = $_FILES['stud_photopath']['type'];
if ($f_type_chk != "image/gif" && $f_type_chk != "image/jpg" && $f_type_chk != "image/jpeg"
&& $f_type_chk != "image/bmp" && $f_type_chk != "image/png" && $f_type_chk != "")
{
$flag = "Select allowed file type and size for photo";
}
if ($_FILES['stud_photopath']['size'] >= 5242880) { $flag = "Select allowed file type and size for photo"; }
$target_path = getcwd() . "/public/photo/";
$db_path = "photo/";
if ($_FILES['stud_photopath']['name'] != '')
{
$file_name = $_FILES["stud_photopath"]["name"];
$file_size = $_FILES["stud_photopath"]["size"] / 1024;
$file_type = $_FILES["stud_photopath"]["type"];
$file_tmp_name = $_FILES["stud_photopath"]["tmp_name"];
$random = rand(111, 999);
$new_file_name = $random . $file_name;
$newfile_name=$cin."_". $file_name;
$upload_path = $target_path . $newfile_name;;
if (move_uploaded_file($file_tmp_name, $upload_path)) { $photo_path = addslashes($db_path . $newfile_name); } /*end if*/
else { $this->notifications->notify('Photo cannot upload', 'error'); }/*end else var_dump($this->validation->show_errors());*/
}/*end if $_FILES['photo']['name']*/
} /*END OF if ($_FILES['photo']['name'] != "") */
else { $photo_path = $photo_val; } /*END OF ELSE ($_FILES['photo']['name'] != "") */
$this->session->unset_userdata('stud_photopath');
$this->session->set_userdata('stud_photopath', $photo_path);
$data['photo_unlink'] = $photo_unlink;
/* echo $dob_dd = $this->input->post('dob_dd');exit;
$dob_mm = $this->input->post('dob_mm');
$dob_yy = $this->input->post('dob_yy');
$dob = $dob_dd . "-" . $dob_mm . "-" . $dob_yy;*/
$stud_age_dob =$this->input->post('stud_age_dob');
$timestamp = strtotime($stud_age_dob);
$dob = date('Y-m-d', $timestamp);
$validation_data = array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' =>$this->input->post('stud_age_dob'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
);
//echo "<pre>";print_r($validation_data); exit;
$this->validation->set_data($validation_data);
$this->validation->set_rules('stud_name', 'Student Name', 'trim|alpha_space|required');
$this->validation->set_rules('stud_gender', 'Gender', 'required');
$this->validation->set_rules('stud_age_dob', 'DOB', 'required');
$this->validation->set_rules('stud_mobile', 'Mobile number', 'numeric|required');
$this->validation->set_rules('stud_email', 'Email Id', 'trim|required|valid_email|xss_clean');
if ($this->validation->run() === FALSE)
{ /* var_dump($this->validation->show_errors()); */ $this->notifications->notify('Please make all entries', 'error');}
else
{
$updation_data=array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' => $this->input->post('stud_age_dob'),
'stud_gaurdian' =>$this->input->post('stud_gaurdian'),
'stud_mother' =>$this->input->post('stud_mother'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
'stud_tel' => $this->input->post('stud_tel'),
'stud_guardian_address' => $this->input->post('stud_guardian_address'),
'stud_pin' => $this->input->post('stud_pin'),
'stud_photopath' => $photo_path,
'stud_age_dob' => $dob
);
/*echo "<pre>";print_r($updation_data); exit; */
$update_status=$this->studentsmodel->update_profile($updation_data, $student_id);
if($update_status==1)
{
//$this->session->set_userdata('profile_status', 'Yes');
/*$this->session->userdata('profile_status');*/
redirect('student/profile/index/', 'refresh');
}
else
{
$this->notifications->notify('profile updted failed', 'error');
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profile_edit.php",$data);
}
Check if you already load this helper
$this->load->helper('url');
This is the information about the redirect function
redirect($uri = '', $method = 'auto', $code = NULL);
Parameters:
$uri (string) URI string $method (string)
Redirect method (‘auto’,
‘location’ or ‘refresh’)
$code (string) HTTP Response code (usually 302 or 303)
Note:
Don't forget add in the config file the value for base_uri
https://www.codeigniter.com/user_guide/helpers/url_helper.html
https://www.codeigniter.com/userguide3/libraries/config.html
remove /id/ from your redirect()
redirect('student/profile/edit/'.$this->session->userdata('student_id'));
This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki
I have the following script which retrieves code from gmail. the code runs well in localhost, but gives error when i upload it on server and make it eun. The script is made in codeigniter.
<?php
class invite_friends extends CI_Controller{
var $FEED_URL = "http://www.google.com/m8/feeds/contacts/default/full";
var $LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
var $username = "my_qmail#gmail.com";
var $passwd = "my_passowrd";
var $postData = array();
function __construct() {
parent::__construct();
session_start();
}
function index()
{
if(isset($_SESSION['logged_user']))
redirect(base_url().'home');
$this->load->view('header');
$this->load->view('invite_friends');
$this->load->view('footer');
}
/*function GmailContacts_lib($gUsername, $gPassword) {
//constructor function
$this->username = $gUsername;
$this->passwd = $gPassword;
}*/
function get_gmail_contacts() {
$emailLists = array();
//create an array for post data
$this->postData = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => $this->username,
"Passwd" => $this->passwd,
"service" => "cp",
"source" => "anything"
);
//initialize the curl object
$curl = curl_init($this->LOGIN_URL);
//set the curl options
$this->set_curl_options($curl, CURLOPT_POST, true);
$this->set_curl_options($curl, CURLOPT_POSTFIELDS, $this->postData);
$this->set_curl_options($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$this->set_curl_options($curl, CURLOPT_SSL_VERIFYPEER, false);
$this->set_curl_options($curl, CURLOPT_RETURNTRANSFER, 1);
//following variable contains the responses
$response = curl_exec($curl);
//check if the user has logged in sucessfully
//and save auth key if logged in
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
if( !empty($auth)) {
$headers = array("Authorization: GoogleLogin auth=".$auth);
//make the request to google contacts feed with the auth key maximum contacts is 10000
$curl1 = curl_init($this->FEED_URL);
//passing the headers of auth key
$this->set_curl_options($curl1, CURLOPT_HTTPHEADER, $headers);
//return the result in a variable
$this->set_curl_options($curl1, CURLOPT_RETURNTRANSFER, 1);
//results response
$feed = curl_exec($curl1);
//parse the feed and return email list array
$emailLists = $this->parse_response($feed);
}
else {
$emailLists = array("Invalid Username/Password");
}
print_r($emailLists);
}
//function to set curl options
function set_curl_options($ch, $option, $value) {
//make the post TRUE
return curl_setopt($ch, $option, $value);
}
//function to parse response
public function parse_response($feed) {
$contacts = array();
$doc = new DOMDocument();
//load the XML response
$doc->loadXML($feed);
//check the entry tag
$nodeList = $doc->getElementsByTagName( 'entry' );
foreach($nodeList as $node) {
//children of each entry tag
$entry_nodes = $node->childNodes;
$tempArray = array();
foreach($entry_nodes as $child) {
//get the tagname of the child
$domNodesName = $child->nodeName;
switch($domNodesName) {
case "title":
{ $tempArray['fullName'] = $child->nodeValue; }
break;
case "gd:email":
{
if (strpos($child->getAttribute('rel'),'home')!==false)
$tempArray['email_1']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'work')!=false)
$tempArray['email_2']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'other')!==false)
$tempArray['email_3']=$child->getAttribute('address');
}
break;
} //end of switch for nodeNames
} //end of foreach for entry_nodes child nodes
if( !empty($tempArray['email_1'])) $contacts[$tempArray['email_1']] = $tempArray;
if( !empty($tempArray['email_2'])) $contacts[$tempArray['email_2']] = $tempArray;
if( !empty($tempArray['email_3'])) $contacts[$tempArray['email_3']] = $tempArray;
}
return $contacts;
}
}
?>
it gives error and here is the error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: controllers/invite_friends.php
Line Number: 54
I would suggest changing your code to the following
if(preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches))
{
$auth = $matches[1];
}
else
{
$auth = null;
}
You could set $auth to null or 0. But if you set it to null I would then instead check:
if(!is_null($auth)) {