-1

I am not too much familiar with PHP, but I wonder how to ask for an input inside a function in PHP ? With python it would be for example:

def F(q) :
    a = raw_input(q) // how to do this inside a function with PHP?
    // do something with a
    return something 

print F("how bla bla bla ?")
print F("What bla ?")
print F("When bla bla ?")

I am not sure how to ask for an input inside a function (each time it is called) since we need to define a form and get the value using an $_POST['aaa'] for example !

I have tried to do this but I don't know if it is the right way, because what I want is to ask for the input inside the function (each time it is called).

<form action="index.php" method="post">
    Name:  <input type="text" name="answer" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

<?php
function F($q)
{
    echo $q;
    $a = $_POST['answer']; // a = raw_input(q)
    $ret = strcmp($a, 'y') == 0 ? 1 : 0;
    return $ret;
}

echo F("how bla bla bla ?")
echo F("What bla ?")
echo F("When bla bla ?")
eLearner
  • 325
  • 6
  • 18
  • I'm voting to close this question as off-topic because Stack Overflow is *not* a code translation service. You are expected to try to **write the code yourself** and then if you have a problem you can **post what you've tried** with a **clear explanation of what isn't working**. – John Conde Aug 06 '15 at 20:49
  • @JohnConde I have edited my question to add what I have tried. – eLearner Aug 06 '15 at 20:53
  • Thank you. Close vote retracted. :)\ – John Conde Aug 06 '15 at 20:54
  • You get the error because the `$_POST` is not populated. Do a check to see if the form has been submitted first. When the form submits I think this would work. – chris85 Aug 06 '15 at 20:54
  • @chris85 yes sure, but I want the user to input the value of a only if the function is called, so I don't think that testing if $_POST['answer'] isset inside the function, is the right way. – eLearner Aug 06 '15 at 20:57
  • @iam-decoder the $_POST is not yet populated what should the function return then ?! It is not clear for me how to get the equivalent behaviour to the python function that I provided which simply asks for the input inside the function. – eLearner Aug 06 '15 at 21:02
  • @eLearner I just looked up what raw_input() does, PHP won't be able to do that because PHP is all parsed prior to the user seeing anything. you should look into Javascript's [`prompt()`](http://www.w3schools.com/jsref/met_win_prompt.asp) function. – iam-decoder Aug 06 '15 at 21:10
  • Ok thank you, I will see the prompt() function in js then, it seems more convenient. – eLearner Aug 06 '15 at 21:12
  • @iam-decoder and is it possible to get the result returned by prompt() in a PHP variable to be able to use it in $ret = strcmp($result, 'y') == 0 ? 1 : 0; ?! – eLearner Aug 06 '15 at 21:19
  • @eLearner you would need to make an ajax request passing the input in the post array, it might be easier to recreate the `strcmp()` function in javascript. – iam-decoder Aug 06 '15 at 21:28
  • I need to use PHP since I need to save the result later in a mysql database, so doing all in JS is not the best solution for me. – eLearner Aug 06 '15 at 21:32
  • then use javascript to create the prompt, then make an ajax request to a php script with the user's input, done-deal! – iam-decoder Aug 06 '15 at 21:34
  • @iam-decoder can you please add a simple example of that to your answer ? Thanks – eLearner Aug 06 '15 at 21:50
  • @eLearner took a long time, but I updated my answer – iam-decoder Aug 06 '15 at 22:32
  • @RyanVincent therefore how can I have the equivalent of the code that I show in my question ? Please provide an answer with an equivalent example. Thanks – eLearner Aug 07 '15 at 09:44
  • My bad - since PHP runs server side there is no way to pause the server-side script and get input from the client with PHP. – Ryan Vincent Aug 07 '15 at 17:49
  • @RyanVincent so there is no way to have an equivalent code to that one, in php. – eLearner Aug 07 '15 at 17:52

3 Answers3

0

The problem you have is that PHP is evaluated before html is, since you don't have anything to "exclude" the function prior to the user hitting the submit button, it's parsing the whole thing and throwing error on the fact that the $_POST array is empty, more specifically, that the 'answer' key doesn't exist inside of $_POST.

to fix your problem with $_POST having an undefined index of 'answer' simply make it wait until the $_POST array has been populated by the submitted form:

Assuming this file is index.php:

<form action="index.php" method="post">
    Name:  <input type="text" name="answer" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

<?php
function F($q)
{
    echo $q;
    $a = $_POST['answer']; // a = raw_input(q)
    $ret = strcmp($a, 'y') == 0 ? 1 : 0;
    return $ret;
}

if(isset($_POST['submit'])){
    F("ha ha ha ?")
}

I don't know what raw_input() does in python, but this will help solve your indexing issue to get you back on track to translating it.

EDIT

(sorry for the delay, took a little while to write this all out) as requested, here's an example of how your process could work:

index.php

<input id="send_request" type="submit" name="submit" value="Submit me!" />
<div id="result"></div>
<script>
var obj_merge = function(a, b, e){
    var c={},d={};
    for(var att in a)c[att]=a[att];
    for(var att in b){if(e&&typeof c[att]==='undefined'){d[att]=b[att];}c[att]=b[att];}
    if(e)c={obj:c,extras:function(){return d;}};
    return c;
};
var serialize_obj = function(data, str){
    if(!str) str = "";
    if(data){
        for(var i in data){
            if(typeof data[i] === 'object') str += serialize_for_post(data[i], str);
            else str += (str.length <= 0) ? i+"="+data[i] : "&"+i+"="+data[i];
        }
    }
    return str;
};
var do_ajax = function(input_config){
    var default_config = {
        url: null,
        req_type: 'GET',
        async: true,
        data: null,
        callback: null
    };
    var config = obj_merge(default_config, input_config);
    if(typeof config.url === 'undefined') return false;

    if(config.data){
        config.data = serialize_obj(config.data);
        if(config.req_type.toUpperCase() === 'GET'){
            config.url = config.url+"?"+config.data
        }
    }

    var xmlhttp;
    if (window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest(); // IE7+, FFx, Chr, Opa, Safi
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5 & IE6
    }
    if("withCredentials" in xmlhttp){
        xmlhttp.open(config.req_type,config.url,config.async);
    } else if(typeof XDomainRequest != "undefined"){
        xmlhttp = new XDomainRequest();
        xmlhttp.open(config.req_type,config.url);
    } else {
        xmlhttp = null;
    }
    if(!xmlhttp){
        console.log("CORS Support Missing.");
        return false;
    }
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState === 4){
            if(typeof config.callback === 'function'){
                config.callback(xmlhttp.responseText, xmlhttp);
            } else {
                console.log(xmlhttp);
            }
        }
    };
    xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    if(config.req_type.toUpperCase() === 'POST'){
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send('POST&'+config.data);
    } else {
        xmlhttp.send();
    }
};

