SitePoint Sponsor

User Tag List

Results 1 to 15 of 15
  1. #1
    SitePoint Wizard WorldNews's Avatar
    Join Date
    Nov 2007
    Posts
    1,033
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    How to do Redirect in PHP with POST and not GET

    Hello,

    How can one redirect in PHP via the Post method rather than method GET?

    That is I know of this redirect and use it often:

    Code PHP:
    header('Location: [url]https://www.xyz.com/page1.php?check=10);[/url]

    but this results in page1.php displaying the variable value pairs exposed to the public.

    How can one do a redirect in php with method POST so that the variable and
    value are not publicly exposed.

    Regards,

    Anoox search engine volunteer

    www.anoox.com

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,578
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You can't, but you can request the page and show its output?

    PHP Code:
    echo file_get_contents("https://www.xyz.com/page1.php?check=10"); 

  3. #3
    SitePoint Member
    Join Date
    Apr 2009
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You cant redirect page with post values in php.

    If you want then you have to use javascript as most sites are doing (if you have seen paypal or other sites saying "wait for 5 seconds".).

    You can do it as below.

    <form name='fr' action='redirect(.)php' method='POST'>
    <include type='hidden' name='var1' value='val1'>
    <include type='hidden' name='var2' value='val2'>
    </form>
    <script type='text/javascript'>
    document.fr.submit();
    </script>

    This will post all variables to redirect(.)php.

    I hope this will help you.

  4. #4
    SitePoint Wizard WorldNews's Avatar
    Join Date
    Nov 2007
    Posts
    1,033
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Greetings,

    And thanks for your response.

    Some questions:
    1- why is there a . in the redirect(.)php?

    2- Are you saying that I create a form as you have below in the page from which I want to redirect to another page with the data sent via Post and not Get? Sorry, I am not following!

    Regards,

    Quote Originally Posted by osmasters View Post
    You cant redirect page with post values in php.

    If you want then you have to use javascript as most sites are doing (if you have seen paypal or other sites saying "wait for 5 seconds".).

    You can do it as below.

    <form name='fr' action='redirect(.)php' method='POST'>
    <include type='hidden' name='var1' value='val1'>
    <include type='hidden' name='var2' value='val2'>
    </form>
    <script type='text/javascript'>
    document.fr.submit();
    </script>

    This will post all variables to redirect(.)php.

    I hope this will help you.

    Anoox search engine volunteer

    www.anoox.com

  5. #5
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think redirect(.)php was typed to overcome sitepoints restriction on posting urls for new members. redirect.php is what was intended.

    And yes, you're essentially outputting a form which will submit via post to a different url, because there is no reliable way to get a browser to send a post request automatically aside from javascript. If the user has javascript enabled, then javascript will submit the form immediately upon page load. Otherwise, the user will need to submit the html form manually, so you should provide a message for them to do so.

    Be aware that the user can still see the values in the form if they view the html source, and so they can obviously manipulate them if they wanted.

  6. #6
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Location
    Ljubljana, Slovenia
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If it's on the same server, you can use session to store values, but.

    header function is used to send HTTP/1.1 specification header, so it should be possible to POST data by using it. There is many thinks you can do with header
    http://si2.php.net/manual/en/function.header.php

    try this:

    PHP Code:
    <?php
    $host 
    "www.example.com";
    $path "/path/to/script.php";
    $data "data1=value1&data2=value2";
    $data urlencode($data);

    header("POST $path HTTP/1.1\r\n" );
    header("Host: $host\r\n" );
    header("Content-type: application/x-www-form-urlencoded\r\n" );
    header("Content-length: " strlen($data) . "\r\n" );
    header("Connection: close\r\n\r\n" );
    header($data);
    ?>
    Gregor Grajzar, web developer
    http://xweblabs.com
    http://grajzar.info

  7. #7
    SitePoint Wizard WorldNews's Avatar
    Join Date
    Nov 2007
    Posts
    1,033
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Ok, thanks for your ideas.
    I think I will stick to storing the data in SESSIONS and passing
    them along this way and sticking with Header to call other pages via
    the Get method.

    Cheers

    Quote Originally Posted by gregor171 View Post
    If it's on the same server, you can use session to store values, but.

    header function is used to send HTTP/1.1 specification header, so it should be possible to POST data by using it. There is many thinks you can do with header
    http://si2.php.net/manual/en/function.header.php

    try this:

    PHP Code:
    <?php
    $host 
    "www.example.com";
    $path "/path/to/script.php";
    $data "data1=value1&data2=value2";
    $data urlencode($data);

    header("POST $path HTTP/1.1\r\n" );
    header("Host: $host\r\n" );
    header("Content-type: application/x-www-form-urlencoded\r\n" );
    header("Content-length: " strlen($data) . "\r\n" );
    header("Connection: close\r\n\r\n" );
    header($data);
    ?>

    Anoox search engine volunteer

    www.anoox.com

  8. #8
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Location
    Ljubljana, Slovenia
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think I will stick to storing the data in SESSIONS and passing
    The secure way. Never should you trust data from post or get even if you "think" that you send it.
    Gregor Grajzar, web developer
    http://xweblabs.com
    http://grajzar.info

  9. #9
    SitePoint Wizard WorldNews's Avatar
    Join Date
    Nov 2007
    Posts
    1,033
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Yes, OK.
    So Sessions is the way to pass all data, and not Get or Post.

    BTW, do you think that one should always set a Session value to Null
    after using it. I mean is this better for computer CPU & Memory performance
    on server and/or client side?

    Regards,

    Quote Originally Posted by gregor171 View Post
    The secure way. Never should you trust data from post or get even if you "think" that you send it.

    Anoox search engine volunteer

    www.anoox.com

  10. #10
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you're sure you won't need the variable anymore, then yes unset() will reduce memory and cpu resource costs. But, unless the variable contains some very large amount of data, this is insignificant. I would more focus on using unset() on session variables for purposes of making your application work properly.

    Be aware though that storing certain things in sessions can break the users ability to browse your site using multiple browser windows. Storing multipage form data in sessions is definately convenient for the programmer, but be aware of this drawback that actions performed in one window may affect the other window because they share the same session data. Sometimes it's desired, sometimes not.

  11. #11
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Location
    Ljubljana, Slovenia
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry but I always tend to complicate thinks. Before you do it read something about Session Fixation and Hijacking:
    http://phpsec.org/projects/guide/4.html
    Gregor Grajzar, web developer
    http://xweblabs.com
    http://grajzar.info

  12. #12
    SitePoint Wizard WorldNews's Avatar
    Join Date
    Nov 2007
    Posts
    1,033
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    BTW, is it better to do use unset() or just set the SESSION to = null?
    I mean which one of these is better:

    unset($_SESSION['xyz'])
    or
    $_SESSION['xyz'] = null

    Regards,

    Quote Originally Posted by crmalibu View Post
    If you're sure you won't need the variable anymore, then yes unset() will reduce memory and cpu resource costs. But, unless the variable contains some very large amount of data, this is insignificant. I would more focus on using unset() on session variables for purposes of making your application work properly.

    Be aware though that storing certain things in sessions can break the users ability to browse your site using multiple browser windows. Storing multipage form data in sessions is definately convenient for the programmer, but be aware of this drawback that actions performed in one window may affect the other window because they share the same session data. Sometimes it's desired, sometimes not.

    Anoox search engine volunteer

    www.anoox.com

  13. #13
    SitePoint Enthusiast
    Join Date
    Apr 2009
    Location
    Ljubljana, Slovenia
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think this is philosophy question
    there is also session_unset that unsets all session variables.

    I use null a lot, since I found wired case in OOP when after unseting it, the class was still there. but null will set it's value to null and not destroy variable where unset() will destroy a variable.

    Since we have a kind of Garbage collector this doesn't matter. Use the one, that fits best to your code on. Perhaps unset would fit best and test it with isset.

    I use null mostly for killing classes, but I always use a destructor method if needed. I've learned this in .net world.
    Gregor Grajzar, web developer
    http://xweblabs.com
    http://grajzar.info

  14. #14
    SitePoint Wizard WorldNews's Avatar
    Join Date
    Nov 2007
    Posts
    1,033
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Yes, I agree.
    So I think I will stick with $_SESSION['xyz'] = null

    Good day

    Quote Originally Posted by gregor171 View Post
    I think this is philosophy question
    there is also session_unset that unsets all session variables.

    I use null a lot, since I found wired case in OOP when after unseting it, the class was still there. but null will set it's value to null and not destroy variable where unset() will destroy a variable.

    Since we have a kind of Garbage collector this doesn't matter. Use the one, that fits best to your code on. Perhaps unset would fit best and test it with isset.

    I use null mostly for killing classes, but I always use a destructor method if needed. I've learned this in .net world.

    Anoox search engine volunteer

    www.anoox.com

  15. #15
    SitePoint Zealot
    Join Date
    May 2003
    Location
    Sarasota, FL
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In some cases you find it neccessary to intercept a POSTed page and redirect the user AND data. One example maybe that a user has submitted a form, but their login has expired and you need to reauthenticate them first. Another example could be purely for debugging purposes where you want to redirect a request after a long set of debugging output. In both case, you can use this set of functions:

    PHP Code:
    /*---------------------------------------------
    common functions file for PHP (1.5.6) [partial]
    Created: 2004 by Chris Bloom [ chrisbloom7[AT]gmail[DOT]com ]
    Last Updated: 2008-05-03
    ---------------------------------------------*/

    if (!defined('POSTBACK_PARAMETER_PREFIX')) define('POSTBACK_PARAMETER_PREFIX','__postback__');

    /**
     * Generates a redirect statement based on current state of output/headers
     *
     * @access private
     * @param mixed $targetURL Optional complete URL to redirect to. If not specified, returns false.
     * @param mixed $dataArray Optional array of name=>value parameters to pass along.
     * @param boolean $pauseBefore Optional flag. Useful for debugging - will force to redirect by manual form/POST.
     * @return null Result dependant on redirect method. May be a JavaScript redirect string if output has already started.
     *   Otherwise, PHP headers will be added directly. Processing will halt directly after in either case.
     */
    function redirect($targetURL false$dataArray false$pauseBefore false) {
        if (!
    strlen($targetURL)) return false;

        
    $search '';
        if (
    strrpos($targetURL,'#') !== false) {
            list(
    $targetURL,$search) = explode('#',$targetURL);
        }
        if (
    strlen($search)) $search '#'.rawurlencode($search);

        if (
    strrpos($targetURL,'?') !== false) {
            list(
    $targetURL,$extraParams) = explode('?',$targetURL);
            
    $extraParams explode('&',$extraParams);
            foreach (
    $extraParam as $name => $value) {
                
    $dataArray[$name] = $value;
            }
        }
        if (
    is_array($dataArray)) $dataArray array_merge($dataArray);

        if (
    $pauseBefore !== false) {
            
    redirectByForm($targetURL.$search,$dataArray,true,false);
        }
        else {
            
    $sep '?';
            foreach (
    $dataArray as $name => $value) {
                
    $targetURL .= $sep.rawurlencode($name).'='.rawurlencode($value);
                
    $sep '&';
            }
            if (!
    headers_sent()) {
                
    session_write_close();
                
    header('Location: '.$targetURL.$search);
                exit();
            }
            else {
                echo 
    "<script type=\"text/javascript\" language=\"javascript\">window.location.replace('".addslashes(htmlentities($targetURL.$search))."');</script>";
                
    session_write_close();
                exit;
            }
        }
    }

    /**
     * Outputs a form to use in request redirection. May submit automatically if browser allows.
     *
     * @access private
     * @param mixed $targetURL Complete URL to redirect to.
     * @param mixed $dataArray Optional array of name=>value parameters to write as input fields.
     * @param boolean $redirectByPost Optional flag. Useful for debugging - will force to redirect by manual form/POST instead of form/GET.
     * @param boolean $autoSubmit Optional flag. Adds an onload javascript directive to submit form automatically.
     * @return null Outputs an HTML form set and terminates script execution.
     */
    function redirectByForm($targetURL$dataArray false$redirectByPost true$autoSubmit true) {
        if (!
    strlen($targetURL)) return false;
        
    $method = (($redirectByPost === true) ? 'post' 'get');

        
    $search '';
        if (
    strrpos($targetURL,'#') !== false) {
            list(
    $targetURL,$search) = explode('#',$targetURL);
        }
        if (
    strlen($search)) $search '#'.rawurlencode($search);

        if (
    strrpos($targetURL,'?') !== false) {
            list(
    $targetURL,$extraParams) = explode('?',$targetURL);
            
    $extraParams explode('&',$extraParams);
            foreach (
    $extraParam as $name => $value) {
                
    $dataArray[$name] = $value;
            }
        }
        if (
    is_array($dataArray)) $dataArray array_merge($dataArray);
        echo 
    '<html><body'.(($autoSubmit == true) ? ' onload="document.forms[0].submit()"' '').'><form method="'.$method.'"'.
            
    ' action="'.htmlentities($targetURL.$search).'">';
        
    writeHiddenFormFields($dataArray);
        echo 
    '<input type="submit" name="'.POSTBACK_PARAMETER_PREFIX.'submit" value="Continue" /></form></body></html>';
        
    session_write_close();
        exit;
    }
    /**
     * Outputs values from the dataArray as hidden form field elements.
     *
     * @param array $dataArray Array of name=>value pairs to output. Nested arrays are processed recursively.
     * @param mixed $clean_array Optional parameter used to trim off array elements that start with specified string. Ignored if false.
     * @param string $id_prefix Optional string to append to beginning of element names when used as element ID attribute
     * @return null Outputs hidden HTML <input> fields directly
     */
    function writeHiddenFormFields($dataArray$clean_array false$id_prefix '') {
        if (!
    is_array($dataArray)) return false;
        if (!
    sizeof($dataArray)) return true;
        if (
    $clean_array) {
            
    $dataArray array_clean($dataArray$clean_array);
        }
        foreach (
    $dataArray as $name => $value) {
            
    // repeat any POST params verbatim (except for the login page's internal POST params)
            // If this page is included by another page as a result of password timeout,
            // we want to preserve the GET or POST in progress

            // POST param name doesn't begin with $loginParamPrefix? Include it as a hidden form item.
            
    if (is_array($value)) {
                foreach (
    $value as $name2 => $value2) {
                    
    writeHiddenFormFields(array("{$name}[{$name2}]" => $value2), $clean_array$id_prefix);
                }
            }
            else {
                echo 
    '<input type="hidden" name="'.htmlentities($name).'" id="'.htmlentities($id_prefix.preg_replace('/[^0-9a-z\-_]/i','_',$name)).'" value="'.htmlentities($value).'" />'."\n";
            }
        }
    }

    function 
    intercept_request($targetURL$returnURL) {
        
    $targetURL = (($targetURL) ? $targetURL 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']);
        
    $returnURL = ((strlen($returnURL)) ? $returnURL false);

        if (
    $_SERVER['REQUEST_METHOD'] == 'POST') {
            
    $dataArray array_clean(array_merge($_GET$_POST), POSTBACK_PARAMETER_PREFIX);
            
    $dataArray[POSTBACK_PARAMETER_PREFIX.'return_method'] = 'post';
            if (
    $returnURL$dataArray[POSTBACK_PARAMETER_PREFIX.'return'] = $returnURL;
            if (
                
    strpos($_SERVER['CONTENT_TYPE'],'multipart/form-data') === 0
                
    &&
                isset(
    $_FILES)
                &&
                
    sizeof($_FILES)
            ) {
                
    //set error message to be displayed on the next page.
                
    $dataArray[POSTBACK_PARAMETER_PREFIX.'error'] = 'Your login expired before the form could be submitted. After signing in you will need to upload the file again.';
            }
            
    redirectByForm($targetURL,$dataArray);
        } else {
            
    $dataArray $_GET;
            if (
    $returnURL$dataArray[POSTBACK_PARAMETER_PREFIX.'return'] = $returnURL;
            
    redirect($targetURL,$dataArray);
        }
    }

    function 
    array_clean ($array$todelete false$caseSensitive false) {
        
    //removes elements from an array by comparing the value of each key
        
    foreach($array as $key => $value) {
            if(
    is_array($value)) {
                
    $array[$key] = array_clean($array[$key], $todelete$caseSensitive);
            }
            else {
                if(
    $todelete) {
                    if(
    $caseSensitive) {
                        if(
    strstr($key ,$todelete) !== false) {
                            unset(
    $array[$key]);
                        }
                    }
                    else {
                        if(
    stristr($key$todelete) !== false) {
                            unset(
    $array[$key]);
                        }
                    }
                }
                elseif (empty(
    $key)) {
                    unset(
    $array[$key]);
                } 
    //END: if($todelete)
            
    //END: if(is_array($value))
        
    //END: foreach
        
    return $array;

    Examples of use:
    PHP Code:
    function require_login($returnURL false) {
        if (!
    is_logged_in()) {
            
    $returnURL = (($returnURL) ? $returnURL 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']);
            
    intercept_request('http://'.$_SERVER['SERVER_NAME'].'/login.php',$returnURL);
        }
        else {
            
    //user is logged in -> reinitialize every few minutes just in case any user data has changed since
            
    if ((time() - $_SESSION[SESSION_NAME]['user']['last_initialized']) > (60*5) || getParam('refresh') == 1) { //check at least once every 5 minutes
                
    return reinit_user();
            }
        }

    PHP Code:
    // Redirect to confirmation
    $dataArray = array(
        
    'id' => $id,
        
    'confirm' => 'add',
    );
    if (
    getParam('add_auto') == 1$dataArray['add_auto'] = 1;
    if (
    $gDebug$dataArray['debug'] = 1;
    redirect($_SERVER['PHP_SELF'], $dataArray$gDebug); 
    Last edited by xangelusx; Apr 21, 2009 at 15:53. Reason: Adding examples
    Chris Bloom
    Web Application Developer


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •