0

OK, so I've searched HIGH and LOW for something VERY simple in PHP and get nothing that works.

I'v been here: http://php.net/manual/en/function.parse-url.php

and I've tried these functions in 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;
}

and as you see, the INCOMING URL has only got two PARAMS: firstname and email like so:

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();
}

Then I tried this function (NOTED ABOVE that populates $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;
}

And again I get just the message with the "TEXT" in quotes.... this stuff is right from PHP.net.

Here's my querystring coming from AJAX like this:

        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');

        });

It's going INTO the php file but like this:

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

All I want to do is this:

$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);

Where $fname and $email are the values from the querystring. Thoughts?

Peter The Angular Dude
  • 1,112
  • 5
  • 26
  • 53

1 Answers1

2

What you are looking for is parse_str

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

outputs:

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

Demo: http://codepad.viper-7.com/pQ7Bx6

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
  • Been there done that from PHP.NET and no joy! It's NOT splitting off the querystring as I displayed it above with the %40 for the "@" symbol and if you notice, the AJAX is pushing the string with a "&" sign for both Params vice the "?" mark for the "first" param. I'm not that much in PHP but can muddle my way around pretty well. All I know is that parse_str is not happening and the result is NULL in Google's console. – Peter The Angular Dude May 18 '15 at 15:33
  • You mean this: void parse_str ( string $str [, array &$arr ] ) – Peter The Angular Dude May 18 '15 at 15:34
  • First, the start of a query string is not `?`. That is the separator between the uri and the query string. The query string starts *after* the question mark. Second, stuff like the `%40` is the url encoded entity for `@`. parse_str should run [urldecode()](http://php.net/urldecode) on each name/value which would decode that. The first function you posted is missing a `urldecode()` call which with it would pretty much be exactly what parse_str does. Third, as you see above, it always returns null because it takes the second argument by reference. – Jonathan Kuhn May 18 '15 at 15:44
  • Jonathan, you da man!!! I love information and especially a teacher who knows his/her craft. Thank you sir! – Peter The Angular Dude May 18 '15 at 15:53