Doing an inline if in the action of a form - php

I need to redirect the user to a site that gets the "Short_proj_name" information. So i did this:
<form action="Main.php?short_proj_name=<?=$_REQUEST['short_proj_name']?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
However, upon searching, i found out that there are several reasons NOT to use $_REQUEST, one of them being security and all that. However, simply doing $_POST['short_proj_name'] or $_GET['short_proj_name'] never returns the information i need.
Basically, how would i go about doing an if statement that checks if the $_GET is empty, and does a $_POST instead? Can i do that in the action method of my form?
EDIT:
Adittionally, is it possible that maybe using both $_POST and $_GET return null, yet using $_REQUEST doesnt? As far as i know, $_REQUEST is both get and post together, but none of them returns any information
It works if i do it as so:
if(!empty($_POST['short_proj_name']))
{
$projName = $_POST['short_proj_name'];
}
elseif (!empty($_GET['short_proj_name']))
{
$projName = $_GET['short_proj_name'];
}
else
{
$projName = $_REQUEST['short_proj_name'];
}
But i'm not sure if that solves the security problem at all

I think the answer here is to always use _GET.
A form can actually send both _GET and _POST data based on what you use in the "action" attribute of the form. The action part doesn't care what you set the "method" attribute as.
From what you are showing above, the params are all in the "action" part of the form so these are always passed into _GET anyway. If the inputs were inside the form then those would be received via _POST
Here's an example.
In PHP I would receive $_GET['monkey'] = '1' and $_POST['lion'] = 1
<form method='post' action='receive.php?monkey=1'>
<input type='text' name='lion' value='1' />
<input type='submit' />
</form>
There shouldn't really ever be an instance where you need to check if the answer is in _GET or _POST and as mentioned in a comment, it's quite a security risk to use $_REQUEST or check if it's in _GET or _POST.
Most times, you can just push the page request URL back into the form "action" to ensure all the same _GET params are included on the form _POST.
The big mistake most people do is try to move them from _GET into hidden input fields inside a form thinking they need to do that to carry all that data through.
However, this type of function call might help you but I wouldn't approve of it.
function getRequestParam($param){
if(isset($_GET[$param])){return $_GET[$param];}
if(isset($_POST[$param])){return $_POST[$param];}
return "";
}

you can like
<?php
if(!empty($_POST))
{
$projName = $_POST['short_proj_name'];
}
else
{
$projName = $_GET['short_proj_name'];
}
?>
<form action="Main.php?short_proj_name=<?=$projName ?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
but i think it's ugly

