60
votes

Is there a way to set a $_POST['var'] without using form related field (no type='hidden') and using only PHP. Something like

$_POST['name'] = "Denniss";

Is there a way to do this?

EDIT: Someone asked me for some elaboration on this. So for example, I have page with a form on it, The form looks something like this

<form method='post' action='next.php'>
<input type='text' name='text' value='' />
<input type='submit' name='submit' value='Submit'/>
</form>

Once the submit button is clicked, I want to get redirected to next.php. Is there a way for me to set the $_POST['text'] variable to another value? How do I make this persistent so that when I click on another submit button (for example) the $_POST['text'] will be what I set on next.php without using a hidden field.

Let me know if this is still not clear and thank you for your help.

4
You mean in the server code or from the client side when a user access some page? - Felix Kling
Can you elaborate what you are trying to do? cURL might be an option, sessions maybe another option. Too vague to give an exact answer. - Jimithus
What? And why do you not want to use a hidden field? That's what they're for. - Mark Snidovich
It's not that I do not want to use them. I just want to know whether there is a way to do it without using hidden field. - denniss
You cannot persist data between page accesses without using a session or cookies. Every variable that you set in page a.php will be lost when page b.php is accessed. It seems you want to use a certain way to do something although this way is not suitable for the problem. - Felix Kling

4 Answers

90
votes

Yes, simply set it to another value:

$_POST['text'] = 'another value';

This will override the previous value corresponding to text key of the array. The $_POST is superglobal associative array and you can change the values like a normal PHP array.

Caution: This change is only visible within the same PHP execution scope. Once the execution is complete and the page has loaded, the $_POST array is cleared. A new form submission will generate a new $_POST array.

If you want to persist the value across form submissions, you will need to put it in the form as an input tag's value attribute or retrieve it from a data store.

6
votes

If you want to set $_POST['text'] to another value, why not use:

$_POST['text'] = $var;

on next.php?

4
votes

you can do it using ajax or by sending http headers+content like:

POST /xyz.php HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

userid=joe&password=guessme
1
votes

You can do it using jQuery. Example:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<script>
    $.ajax({
        url : "next.php",
        type: "POST",
        data : "name=Denniss",
        success: function(data)
        {
            //data - response from server
            $('#response_div').html(data);
        }
    });
</script>