PHP - Function - Validate Ip Address And Return Errors
HI guys
I have vreated a site and am now trying to validate the ip address i have created a function but am failing to get it to work i need to add the errors to add to the errors array but instead it keeps resetting and leaving me with the last error that is returned any help would be greatly appreciated im a newbie so if i can understand the concept behind whats happening it will be of great benefit Thanks Sean heres the code // Function validateIpaddress($address,$record,$errors) // { // if ($address !=="" or $address !=="ip_address") // { // Print_r($address); // echo "<br><br>"; // $fullstoppos = strpos(($address), "."); // echo "strpos = $fullstoppos"; // $fullstoppos2 = strpos(($address), ".", $fullstoppos+1); // echo "strpos2 = $fullstoppos2"; // $fullstoppos3 = strpos(($address), ".", $fullstoppos2+1); // echo "strpos3 = $fullstoppos3"; // } // if ($fullstoppos !==4 && $fullstoppos2 !==9 && $fullstoppos3 !==14) // { // $errors[] = "<br><font color='red'>Please correct the following.Or contact your client manager for assitance.<br>* $record is a required field.An ip address is a 16 digit numerical value. </font>"; // } // } $errors = validateIpaddres($_POST['destinationPoint'],A/AAAA record, $errors) Similar TutorialsWhere should I validate the return value?
In the function should I validate the value before returning it.
Or once the value has been returned, should I check it?
Is it really necessary to validate the return value?
Thank you.
I want to make the form so only people with a specific email address can sign up to the site. So for example their ending email address was.... @something.apple.biz.com .. but to be accepted into the site, the email HAS to end with apple.biz.com. How could you validate it so it matches something specific like this. Here is my code at the moment which just checks that their is at least one . after the @ for it to be an acceptable email. If anyone could say what else to add to do this would be great if($email != '' && $register){ $emailcheck = explode("@", $email); $sql = "SELECT email FROM member WHERE email='$email'"; $query = mysql_query($sql); $emails = mysql_num_rows($query); if($emails != 0 ){ $alert .= '<p class="alert" style="clear:both;">That email address has already been registered</p>'; $register = false; }elseif(count($emailcheck) != 2){ $alert .= '<p class="alert" style="clear:both;">Please enter a valid email address</p>'; $register = false; }elseif(count($emailcheck) == 2){ $emailchecktwo = explode(".", $emailcheck[1]); if(count($emailchecktwo) < 2){ $alert .= '<p class="alert" style="clear:both;">Please enter a valid email address</p>'; $register = false; } } } Hey all, having a very odd problem Ive never encountered. I am trying to send mails via PHP's built in mail function. I set the From and Reply-To like so: Code: [Select] <?php $headers = "From: noreply@contractortraining.energy.gov\r\n"; $headers .= "Reply-To: noreply@contractortraining.energy.gov\r\n"; Now here is when things get weird. When this email sends the return email gets changed to noreply@doe.golearnportal.org. Oddly enough it only happens when the From is "contractortraining.energy.gov". For example: If I send with these headers the email comes in as doe.golearnportal.org However if I change the headers to be something like "sometest.org" or "nowhere.golearnportal.org" or anything other than "contractortraining.energy.gov" it will come through using the specified headers. It is only when I use "contractortraining.energy.gov" that the headers get changed. Any ideas what could be responsible for this type of behavior? I dont think its a PHP issue at the moment, and this code is working successfully on several other servers. //my php code sample <?php include_once('con.php'); if(isset($_POST['username'])){ $message = []; if(empty($_POST['username'])){ $message['username'] = 'username required'; } #some validation continue... $data = $_POST['username']; if (count($errors) === 0){ #ccode... $message['username'] = 'success your name saved'; } } ?> //my jquery ajax $('.username').click(function() { $.ajax({ url: 'user.php', method: 'POST', data: $('.user').serialize(), success: function(data) { swal('Wow!','success message from php','success'); }, error: function(data) { swal('Oops!','error message from php','error'); } }); return false; });
Hello, I need function or something which check valid or not url. This function: function validateurl($url){ return preg_match('/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i', $url); } supports http://www.google.com or http://google.com , but doesn't support www.google.com ... How I can do Validate Url function, which will support http://www.google.com , http://google.com , and www.google.com ? Best Regards, Tadas 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. Hi, I've put together a callback request form that emails my client when someone fills it out. the form is as follows Code: [Select] <form method="post" action="php/callbackform.php"> Name: <input name="name" type="text" /><br /> Phone number: <input name="phone" type="text" /><br /> no: <input type="checkbox" name="no" value="This customer does not want their information to be used for marketing purposes" /><br /> <input type="submit" /> </form> it posts to this code Code: [Select] <?php $name = $_REQUEST['name'] ; $phone = $_REQUEST['phone'] ; $optout = $_REQUEST['no'] ; $message = $phone . " " . $optout; mail( "client@example.com", "Call back form request", $message, "From: $name" ); header( "Location: http://www.example.com/index.php" ); ?> The problem is that when the email is received, the email 'from' field shows my servers default email address. So if someone called bob filled out the form the resulting email would show as; From: bob<default@myserver.com> My client doesn't want to add an email box to use as the from address so is there anyway i can hide my address being included in the email header? thanks Richard let say i have a function function checkme($x) { if(strlen($x)>10) { return $x; } else { return false; } } $variable=checkme("5"); so two questions i wish to ask... 1. If i wish to get the empty string for the $variable, then is it correct to have return false there? 2. If it is true that return shall not be used twice in a function as it will somehow reduce bytes space or something like that?? thanks in advance Hi, i got this function to get the wordCount that i store in a tabel: Code: [Select] function getWordCount($word) { $query = "SELECT count FROM uniqueWords WHERE word='$word'"; $data = execQuery($query); return $data; } Only it returns an array, what i want is to have it return a integer, how can i do that? Hi all, can you give me suggestion how to return value from function like this Code: [Select] function returnArray(){ for($i=1; $i<=3; $i++){ return $i; //how to return this as array?? } } when I code "echo" inside the function then call the function it give me output => 123 but when I code "return" inside the function, it will give output => 1 Can you suggest me how to output it as array? Hi,Dear Frnds...........................I Hope U r all fine. I am using php.Here is the problem in the Return array from function. This is the code. Code: [Select] <?php $store = array(); $test = get_my_links(); print_r($store); function get_my_links() { $my_array = array('e','f','g'); foreach($my_array as $key=> $list) { $store[] = $list; } return $store; } ?> Suppose the array is maked dynamically. please help me..THANKS... Please help me fix these errors in my function. Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in Code: [Select] function verify_user_fanned_company($uid, $cid) { $uid = (int)$uid; $sql = " SELECT `company_id` FROM `company_fans` WHERE `user_id` = {$uid} AND `company_id` = {$cid} "; $query = mysql_query($sql); $result = mysql_result($query, 0); $num = mysql_num_rows($result); if ($num === 1) { return true; } } Code: [Select] <?php $is_fanned = verify_user_fanned_company($user_info['uid'], $info["companyid"]); if ($is_fanned = true) { ?> do stuff <?php } ?> Hi, I'm trying to output some details from my database, along with a BLOB image. At the moment I'm having some warnings and notices and I don't know how to solve them. Here's the warnings and notices: Notice: Undefined index: id in G:\xampp\htdocs\xampp\dsa\search_func.php on line 38 Notice: Undefined variable: terms in G:\xampp\htdocs\xampp\dsa\search_func.php on line 13 Warning: mysql_query() expects parameter 2 to be resource, object given in G:\xampp\htdocs\xampp\dsa\search_func.php on line 16 Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in G:\xampp\htdocs\xampp\dsa\search_func.php on line 22 Notice: Trying to get property of non-object in G:\xampp\htdocs\xampp\dsa\search_func.php on line 27 Notice: Trying to get property of non-object in G:\xampp\htdocs\xampp\dsa\search_func.php on line 27 Notice: Trying to get property of non-object in G:\xampp\htdocs\xampp\dsa\search_func.php on line 27 Notice: Trying to get property of non-object in G:\xampp\htdocs\xampp\dsa\search_func.php on line 27 Notice: Trying to get property of non-object in G:\xampp\htdocs\xampp\dsa\search_func.php on line 28 Notice: Trying to get property of non-object in G:\xampp\htdocs\xampp\dsa\search_func.php on line 28 Notice: Trying to get property of non-object in G:\xampp\htdocs\xampp\dsa\search_func.php on line 28 Here's the function code: Code: [Select] <?php /* return the details of an employee parameter empno - employee number eg empHTML.php?empno=7521 This is very basic e.g no error checking */ function search($dbc, $id) { // define the query string $query = "SELECT * FROM stick, location, identification WHERE make LIKE '%$terms%' AND stick.sid = location.lid AND identification.stickID = stick.sid "; // execute the query and return a pointer to the resultant SQL relation $dbresult = mysql_query($query,$dbc); // return the result as a simple HTML table $output = Array(); // get each tuple in the table as an object $image = mysql_fetch_object($dbresult); // interpolate the required employee values -> is the equivalent of the java DOT notation $output[] = '<ul>'; $output[] = '<li> Type: '.$image->make .'<br />Size: '.$image->size .$image->type .'<br />Colour: '.$image->colour . '<br /> Street Missing in: ' .$image->street.'<br />Town missing in: '.$image->town .'<br />City missing in: '.$image->city.'</li>'; $output[] = '</ul>'; return join('',$output); } // connect $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // get the department name from the URL $id = $_REQUEST['id']; // print the table of employees for this department // put it ina div HTML element with an emp class to support CSS styling print search($dbc, $id); print "<img src='getPhoto.php?id=$id'/>"; // close the database mysql_close($dbc); This is my error: Code: [Select] Fatal error: Can't use function return value in write context in /home/a8152576/public_html/SecretSanta.html on line 41 confused about why. This is the line 41: if(isset($_POST('submit')){ this is the php of my page (without the mysql data): <?php class functions{ public static function chooseGiftee($SS){ $done = false; while($done=false){ $sqllink= mysql_connect($mysql_host,$mysql_user,$mysql_password); if(!$sqllink){ echo "Could not connect! Please Try Again"; mysql_close($sqllink); } else { $selectGiftee = "SELECT * FROM SecretSantas ORDER BY RAND() LIMIT 0,10;"; while($row=mysql_fetch_array($result)){ $results = mysql_query($selectGiftee); if(!$row['Gifter']=''){ $done=false; } else { $gifteeResults = $row['Name']; $addSS = "INSERT INTO SecretSantas (Gifter) VALUES ('" .$SS. "')"; $done=true; return $gifteeResults; } } } mysql_close($sqllink); } } } if(isset($_POST('submit')){ $echoName = functions::chooseGiftee($_POST['gifterName']); echo $echoName; } ?> This is html: <form id="form1" name="form1" method="post" action=""> <p> <label>Your Name: <input type="text" name="gifterName" id="gifterName" /> </label> <input type="submit" name="submit" id="submit" value="Submit" /> </p> <p> </p> </form> Confused about the issue, first time using functions. Thanks in advance, Brandon not sure if this is possible but i do not know how to return multiple values and read them where the call was made. Code: [Select] $string = "clause1"; func1($string); // somehow read the response and use the return values seperately. // both $string2 and $string3 Code: [Select] function func1($input) { if ($input == "clause1") { $string2= "value2"; $string3= "value6"; } if ($input == "clause2") { $string2= "value3"; $string3= "value7"; } if ($input == "clause3") { $string2= "value4"; $string3= "value8"; } if ($input == "clause4") { $string2= "value5"; $string3= "value9"; } return ($requesttype, $messagetitle); } My tree gather function gives me multidimensional array. However i want it to be one dimensional . I was getting one dimensional earlier however i forgot how i got it. Can someone please tell me my mistake Code Code: [Select] <?php include'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { $child[] = $array['lchild']; $child[] = $array['rchild']; $eh[] = tree_gather($array['lchild']); $child = array_merge($child, $eh); $eh1[] = tree_gather($array['rchild']); $child = array_merge($child, $eh1); } return $child; } $pair = tree_gather(1000000); echo "<pre>"; print_r($pair); echo "</pre>"; ?> Output Code: [Select] Array ( [0] => 3632873 [1] => 5951538 [2] => Array ( [0] => 8930480 [1] => 7563232 [2] => Array ( [0] => 1144744 [1] => 4386810 [2] => [3] => ) [3] => ) [3] => ) Hi, I have some strange issues with my code: Code: [Select] <?PHP session_start(); $loginid = $_SESSION["valid_id"]; // First check if we are guest or user. if (!$_SESSION["valid_email"]) { $visitor = "yes"; } else { $visitor = "no"; $email = $_SESSION['valid_email']; $userid = $_SESSION['valid_id']; } //Load Header (blue menu) require("./inc/header.php"); //Load Sub-acc (silver account menu) require("./inc/sub-group.php"); //Load nav-group (Tabs) require("./inc/nav-group.php"); //Load Config file require("./inc/config.php"); //Set & get profile ID $getid = $_GET["id"]; //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); } //If we are guest, do we allow anon access to the profile IF ($row["privacy"] <= 10 && $visitor = "yes") { exit("You may not view this profile as a visitor, due to the users privacy settings"); } //Let's check if we are friends ELSEIF ($visitor = "no") { $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); $row2 = mysql_fetch_array($result2); $friends = $row2["status"]; if (mysql_num_rows($result2) = 0) { $friends = "no"; } } //If we are friend, do we allow access to the profile IF ($row["privacy"] >= 9 && $friends != 1) { exit("You may not view this profile because of the privacy settings."); } $row = mysql_fetch_array($result); $memgroup = $row["group"]; IF ($row["activated"] != 1) { exit("This account is suspended and cannot be viewed."); } //Check what group member is in. $result2 = mysql_query("SELECT * FROM profiles_groups WHERE id=('$memgroup') LIMIT 1"); $row2 = mysql_fetch_array($result); ?> Alright, so the error: Fatal error: Can't use function return value in write context in C:\xampp\htdocs\prog\profile.php on line 45 Code: [Select] 42. $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); 43. $row2 = mysql_fetch_array($result2); 44. $friends = $row2["status"]; 45. if (mysql_num_rows($result2) = 0) Alright, this is one thing that bothers me, the other is: Code: [Select] //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); I tried to put an invalid ID, and already here the script should have died/exited before executing the parts of the code that doesn't work. I tested my code on another page and it works flawlessly, perhaps this error is just generated before it actually exists i dunno.. Any way, any help is much appreciated } Hello everyone, Pretty much what I am trying to do is run a query and based of the queries result, return a string - as of now it is turning up blank and cant seem to pass any strings through the function. Current function: function addNewBookmark($hash,$url,$title,$username){ Code: [Select] $query = "INSERT INTO bookmarks (hash,url,title,username) VALUES '".md5($hash)."', '".$url."', '".$title."', '".$username."')"; $result = mysql_query(query, $this->connection); $message = ''; if(mysql_affected_rows($this->connection)!=1) { $message = 'This URL already exists in the database!'; return $message; } else $message = 'The URL was shared!'; return $message; } The above code seems to run fine, just cant seem to pass a string...read that you can possibly use a __toString function? but that keeps throwing errors when I try to work with it. Thanks all! I hate array... 😞 So I had a block of code inside my photo-gallery.php script that took the path to my photos directory, and went to that directory, and then read all of the photo filenames into an array. Then in my HTML, I iterate through this array to display all of the photos for my gallery. Now I would like to move that code to an included file so multiple scripts can access it and always be working with the same array. It seems to me that I need to encapsulate my code inside a function? Then I could call my getPhotoFilesArray back to my callings cript, and use that array for whatever. I haven't coded PHP in like 4 years and I am struggling to return the entire array back to my caling script. This is what I have so far... function getPhotoFilesArray($photoPath){ $photoFiles = array(); <code to find corresponding files> $photoFiles gets populated in a loop return $photoFiles; }
Then in my calling script, I have... <?php require_once('../../../secure_outside_webroot/config.php'); require_once(WEB_ROOT . 'utilities/functions.php'); getPhotoFilesArray($photoPath); var_dump($photoFiles);
I get some error...
Notice: Undefined variable: phtoFiles in photo-gallery.php line 133 (which is my var_dump).
<br> Would appreciate help getting this to work!
Edited December 6, 2019 by SaranacLake |