document.getElementById('send_request').onclick = function(event){
    var result = prompt("Enter Something");
    do_ajax({
        url: "ajax_page.php",
        data: {"answer": result},
        req_type: "POST",
        callback: function(response){
            var json_data = JSON.parse(response);
            var output = json_data ? "" : response;
            if(output.length === 0 && json_data){
                for(var key in json_data){
                    output += key+": "+json_data[key]+"<br />";
                }
            }
            document.getElementById('result').innerHTML = output;
        }
    });
};
</script>

ajax_page.php

<?php
function F($a){
    return strcmp($a, 'y') == 0 ? 1 : 0;
}
if(!empty($_POST) && array_key_exists('answer', $_POST)){
    $result = F($_POST['answer']);
    /*
     * DO SOMETHING WITH $result
     */
    echo json_encode(array('status' => true, 'result' => $result));
    die;
} else {
    echo json_encode(array('status' => false, 'error' => 'No answer was provided'));
    die;
}
echo json_encode(array('status' => false, 'error' => 'Something went wrong, sorry about that!'));
die;
iam-decoder
  • 2,554
  • 1
  • 13
  • 28
0

You can do this with the command line version of php (PHP cli getting input from user and then dumping into variable possible?), but otherwise you need to use form submission (or possibly Ajax).

Community
  • 1
  • 1
Robin Andrews
  • 3,514
  • 11
  • 43
  • 111
-1

After reading the comments on your post i think is about: statefull (Python) and stateless (PHP). A website works from request to request and python programms start once and ends once. So you have to do more kompex code logic in php as in python to get the same done.

Hope that helps.