Sending query string value through url using foreach loop - php

I am using codeigniter for the application. First,I created the View that consist of Message TextArea Box , DropDownlist which value comes from database, and submit button. I have database of two colums one for mobile number and another for service provider.I have predefined url with query string value (http://www.something.com?mobno=numbervar&msg=messagevar)
In model class, I have function called getProvider1, to get return the array of mobile number of particular provider. I should use the above url with query string passing mobile number and message that inputted by user. Here I have used foreach loop to pass message to different mobile number through query string .
The problem is that I couldn't get idea how to pass message to multiple mobile number without visiting that something.com pages and show result which query string value is passed and which are failed... Here, I couldn't pass the different query string value in that url using foreach. It only visited one page or redirect once....Is there any function something like redirect()....or any other options. Please want some suggestion... will be greatly appreciated.... Following is the controller's function to send message
function message()
{ $message = $this->input->post('message');
$provider = $this->input->post('provider');
if($provider == 'provider1')
{
$number = $this->message_model->getProvider1();
$mobile = array();
foreach($number as $no)
{
$mobile = $no;
redirect('http://something.com?mobno='.$mobile.'&msg='.$message);
}
}
else if
{
// same process for service provider2
}
else
{
//other service provider
}
}

Firstly, I'm not 100% sure what it is you want to do exactly, but redirect will clearly only work once (since after you have redirected you are no longer on your page).
What you could do, based on my understanding of your code, is look in to cURL. It gives you the opportunity to load several pages and look at their results "behind the scenes" and display whatever you want to your users.
Some other notes.
/* Instead of doing the same thing for all provides with IFs, rewrite you message model to take the provider name as a input variable insdead. */
$number = $this->message_model->getProvider($provider);
/* $mobile = array(); // you never use this array, no need for it */
foreach($number as $mobile)
{
/* $mobile = $no; //completly useless, just name it in the foreach */
/* --- do a cURL request here --- */
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://something.com?mobno='.$mobile.'&msg='.$message);
$curl_info = curl_getinfo($curl);
curl_close($curl);
if ($curl_info['http_code'] != 200) /* Handle error if any */
{
$errors[] = 'ERROR WITH REQUEST: http://something.com?mobno='.$mobile.'&msg='.$message;
}
}

Related

PHP Dynamic signup page

I wanted to create a dynamic signup.php. The algorithm is as follow:
Algorithm
when signup.php is requested by client, the code will attempt to check whether user send any data in $_POST.
if $_POST does not contains any data (means it's the first time user request for signup.php), a signup form will be return to the user, allowing user to enter all his/her details and again send back to signup.php through submit button.
if $_POST does contains data (means user has fill up the signup form and is now sending all the data back to signup.php), then the php code will attempt validate all those data and return result showing user has been successfully registered or error if failed to do so.
The problem I'm having right now is how am I going to check whether it's the first time user request for signup.php or not?
Use isset() to check if $_POST contains data.
http://php.net/isset
To answer your question, "how am I going to check whether it's the first time user request for signup.php or not?", honestly, probably for other users......
There are a few ways, cookies, storing request ips in a database, bleh, bleh, bleh. But...... None of them are guaranteed. The user can disable cookies, use a dynamic ip, etc. You could issue a unique hash and place it as a login.php?q=encValueForUniquePageRequest
but...... The architecture you laid out won't be practical.
Sorry :(
To check that request is POST:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//process new user
}
?>
Example:
<?php
Class signup_controller extends controller{
private $data = array();
private $model = array();
function __construct(Core $core){
parent::__construct($core);
/* load models - assign to model */
$this->model['page'] = $this->core->model->load('page_model', $this->core);
$this->model['auth'] = $this->core->model->load('auth_model', $this->core);
/* check script is installed - redirect */
if(empty($this->core->settings->installed)){
exit(header('Location: '.SITE_URL.'/setup'));
}
}
function index(){
/* do signup - assign error */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($this->model['auth']->create_user(1)===false){
$this->data['error'] = $this->model['auth']->auth->error;
}
}
/* not logged in */
if(empty($_SESSION['logged_in'])){
/* assign form keys */
$_SESSION['csrf'] = sha1(uniqid().(microtime(true)+1));
$_SESSION['userParam'] = sha1(uniqid().(microtime(true)+2));
$_SESSION['passParam'] = sha1(uniqid().(microtime(true)+3));
$_SESSION['emailParam'] = sha1(uniqid().(microtime(true)+4));
/* get partial views - assign to data */
$this->data['content_main'] = $this->core->template->loadPartial('partials/signup', null, $this->data);
$this->data['content_side'] = $this->core->template->loadPartial('about/content_side', null, $this->data);
/* layout view - assign to template */
$this->core->template->loadView('layouts/2col', 'content', $this->data);
}
/* signed in - redirect */
else{
exit(header('Location: ./user'));
}
}
}
?>

CakePHP - sending POST requests in cakephp API and data handling

I have created a CakePHP app and after already set the routes.php files,i can send JSON requests,in order to use my app as an API. For testing,i have created a function which goes like this:
public function api() {
if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
$this->set('results',$result);
$this->set('_serialize',array('results'));
}
}
I have also created the exact same function with another name,which is meant to be used via a web form and that works correctly. BUT,this code,at this function here,when i POST data (i use Dev HTTP Client chrome extension),it returns the $results variable empty,like it does not receive what i send :/
I send the data as follows via the chrome extension i use:
data1='stuff1'&data2='stuff2'
and it returns me just
{
"results":""
}
(while the same code works perfectly when used without json).
Did i miss something?Does it seem to do something wrong? Please help me a bit around here..
ps:if you need more info,just tell me and i'll post it.
Thank you in advance!
The correct way to access that post would be
$this->request->data['data1'];
to verify what data is being sent do this:
public function api() {
//if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
//$this->set('results',$result);
$this->set('results',array('root'=>$this->request);
$this->set('_serialize',array('results'));
//}
}

kohana 3 creating routes with get

This has to do with routing. So for getting parameters via url, you basically pass the data to the url following the route format you set.
This is working with links. I created the route, passed the data into the url, and used the request method to get the parameter for use in the controller. like URL::site("site/$color/$size")
What if I am constructing the url by form submission? For example, if I want to create a basic search query.
How do I get my form submission to look like this search/orange/large and not like this search.php?color=orange&size=large when I submit a form via get method.
By definition, the GET method puts the submitted information as URL parameters. If you specifically want to end up with a URL like site/$color/$size, you can use the POST-REDIRECT-GET pattern.
A partial example, from a controller on one of my sites (there is a submit button on the page named clear_cache_button):
public function action_index()
{
$session = Session::instance();
$is_post = (Request::current()->post('submit_button') !== NULL);
$is_clear_cache = (Request::current()->post('clear_cache_button') !== NULL);
$p = Database::instance()->table_prefix();
$people = DB::query(Database::SELECT, "
SELECT *
FROM `".$p."Tabe`;
")->cached(600, $is_clear_cache)->execute()->as_array('RegID');
if ($is_clear_cache)
{
HTTP::redirect(Request::current()->uri());
}
...
...
...
}
You can use Route filters (v3.3) or callbacks (3.1, 3.2) and set route params manually.
You can do it this way...
public function action_index()
{
// this will only be executed if you submmitted a form in your page
if(Arr::get($_POST,'search')){
$errors = '';
$data = Arr::extract($_POST,array('color','size'));
// you can now access data through the $data array:
// $data['color'], $data['size']
// perform validations here
if($data['color']=='') $error = 'Color is required';
elseif($data['size']=='') $error = 'Size is required';
if($error==''){
$this->request->redirect('search/'.$data['color'].'/'.$data['size']);
}
}
// load your search page view here
echo 'this is the search page';
}
Hope this helps you out.

calling ajax from within a php function having a switch ($this->method)

when creating an XMLrequest in a php file having a code which goes something like this... I am using a MVC ( model-view-controller structure ) and this is a controller php file..
Controller_Institute extends Controller_Default{
function register(){
try {
$this->requireLogin();
switch($this->method){
case 'GET':
$content = $this->render('institute_registration_confirm');
break;
case 'POST':
$result = mysql_query("SELECT * FROM password WHERE pass='".mysql_real_escape_string($_POST['pass'])."'");
$num=mysql_num_rows($result);
if($num==2)
{
$content = $this->render('institute_registration');
}
else
{
$content = $this- >render("message",array('msg'=>'Your password is incorrect'));
}
break;
}
$institute = R::dispense('institute');
$institute- >import($_POST,'name,latitude,state,longitude,address,phone,year,url');
$id = R::store($institute);
}
catch(exception $e){
//If there was an error anywhere, go to the error page.
$content = $this->render('error',array('exception'=>$e));
}
$page = $this->render('default',array('content'=>$content));
return $page;
}
i am sending the ajax request from within the function ... so when the ajax sends back the request , it gets caught in the switch case... and then the response text becomes the function return value replacing the actual text... any idea how to prevent the xml response from getting into the switch case...? the institute_registration is the view file and i am including that file in my framework and then triggering the ajax function from within that file to check whether the password ( to enable registration form ) is correct or not...
Given the limited information and pseudo-code, I recommend setting up a stand-alone page called say... "ajax.php" that is stand alone and doesn't base it's return value on the request method. The pages that use AJAX will need to either POST or GET from this page depending.
If you determine whether or not regular output vs AJAX output is returned via request method, then you are limiting yourself in 2 ways. The first is you will not be able to do 1 or the other on your web pages (GET vs POST) instead of both. Also, the second, when it comes to the AJAX, you will not be able to run GET & POST AJAX requests, and yes, you can do both with AJAX: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Set and get global variable in php (ZendFramework)

I am using ZendFramework with PHP, and I want to set and get a variable as a global variable. I.E. I set it in the class of Zend Controller and access it any action in the class.
For example:
<?php
class SubscriptionController extends Zend_Controller_Action
{
private $EMAIL = false;
private $USERNAME = false;
First I am validating email addres with ajax call
public function checkusernameAction()
{
$email = //query to find email;
if($email){
$EMAIL = true;
}else{
$EMAIL = false;
}
}
then I want subscribe user on the basis of private variable again with ajax call
public function subscribeAction
{
if($EMAIL == true)
{
//some stuff
}
}
I am getting private var by $this->EMAIL, but not able to access it
You can use Zend_Registry to use the variable throughout application.
You can set a variable like this
Zend_Registry::set('email', $EMAIL);
and later can get it like this
$email= Zend_Registry::get('email');
Looks to me like you are making two distinct requests calling, respectively, checkusernameAction() and subscribeAction(). Since these are distinct requests, the email value you set in the controller during checkusernameAction() will be gone on the second request which calls subscribeAction(). It's the same controller class, but you are looking at two distinct instances, one in each request.
As I see it, you can either:
Pass the email address in each AJAX request, but this seems unlikely since you get the email address from the first call to checkusernameAction().
Save the email in the session during the first checkusernameAction() call and then pick it up during the second subscribeAction() call.
Extract the "get email from username" code into a separate class or method and then call it in both places. After all, you don't want to get bitten by a "race condition" in which the state of the system changes between the two AJAX requests (maybe the user's email changes via some other process or via another set of requests that occur after the first AJAX request containing the call to checkusernameAction().
You can also used a function for set and get a value.
// Setter function
public function setConsumerKey($key)
{
$this->_consumerKey = $key;
return $this;
}
// Getter function
public function getConsumerKey()
{
return $this->_consumerKey;
}

Categories