post method not working on condition - php

I have created a page on which a form posts its value. So I add some lines to get those values like
$parameter = mysqli_real_escape_string($con,$_POST['Parameter']);
But when I open that page without that form it shows Notice that
Undefined index parameter in page on line.
So I want to make something like if I post the values then only specific area will work.
Otherwise remaining area will work just like if condition.
For ex.
if(post)
{}
else
{}
How can I do this?

First you would need to check if the values are set properly..You can do it with the if condition which would be like
if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
// do the things after form processing
}else{
//things you want to do after form breaks.
}

Use isset() to check
if(isset($_POST['Parameter'])){
//desired tasks
//$parameter = mysqli_real_escape_string($con,$_POST['Parameter']);
}else{
//other task
}

You can use isset() function. In your case if should be like
if(isset($_POST['param']))
{
//Do something
}
else
{
//Do something else
}

Related

change body of if statement based on its condition

Here is my question
I have a class say ABC and a function XYZ defined inside it and that function is returning something based on the above logic in it.
class ABC {
function XYZ{
..........
.......
return "--- ";
}
}
Now there is an object on another page of this class which calls this method.
$z= new ABC;
if( $z->XYZ() )
{
some output
}
else{
another output
}
My problem is i dont have access to PAGE 2. but i need to change the output of else statement. I have only access to class ABC because i am overriding it in a module. so, in short i can only alter function XYZ. Whats the solution??
If its of any significance, i am working on MAGENTO ECOMMERCE Platform and class is a block class and page 2 is a template
You can alter the output html with an observer with the http_response_send_before event.
Capture the html and do your stuff.
You have a good explanation here
I hope this can help you
you can also do as follow :
<?php
ob_start();
// do your stuff
// ...
// here you capture all the output that it is generated by your scripts
$v = ob_get_contents();
// alter the value of $v by detecting if it should be changed. you can user regex for example to
// detect and update
// ...
// here you clean all data stored in buffer
ob_clean();
// and put the updated data in buffer
print $v;
// end of buffer operations
ob_end_flush();
?>
hope it helps,
You need a way to differentiate PAGE1 from PAGE2, lets say by the URL if it's possible. So you would have to change your method that will check on which page is currently and according to it, it will change the output, but you must write the output in the method itself instead of writing it in the template.
class ABC {
function XYZ {
$result = $this->getResult(); //Helper method to get the result.
if ($result) {
//Do something when result is true.
} else {
$url = $this->checkUrl(); //Check URL of the page.
if ($url == PAGE2) { //If you are on PAGE2
//Do something specific for the PAGE2
} else {
//Do something for all other pages
}
}
}
}
I know it's not the perfect solution, but I hope it will help you somehow.
The page number has to be specified somewhere in the $_GET or the $_POST array (or in another query). Check that variable and implement the alternative logic.

Replace die statement

Currently my code looks like this
<?php
if($controlSomething) {
include(header);
echo "something";
include(footer);
die();
}
if($anotherControl) {
include(header);
doSomeOperations(); // would throw an error if $controlSometing is true
echo "something else";
include(footer);
die();
}
?>
Clearly this is not a good way to do things. I want to move to something cleaner.
I created a view class to wrap the page and avoid the include(header)/include(footer) repetition. I also converted all the conditional statement, changing if($condition) into function condition ().
Now what should I do ? I was thinking of something like this :
if(condition1()) { message for condition1 ...}
else if(condition2()) {}
The problem is that this file might be included by another file that will be executed because there is no die statement anymore.
So should I include a var like "Die" in the view object and check its value before doing anything on every page ? This doesn't seem clean to me.
I have thousands of lines of code like this so the more simple/automated the solution, the better.

How I can keep variable in controller/action after form has been invalid (population)?

Got action with one waiting for parameter , and to run this action I need always one param. But also in this action I doing validation for other form and after this my first variable always disappears.
How I can keep this $var after isValid?
public function myAction(){
if ($this->getRequest()->isPost() || $this->getRequest()->getParam('number')){
//this is where got my number
$number = $this->getRequest()->getParam ('number');
//and use to display site.
if ($this->getRequest()->isPost()){
if($commentForm->isValid($this->getRequest()->getPost())){
//if I get Valid data I do upload or etc.
} else {
//but if form is inValid won't display everything one more time.
//but **$number is now Null**.
$this->view->data = $tUser->getCommentAndUserByTelephone($number);
$this->view->commentForm = $commentForm;
}
}
}
}
How I can keep this $number without repost?
You can try storing it with sessions.
http://www.w3schools.com/php/php_sessions.asp
$_SESSION['numbers'];
Pass that number to view $this->view->number = $number; and resend it instead of a new number. Simple!

A better way to check if a user were logged in and generate like dislike link

I have a script that takes some 500 rows from a table, and based on whether or not a user is logged in, generates a link to like or dislike the item.
The way it currently goes is like this:
//Select * from table;
//while(){
if($userLogged)
{
echo $row['columnName'].' Like - Dislike';
}else{
echo $row['columnName'];
}
}
This way, it checks if a user is logged at each and every row. $userLogged is set in a file that's included on this page.
What would be a better way to do this instead of checking if a user were logged in inside the loop for each and every row?
Not getting your question quiet well but I think you want to prevent condition each time you loop so you can check the condition first and than loop accordingly, example
if($userLogged) {
while(condition) {
}
} else {
while(condition) {
}
}
This way you don't have to check the condition inside the loop each time it loops
Use sessions here
session_start();
if(isset($_SESSION['userLogged']))
{
echo $row['columnName'].' Like - Dislike';
}else{
echo $row['columnName'];
}
If the code for the like and dislike is identical for each entry then you could do something like this.
$links = ($userLogged)?"Like - Dislike":"";
while (condition){
echo $row['columnName'].$links;
}

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

Categories