PHP - Pass $_post Variables To Function
Hello everyone,
Can someone show me a way how to pass $_post variable from a form to a function? So, input username and input password to a function login($username, $password). Similar TutorialsI have the array defined and print_r (outside the function is show what I need...) However, I need to somewhay pass those three arguments - name, price, shipping (keys & values) into the "all_products" function and assign (inside the function) each element to a variable {name, price, shipping}. Code: [Select] function all_products($key,$value) { # This is where I'm lost - I know the values are passed to the function but how to I assign them to below variable? echo "$name"; echo "$price"; echo "$shipping"; // Products array defined to send values into "all_products" function & loop to display item name & individual pricing (using WHILE LOOP) $products = array('Product1' => array ( 'name' => 'item one', 'price' => '30.00', 'shipping' => '0.00'), 'Product2' => array ( 'item two', 'price' => '19.50', 'shipping' => '0.10'), 'Product3' => array ( 'item three', 'price' => '21.99', 'shipping' => '0.10') ); while (list($keys, $values) = each($products)) { while (list($k, $v) = each($values)) echo "Checking Looped Data Outside Function: <strong>$k: </strong> $v<br/>"; # echo "<pre>"; # print_r($value); # echo "</pre>"; # Trying to send array elements into "all_products" function & echo (name, price, shipping) keys and values inside that function all_products($k,$v); } Ok- I have seen it go both ways on this forum and I was wondering which is correct- or more secure. I have a script that receives $_POST variables from a form. Which is better- to change the name of the $_POST variable to do script manipulations or to simple do them with the $_POST['whatever'] $whatever = $_POST['var_from_form']; or simply utilize $_POST['var_from_form'] I know it would be less typing changing it to $whatever, but does it really matter? And yes- register_globals is off. Cheers- I'm building a form using ajax that will allow users to add additional rows to their submissions. The problem however is getting PHP to recognize those variables. So that if the user submits 5 rows, it reads and creates a variable for all 5. I'm pretty sure that doing this will involve some form of while() processing and a total row count, but I'm unsure how to name the variables on the form end and how to receive those into PHP without the script erroring out. Suggestions? I was thinking something along the lines of naming each variable something like "number_title" or as an example "5_title." Then using a while function to pull the data from $_POST[$number.'_title']; or something similar, but I'm unsure if that method would even work. foreach ($_POST as $key => $value){ // Handle escape characters, which depends on setting of magic quotes if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1){ $value = urlencode(stripslashes($value)); } else { $value = urlencode($value); } $req .= "&$key=$value"; } $reg is not returning anything. Hello Masters I need to iterate through multiple $_POST[''] variables that have been submitted by a form, from the user, checking to see if they have been set or left unfilled. Having a tough time finding a tutorial online... I am a php noob... So I though that I would assign short variable names to the $_POST variables and put them into and array(with names for keys) , then use a for loop and isset() to echo any variable's key in which its value has not been set to the user. I have found out that I can not use variables as array values.... What is the best way to do this? Thanks to you in advance sirs. I have the following loop in which I receive Parse error: $letters = array ("A", "B", "C", "D","E", "F", "G", "H","I", "J", "K", "L", "M", "N", "O", "P","Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "Æ", "Ø", "Å"); for ($i = 1; $i < 29; $i++) { if ($_POST['$letters['$i']']){ echo "You have selected the following products:" . "<br>" . $_POST['$letters['$i']]; } } or is it possible to write something like that: for ($i = 1; $i < 300; $i++) { if ($_POST['$i']){ echo "You have selected the following products:" . "<br>" . $_POST['$i']; } } Please, help me. I need to use array and variables inside _POST[]. I have a php search page that takes form data to create its queries, then reload the original search page. The form is long, so there are numerous $_POST's to convert to variables for use in the query. I've looked at "extract" and a few other code snippets. But it's a form and I don't want any security issues. I'm hoping there's a "foreach" solution, but I'm a beginner. What's a proper way to to simplify this: $s1 = $_POST["s1"]; $s2 = $_POST["s2"]; $s3 = $_POST["s3"]; $s4 = $_POST["s4"]; $s5 = $_POST["s5"]; $s6 = $_POST["s6"]; $s7 = $_POST["s7"]; $s8 = $_POST["s8"]; $s9 = $_POST["s9"]; $s10 = $_POST["s10"]; $s11 = $_POST["s11"]; $s12 = $_POST["s12"]; i hav this url n whenever i click on this url i get som mssg send on my mobile i hav a form whose code is Code: [Select] <form action="formprocess.php method="post"> telephone<input type="text name="telephone> <input type="submit" name="submit"> </form> i want to send telephone as parameter to this url so whenever user enters his telephone he gets d mssg after clicking on submit.....but i hav no idea how to do tht...help me somone plssssssss http://www.abc.in/smsapi/sendsms.php?sendto=9987234123&msg=your Hi guys, I have got a problem with the if variable statements. When I insert the text of the image location, the name of the strings and when I did not insert the username, all I get this: Code: [Select] image, strings or username are missing Username or password are missing. It should not display with the "Username or password are missing.", only the "image, strings or username are missing". The area of the code i am working on: if($image == '' && $strings == '' && $username == '') { $errmsg_arr[] = 'image, strings or username are missing'; $errflag = true; } elseif($username == '' && $password == ''){ $errmsg_arr[] = 'Username or password are missing.'; $errflag = true; } <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'myusername'); define('DB_PASSWORD', 'mypassword'); define('DB_DATABASE', 'mydbname'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $image = clean($_GET['image']); $strings = clean($_GET['strings']); $username = clean($_GET['user']); $pass = clean($_GET['pass']); $delete = clean($_GET['delete']); if($image == '' && $strings == '' && $username == '') { $errmsg_arr[] = 'image, strings or username are missing'; $errflag = true; } elseif($username == '' && $password == ''){ $errmsg_arr[] = 'Username or password are missing.'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['image'])) { $insert[] = 'image = \'' . clean($_GET['image']) . '\''; } if(isset($_GET['strings'])) { $insert[] = 'strings = \'' . clean($_GET['strings']) . '\''; } if(isset($_GET['user'])) { $insert[] = 'username = \'' . clean($_GET['user']) .'\''; } if(isset($_GET['pass'])) { $insert[] = 'pass = \'' . clean($_GET['pass']) . '\''; } if(isset($_GET['delete'])) { $insert[] = 'delete = \'' . clean($_GET['delete']) . '\''; } if (count($insert)>0) { $names = implode(',',$insert); if(isset($image) && ($strings) && ($username)) { echo "test"; } elseif($username && $delete == 'all') { if ($delete != NULL) { mysql_query("DELETE FROM user_list WHERE username='$username'"); $deleted = mysql_affected_rows(); if($deleted > 0) { echo("The data are now deleted"); } else { echo("The user's data is empty"); } }else{ echo("failed"); } mysql_close($link); } } } ?> Do anyone know how i can get pass on those methods if I enter the images, the name of the strings and the username or the or the username with the password? I am trying to build a website, whe
1) User logs in (UserA)
2) Inserting a name in the search box and pressing "Search", a list of all users matching that name is shown
3) The user selects a user (UserB) from that list (among several results)
4) By selecting the user (UserB) , a message box appears to insert text
5) The user(UserA) types the message
6) The user(UserA) presses the SUBMIT button and sends the message to the other user(UserB)
The problem i face is how to pass the variables from my PHP script to the JavaScript script. Its easy for me to get the values of input fiedls, select fields or any other DOM element value. But if the value i need to pass to Javascript file to perform an AJAX call isnt inside a DOM element, how do i do it?
For example, for me to determine the user that will send the message (userA), i will need several data. This data, i have them inside the PHP script as variables, but dont know how to pass them to Javascript file.
Getting the data from the URL, or from a hidden input field or any other DOM element, is a solution, but i want to know the way that is safer and better.
To summarize:
[PHP Script with necessary data]-->[pass necessary data from PHP to JavaScript file]-->[perform an AJAX call] --> [return data to PHP Script]
How do i do it?
Thanks in advance.
Hello I have this login page with code Code: [Select] <?php header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 session_start(); //Below means if session database server crdentials is not set, require to use/set that connection then if (!isset($_SESSION['SESSION'])) require ( "../db_connection.php"); if($_SESSION['LOGGEDIN'] == TRUE) { header("Location: account.php"); exit; } $_SESSION['FORM_SUBMITTED'] = ""; $CRLF = chr(13).chr(10); $user_id = ""; if (isset($HTTP_GET_VARS["user_id"])) $user_id = $HTTP_GET_VARS["user_id"]; if ($user_id == '') { if (isset($_SESSION['user_id'])) $user_id = $_SESSION['user_id']; } //Validations $flg = ""; $error = ""; if (isset($HTTP_GET_VARS["flg"])) $flg = $HTTP_GET_VARS["flg"]; switch ($flg) { case "yellow": $error = "<font class=\"txt_main_str12_mar\"><BR>Your Account Has Not Been Verified.<BR>Check your email for Activation Instructions.<br>Click <a href=\"/courses/forgot_login.php\">here</a> to have the activation email resent.</font>"; break; case "red": $error = "<font class=\"txt_main_str12_mar\"><BR>That userid/password combination is not in our database.<br>Please Try Again.</font>"; break; case "blue": $error = "<font class=\"txt_main_str12_mar\"><BR>Your Session has Expired.<br>Please Login Again.</font>"; break; default: $error = " <br>"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login Page</title> <script language="JavaScript"> <!-- function loadedPage() { } function submitForm() { if (isEmpty(document.forms[0].user_id.value)) { alert("Please enter your UserID."); bSubmit = false; return false; } if (isEmpty(document.forms[0].password.value)) { alert("Please enter your Password."); bSubmit = false; return false; } document.forms[0].submit(); } //--> </script> </head> <body><center><br /><br /> <form name="form1" method="post" id="form1" action="/php/sessions/login/login_processing.php"> <table> <tr> <td>User ID</td> <td><input type="text" name="user_id" id="user_id" value="<?php echo $user_id ?>" size="24" maxlength="30" /></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" id="password" size="24" maxlength="30" /></td> </tr> <tr> <td> </td> <td><input type="submit" name="Submit" value="Submit" onclick="submitForm();" /></td> </tr> </table> </form> </center> </body> </html> and login processing page with code Code: [Select] <?php header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 session_start(); //Below means if session database server crdentials is not set, require to use/set that connection then if (!isset($_SESSION['SESSION'])) require ( "../db_connection.php"); // reset session variables... $_SESSION['user_id'] = ""; $_SESSION['LOGGEDIN'] = false; $_SESSION['EMAIL'] = ""; $_SESSION['FNAME'] = ""; $_SESSION['LNAME'] = ""; // initialize variables... $user_id = ""; $password = ""; $email = ""; // make sure post parameters were sent... if (isset($HTTP_POST_VARS["user_id"])) $user_id = addslashes($HTTP_POST_VARS["user_id"]); if (isset($HTTP_POST_VARS["password"])) $passwd = addslashes($HTTP_POST_VARS["password"]); $_SESSION['user_id'] = $user_id; // form variables must have something in them... if ($user_id == "" || $password == "") { header("Location: ./login_page.php?flg=yellow&user_id=".$user_id); exit; } ?> I'm having problem with the last piece of code above, it's redirecting me eventhough I have entered a value on the userid and password from the login page... Hello, I am new to PHP and would like to know what I am doing incorrectly. I have designed a login form which contains two variables: the username and the password. So for the username: <input type="hidden" name="email" id="email" value="example_username"> And for the password: <input type="password" name="password" id="password" size="15"> I then created a php script which I want to pass the variables "email" and "password" to the e-mail address: <?php { $message = "$email"; $message2 = "$password"; mail ("email@myserver.com", "Hello", $message, $message2); } ?> This should happen through the command: <action="http://www.myserver.com/myscript.php" method="post"> All I get is a blank email with the subject "Hello". Why are the email and password variables not being passed to my email by the php script? Thanks. I have a form, where I'm collecting registration info - like name, address, email, password. I'm calling another php file at server side code, where it will check whether the email exists or not. Pretty simple, just receiving those post variables and check with the database. The issue, if I find a match, I want to go back to the registration.php page, using the following code: if ($email_already_use == "y") { $_SESSION['ERROR'] = "Error"; $_SESSION['MESSAGE'] = "This email address already used. Please try another"; header("location: ".$settings['site_url']."registration.php"); exit; } Now, I would like to place the user input at the registration.php file, but I do not want to use pass variable at URL like this: header("location: ".$settings['site_url']."registration.php?".name=$name&address=$address&email=$email; Is there anyway, I can retrieve those variables at registration.php, without specifying .name=$name&address=$address&email=$email ? Thanks for your help. I see some sites has similar implementation, but did not find anything like how to do it. I have a search page that then submits to a php page that queries the database. I've been struggling to figure out how to paginate it, but I think I've narrowed down the problem. I didn't realize $_POST results didn't pass through when people clicked the pagination links at the bottom. I verified this by replacing the LIKE variable with a specific word and it worked. I'm trying to learn how to set up sessions, thinking this might solve my problem. Doesn't seem to be working. Can I get some suggestions on how to do this? What's happening now is that it's pulling a random 8 pages that have nothing to do with the original query. I start my entire page with: Code: [Select] <?php session_start(); $_SESSION['leafshape'] = $_post['select1']; $_SESSION['leafcolor'] = $_post['select2']; $_SESSION['leafvein'] = $_post['select3']; $_SESSION['leafmargin'] = $_post['select4']; $leafshape = $_SESSION['leafshape']; $leafcolor = $_SESSION['leafcolor']; $leafvein = $_SESSION['leafvein']; $leafmargin = $_SESSION['leafmargin']; and I'm setting up the queries like this: Code: [Select] $query = "SELECT COUNT(*) as num FROM descriptors JOIN plantae ON (descriptors.plant_id = plantae.plant_name) WHERE descriptors.leaf_shape LIKE '{$_SESSION['leafshape']}' AND descriptors.leaf_venation LIKE '{$_SESSION['leafvein']}' AND descriptors.leaf_margin LIKE '{$_SESSION['leafmargin']}'"; I also tried replacing the '{$_SESSION['leafshape']}' in the query with the assigned variable $leafshape Before, if I wanted to send a welcome letter when a user registers i'd do this. $body = "<inserted html code>"; mail('email@email.com', 'Subject', $body, $headers); Now that I am advancing in PHP, I was trying a different method, because when I did the above method, I would have to take all the HTML out of the variable to change something, like an image link, etc... I have tried doing another method, where I can actually leave all the HTML code in a separate file, so that I can easily edit it, and tried 3 things... This one works, but it doesn't pass variables: $body = file_get_contents("emailTemplate.inc.php"); mail('email@email.com', 'Subject', $body, $headers); When I do this one, the page actually just shows on the current page (naturally): $body = include("emailTemplate.inc.php"); mail('email@email.com', 'Subject', $body, $headers); Of course, this has the same effect as the include function: $body = require("emailTemplate.inc.php"); mail('email@email.com', 'Subject', $body, $headers); So my question is, how do I send a formatted HTML email, and pass variables to it, so I can personalize it by the persons name, etc, without adding the HTML to a variable, and so that I can easily update the page whenever I want, and without taking it out of the variable, and sticking back in the edited code? Any help would be appreciated! I would also like to say that I am using this code for the $headers variable too: $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: from@email.com <email@email.com>' . "\r\n"; Thank you in advanced! I want to query a database (search) and pass the desired columns from the search results to another page like so: Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user require('auth.php'); if (isset($_POST['submit'])) { // Connect to the database. require_once ('config.php'); //Query the database. $sql = "SELECT* FROM members INNER JOIN images ON members.member_id = images_member_id WHERE members.ethnicity = '{$_POST['ethnicity']}'"; $query = mysql_query($sql); if(mysql_num_rows($query) > 0){ while(($row = mysql_fetch_assoc($query)) !== false) { //Redirect to search results page. header("Location: search_results.php?friend='.$row['member_id'].'&me='.$_SESSION['id'].' &pic='.$row['image'].'&name='.$row['username'].'"); } } else { //If no results found. echo 'No results match this search query.' ; } } ?> I get the following error when i try to run the page (by submitting a form from another page which executes this page): Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/a4993450/public_html/profile_search.php on line 31 The culprit line is this one: header("Location: search_results.php?friend='.$row['member_id'].'&me='.$_SESSION['id'].' &pic='.$row['image'].'&name='.$row['username'].'"); As you can see, I eliminated all white space between the variables and concatenations, thinking that that was the problem but I keep getting the error message. I'm at a loss about what to do next. Any help? Hello, its a bit difficult to explain the issue that I have but I will try my best. I have this small code $message = $_POST['message1']; in my php code and message1 is the name of a textarea in my page. i also have another textarea called message2 in my page. what I need to do is to use the message1 and message2 in the $message = $_POST function. For example: $message = $_POST['message1'] + $_POST['message2'] or anything that is acceptable in PHP coding and works in PHP. I hope I havent confused you guys and you undersstood what I mean... Thanks Hi, I was going to through a PHP tutorial, and came across a form validation user defined function . Below is an example.. Code: [Select] function check_required_fields($fields){ $field_errors = array(); foreach ($fields as $requried_fields) { if (!isset($_POST[$requried_fields]) || (empty($_POST[$requried_fields]) && $_POST[$requried_fields] != 0)) if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { $errors[] = $requried_fields; } } return $field_errors; } When the user defined function was called they added an $_POST and the end of the user defined function. Here is a the code snipped of how it looks Code: [Select] $errors = array(); // perform validations on the form data $required_fields = array('username', 'password'); $errors = array_merge($errors, check_required_fields($required_fields, $_POST)); If the validation can be preformed with out the $_POST, why bother inserting it? Thanks! I have a basic form for collecting data, I have a function for collecting the ip address of the visitors unfortunately I cannot get the ip collection working with the rest of the form once I put the if($_POST['emailaddress']) {.........} in. My aim is once the user has completed the form, data gone to MySQL database that the data will then be printed via the echo statements on to the form as the action sends it back to the same page. Currently my code is <?php /* This script is a form handler, each section is commented as to what it does. 1. connects to the database (see connect.php). 2. it gets the users ip address. 3. Strips tags from the data entered so that no malicious code can be entered and corrupt/cause problems with the database or site. 4. Inserts the relevant data into the database in this case it is the ip, haveemail, emailaddress, browser, otherbrowser, resolution, otherresolution. 5. Sends the data just entered by the user back to the screen so they can see what they entered */ // 1. connection to MySQL require ("php/connect.php"); // if this script is unavailable then the rest of the code is pointless as need a connection to the database. // if fields are completed if($_POST['emailaddress']) { // if this field has had data entered then process the data // 2. collect ip address //$ip = getRealIpAddr(); // 3. Strips tags and POST variables from the form $haveemail = strip_tags($_POST['haveemail']); $emailaddress = strip_tags($_POST['emailaddress']); $browser = strip_tags($_POST['browser']); $otherbrowser = strip_tags($_POST['otherbrowser']); $resolution = strip_tags($_POST['resolution']); $otherresolution = strip_tags($_POST['otherresolution']); // 4. insert data to dbase $query="INSERT INTO datacollection1 (id, ip, haveemail, emailaddress, browser, otherbrowser, resolution, otherresolution) VALUES ('Null', '$ip', '$haveemail', '$emailaddress', '$browser', '$otherbrowser', '$resolution', '$otherresolution')"; // Null is in the id field as this is added automatically in the database as it is set to auto increment upon an entry going in and is primary key. // message to say if database has been updated mysql_query($query) or die (mysql_error()); //echo "<b>Your IP address is: $ip</b> <br />"; /*function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } */ // 5. displays information on form to advise what the user just entered echo '<br/>'."The database has just been updated with the following information: ".'<br/><br/>'; // echo "Your ip address is ".$ip.'<br/>'; echo "You answered ".$haveemail." to having an email address.".'<br/>'; echo "Your email address is ".$emailaddress.'<br/>'; echo "You use ".$browser." to browse the internet".'<br/>'; echo $otherbrowser.'<br/>'; echo "Your screen resolution is set at ".$resolution.'<br/>'; echo $otherresolution.'<br/>'; echo "Now you have completed this form, please follow onto the main form, this form seeks to get your valuable opinion regarding your likes and dislikes of the websites researched."; } mysql_close($db); // closes the database, this is good practice but the database will close once stopped running. ?> I have tried moving the function outside of the if($_POST['emailaddress']) but it still didnt get the ip address. Just as a side note everything else works, the data is written into the database bar the ip address. I would appreciate some help Thanks in advance. |