Setting POST variable without using form

PhpHtmlPost

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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

$_POST['text'] = $var;

on next.php?

Solution 3 - Php

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

Solution 4 - Php

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondennissView Question on Stackoverflow
Solution 1 - PhpSarfrazView Answer on Stackoverflow
Solution 2 - PhpRakwardView Answer on Stackoverflow
Solution 3 - PhpbcoscaView Answer on Stackoverflow
Solution 4 - Phpjoan16vView Answer on Stackoverflow