Here is a simple code :
<?php
if (isset($_GET) && $_GET['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else if (isset($_POST) && $_POST['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else
echo $_REQUEST['short_proj_name'];
?>
But if you get the value from a post or get, it can be anything so be careful...
If the "short_proj_name" is a file name, a nasty person can get access to other files just by guessing their names...

Related

I can only pass my $_GET variable to the header() method after sumitting the form (POST method)

Good morning, afternoon or night :D
I want to pass my $_GET['area'] variable to a method, but after submitting the form, it only let me pass such variable to the header() method:
Note: This is the variable from the URL I want to pass: /index.php?area=work
I have a index.view.php with a button:
<a href="crearArt.php?area=<?php echo $_GET['area'] ?>" >Add new article</a>
From the URL, the button receives the $_GET['area'] and when I click the button it takes me to the area where I can create new articles, here is the code of crearArt.view.php file:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
//... Bunch of inputs
<button type="submit" name="crearArticle">Create New Content</button>
</form>
When I click on "Create New Content" (submitting the form), the crearArt.php file should get the $_GET['area'] variable and pass it to the $addDataToDB() method but that doesn't happens, if I put a print_r() inside the if condition to check if the variable it doesn't show the variable.
Furthermore, if I pass the variable to the header() method it does work, meaning that (I think) the variable still there.
Here the crearArt.php file
<?php
$inputNames = [];
$inputValues = [];
if(isset($_POST['crearArticle'])){
// Get all inputs from the form
foreach($_POST as $key => $value){
if($key !== 'crearArticle'){
// This will NOT add the button' name property when the form gets submitted
array_push($inputNames, $key);
array_push($inputValues, $value);
};
};
// Add values to WorkDB || CodeDB
$addDataToDB($inputNames, $inputValues, $_GET['area']);
// Return to index.php?area=??
header('Location: index.php?area='.$_GET['area']);
} // END MAIN IF
?>
Sumerizing, when I press on "Create New Content" it should pass the variable to $addDataToDB() but it doesn't do it, even though the URL has the $_GET['area'] var with it: /crearArt.php?area=work
Question:
Is there a way to get this variable without creating hidden inputs in the crearArt.view.php?
Thanks in advance
PS: I'm new into PHP.
In addition
I tried creating a var outside the if conditional and then passing it to the method but that doesn't work either.
By using that variable I'm gonna let the function "know" from which area I come from so the function "know" to which database it has to refer to.
If I use variable as a string ('work'), it does work.
Each HTTP request you make has its own URL.
The request you make to crearArt.php?area=<?php echo $_GET['area'] ?> and the request you make to <?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?> are different requests with different query strings and will have different values in $_GET.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>"
According to the manual, PHP_SELF is:
The filename of the currently executing script, relative to the document root.
You haven't put a query string in your URL.
When you submit the form $_GET['area'] won't exist.

can't be able to understand $_post in codeigniter

using codeigniter mvc pattern I create form in view that take only two values form user
<form action="<?php base_url(); ?> blogs/new_post" method="POST">
<label>Title</label>
<input type="text" name="post_title" />
<label>discription</label>
<input type="text" name="post_detail" />
<input type="submit" value="post" />
</form>
now when i submit the form, data goes to the controller now here confusion created in my code that i can't able to understand i use three cases in controller fist is if i use !empty($_POST) in controller and in view weather i fill the form or not fill the form message displayed in controller is post
my question is why always displaying post why not displaying not a post when i fill nothing in the form
if(!empty($_POST)) {
echo "post";
} else {
echo "not a post";
}
my second question is same related to the first condition now i use isset instead of !empty
public function new_Post() {
if(isset($_POST)) {
echo "post";
} else {
echo "not a post";
}
}
in this case either i fill form or not fill form when i submit the form the result always same that is "post"
and in third case if i use !isset the the result is always not a post eiter i fill or not fill the form
hope so you will understand my problem when i comes to if(!empty($_POST)) this condition then my mind is confuse what is the purpose of $_post
This is because you are using the whole global variable $_POST to check empty and isset(). $_POST is not empty when you click on the button. You just Print_r the $_POST it will have the value of submit button. You need to print the value of $_POST on click and see the values in the array
Well, in CodeIgniter (and most of the framework) doesn't allow you to access $_POST directly due to security reason.
You must access $_POST values through $this->input->post()
For more information read Input Class from CodeIgniter's docs
https://www.codeigniter.com/user_guide/libraries/input.html
$_POST is exist when you click on the button:
so empty and isset cant work Correctly
the value at the first is
Array
(
)
SO U should check
if($_POST)
instead
if(!empty($_POST)) OR if(isset($_POST))
AND best way is u check
if ($this->input->post())

Possible to manipulate $_POST variable in php script and express it in another php script?

I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();

Refresh page without losing the Post value

How do I maintain the $post value when a page is refreshed; In other words how do I refresh the page without losing the Post value
This in not possible without a page submit in the first place! Unless you somehow submitted the form fields back to the server i.e. Without Page Refresh using jQuery etc. Somesort of Auto Save Form script.
If this is for validation checks no need for sessions as suggested.
User fills in the form and submits back to self
Sever side validation fails
$_GET
<input type="hidden" name="first"
value="<?php echo htmlspecialchars($first, ENT_QUOTES); ?>" />
validation message, end.
alternatively as suggested save the whole post in a session, something like this, but again has to be first submitted to work....
$_POST
if(isset($_POST) & count($_POST)) { $_SESSION['post'] = $_POST; }
if(isset($_SESSION['post']) && count($_SESSION['post'])) { $_POST = $_SESSION['post']; }
You can't do this. POST variables may not be re-sent, if they are, the browser usually does this when the user refreshes the page.
The POST variable will never be re-set if the user clicks a link to another page instead of refreshing.
If $post is a normal variable, then it will never be saved.
If you need to save something, you need to use cookies. $_SESSION is an implementation of cookies. Cookies are data that is stored on the user's browser, and are re-sent with every request.
Reference: http://php.net/manual/en/reserved.variables.session.php
The $_SESSION variable is just an associative array, so to use it, simply do something like:
$_SESSION['foo'] = $bar
You could save your $_POST values inside of $_SESSION's
Save your all $_POST's like this:
<?php
session_start();
$_SESSION['value1'] = $_POST['value1'];
$_SESSION['value2'] = $_POST['value2'];
// ETC...
echo "<input type='text' name='value1' value='".$_SESSION['value1']."' />";
echo "<input type='text' name='value2' value='".$_SESSION['value2']."' />";
?>
Actually in html forms it keeps post data.
this is valuble when you need to keep inserted data in the textboxes.
<form>
<input type="text" name="student_name" value="<?php echo
isset($_POST['student_name']) ? $_POST['student_name']:'';
?>">
</form>
put post values to session
session_start();
$_SESSION["POST_VARS"]=$_POST;
and you can fetch this value in another page like
session_start();
$_SESSION["POST_VARS"]["name"];
$_SESSION["POST_VARS"]["address"];
You can use the same value that you got in the POST inside the form, this way, when you submit it - it'll stay there.
An little example:
<?php
$var = mysql_real_escape_string($_POST['var']);
?>
<form id="1" name="1" action="/" method="post">
<input type="text" value="<?php print $var;?>"/>
<input type="submit" value="Submit" />
</form>
You can use file to save post data so the data will not will not be removed until someone remove the file and of-course you can modify the file easily
if($_POST['name'])
{
$file = fopen('poststored.txt','wb');
fwrite($file,''.$_POST['value'].'');
fclose($file);
}
if (file_exists('poststored.txt')) {
$file = fopen('ipSelected.txt', 'r');
$value = fgets($file);
fclose($file);
}
so your post value stored in $value.

use php to change a html elements inner text

I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.

Categories