如何解析PHP URL Querystring并获取param值

时间:2015-05-18 15:26:22

标签: php ajax

好的,所以我在PHP中搜索了一些非常简单的HIGH和LOW,并且没有任何效果。

我来过这里:http://php.net/manual/en/function.parse-url.php

我在PHP中尝试过这些函数:

function parse_query($var)
{
  /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = parse_url($var, PHP_URL_QUERY);
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val)
   {
    $x          = explode('=', $val);
    $arr[$x[0]] = $x[1];
   }
  unset($val, $x, $var);

  print "Name: " . $arr[0] . "\n";
  print "Email: " . $arr[1] . "\n";

  return $arr;
}

如您所见,INCOMING URL只有两个PARAMS:firstname和email就像这样:

if (isset($_POST['dataObj'])) {
    $json = $_POST['dataObj'];

    var_dump(json_decode($json, true));

    $strJSON = proper_parse_str($json);
    $strJSON1 = parse_query($json);

    echo "Here's the JSON OBJ: " . $strJSON;
    echo "Here's the JSON OBJ with a simple parser: " . $strJSON1;

} else {

    echo json_encode(
            array("data" => $errors,
                "success" => false,
                "errMsg" => "Oh, Snap! The Data coming in died!",
                "errNbr" => "500"));
    exit();
}

然后我尝试了这个函数(注意上面填充$ strJSON。

function proper_parse_str($str) {

    print $str . "\n\n";

    # result array
    $arr = array();

    # split on outer delimiter
    $pairs = explode('&', $str);

    # loop through each pair
    foreach ($pairs as $i) {
        # split into name and value
        list($firstname, $value) = explode('=', $i, 2);
        list($email, $value) = explode('=', $i, 2);

        # if name already exists
        if (isset($arr[$firstname]) and isset($arr[$email])) {
            # stick multiple values into an array
            if (is_array($arr[$firstname]) and is_array($arr[$email])) {
                $arr[$firstname][] = $value;
                $arr[$email][] = $value;
            } else {
                $arr[$firstname] = array($arr[$firstname], $value);
                $arr[$email] = array($arr[$email], $value);
            }
        }
        # otherwise, simply stick it in a scalar
        else {
            $arr[$firstname] = $value;
            $arr[$email] = $value;
        }
    }

    # return result array
    return $arr;
}

我再次用引号中的“TEXT”得到消息....这个东西来自PHP.net。

这是来自AJAX的我的查询字符串:

        var formData = {
            "firstname": $('input[name=firstname]').val(),
            "email": $('input[name=email]').val()
        };
        formData = $(this).serialize() + "&" + $.param(formData);

        var headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
            'Access-Control-Allow-Headers': 'Content-Type',
            //'Content-Type': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        }

        $.ajax({
            url: "webServices/saveCommInfo.php",
            type: "POST",
            crossDomain: true,
            headers: headers,
            //async: false,
            //jsonpCallback: 'jsonpCallback',
            //dataType: 'json',
            //cache: false,
            //encode: true.
            data: {"dataObj": formData}

        }).success(function (data) {

            console.log("This is coming back from the server: ", data);

            // ALL GOOD! just show the success message!
            $('form').append('<div id="success" class="alert alert-success">' + data.status + '</div>');

            // Success message
            $('#success').html("<div class='alert alert-success'>");
            $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
            $('#success > .alert-success').append("<strong>You joined... Welcome!</strong>");
            $('#success > .alert-success').append('</div>');
            //clear all fields
            $('#contactForm').trigger("reset");
            console.log('AJAX SUCCESS!');

        }).complete(function (data, textStatus, jqXHR){

            console.log('AJAX COMPLETE');

        });

它正在进入php文件但是像这样:

&firstname=John&email=john%40someemail.net

我想做的就是:

$sqlA = "INSERT INTO " . $sTable . " (fname, username, password, active, datCreated, userCreated, email, newUser)
            VALUES ('" . $fname . "','" . $username . "','" . $password . "',0,'" . date("Y-m-d") . "','webformuser','$email','" . $_SESSION['sessionid'] . "',1)";

    $result = mysqli_query($con, $sqlA);

其中$ fname和$ email是查询字符串中的值。想法?

1 个答案:

答案 0 :(得分:2)

您要找的是parse_str

$queryString = "test=1&foo=bar";
parse_str($queryString, $out);
echo '<pre>'.print_r($out, 1).'</pre>';

输出:

Array
(
    [test] => 1
    [foo] => bar
)

演示:http://codepad.viper-7.com/pQ7Bx6