I have this code:
btn_jouer.onRelease = function ()
{
verif = txt_email_user.text;
if (txt_email_user.text == "")
{
txt_erreur.textColor = 16724736;
txt_erreur.text = "Champ(s) manquant(s)";
}
else if (verif.indexOf("#", 0) == -1 || verif.indexOf(".", 0) == -1)
{
txt_erreur.textColor = 16724736;
txt_erreur.text = "Adresse E-mail invalide";
}
else
{
php_login = new LoadVars();
php_login.email = txt_email_user.text;
php_login.sendAndLoad(_root.page_Login, php_login, "POST");
php_login.onLoad = function(succes)
{
if (succes)
{
//txt_erreur.text = php_login.etat;
//return;
if (php_login.etat == "exist")
{
_root.var_user.id = php_login.id;
_root.var_user.nom = php_login.nom;
_root.var_user.prenom = php_login.prenom;
_root.var_user.score = php_login.score;
_root.MovieLogin.unloadMovie();
if (_root._root.selectedPhone == "KS360")
{
_root.gotoAndStop(4);
}
else
{
_root.gotoAndStop(3);
} // end else if
}
else if (php_login.etat == "non")
{
trace (php_login.etat);
txt_erreur.text = "Email non enregistré! veuillez vous s'inscrir";
} // end if
} // end else if
};
} // end else if
};
The "page_Login" is login.php file on the server,
After debugging, the file login.php successfully received Posted data so i got:
$_POST['email'] = "what ever you type in swf form";
The login.php processor file:
if(isset($_REQUEST['email'])){
$email = strtolower(addslashes($_REQUEST['email']));
$DB->_request("select * from gamers where email='$email'");
if($DB->_nr() > 0) {
$row = mysql_fetch_array($DB->Result);
echo "&etat=exist&nom={$row['nom']}&prenom={$row['prenom']}&score={$row['score']}";
//
exit;
}
else {
echo "&etat=non";
exit;
}
}
Here above, the $DB->_nr() always returns "0" even the email address exists!
I have tried to create a simple html page having a form with method POST and have a simple input type text with a name="email"
When i write my email which is valid in the database and hit submit $DB->_nr() returns 1.
This really is driving me crazy, i'm sure that the email address exists, the login.php page receive posted data "email = validemail#domain.com" from SendAndLoad(); but mysql_num_rows returns 0.
Any one there had the same issue??
Any help would be so much appreciated!
Barry,
Use the following code in PHP to compare the email in both cases: given from flash and from HTML form:
if(isset($_REQUEST['email'])){
//createa the testFile.txt and give it attributes with 0777 for permission (in case you are under linux)
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "-".$_REQUEST['email']."-\r\n");
fclose($fh);
$email = strtolower(addslashes($_REQUEST['email']));
$DB->_request("select * from gamers where email='$email'");
if($DB->_nr() > 0) {
$row = mysql_fetch_array($DB->Result);
echo "&etat=exist&nom={$row['nom']}&prenom={$row['prenom']}&score={$row['score']}";
//
exit;
}
else {
echo "&etat=non";
exit;
}
}
if you test for both of the cases, you will be able to compare the two exact forms. I have put "-" in the front and the end of it just to see if there are any whitespaces next to the email value.
Please reply with a compare result. thank you.
Related
I am trying to create a CSV Checker which inserts the checked data into a Database and any unsuccessful data added to a .txt file.
I am trying to used regular expressions to validate the data I am inserting, the while loop without any validation works and inserts fine but as soon as regular expressions are used it does not work.
<?php
include_once('connection.php');
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$date = date('d/m/y h:i:s a', time());
$filetxt = "./errors.txt";
$errors = array();
$var1 = 5;
$var2 = 1000;
$var3 = 10;
$sql = '';
if(isset($_POST["Import"]))
{
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while(($emapData = fgetcsv($file, 10000, ",")) !==FALSE)
{
if(isset($_GET['strProductCode']))
{
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode']))
{
$errors['strProductCode'];
}
}
if(isset($_GET['strProductName']))
{
$emapData[1] = $conn->real_escape_string(trim($_GET['strProductName']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductName']))
{
$errors['strProductName'];
}
}
if(isset($_GET['strProductDesc']))
{
$emapData[2] = $conn->real_escape_string(trim($_GET['strProductDesc']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductDesc']))
{
$errors['strProductDesc'];
}
}
if(isset($_GET['intStock']))
{
if (!preg_match("^[0-9]", $_POST['intStock']))
{
$errors['intStock'];
}
}
if(isset($_GET['intPrice']))
{
if (!preg_match("[0-9]", $_POST['intPrice']))
{
$errors['intPrice'];
}
}
if(isset($_GET['dtmDiscontinued'])){
if($emapData[6] == preg_match("[a-zA-Z]", $_POST['dtmDiscontinued']))
{
$emapData[6] = $date;
echo $date;
}else{
$emapData[6] = Null;
}
}
if(count($errors > 0))
{
// errors
$write = "$emapData[0], $emapData[1], $emapData[2], $emapData[3], $emapData[4], $emapData[5], $emapData[6]\r\n";
file_put_contents($filetxt , $write , FILE_APPEND);
}else{
// insert into Database
$sql = "INSERT INTO tblproductdata(strProductCode, strProductName, strProductDesc, intStock, intPrice, dtmAdded, dtmDiscontinued) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$date','$emapData[6]')";
$res=$conn->query($sql);
}
}
fclose($file);
echo "CSV File has successfully been Imported";
echo "<br>";
echo "Any errors within the CVS Database are reported here.";
echo "<br>";
$fh = fopen($filetxt, 'r');
$theData = fread($fh, filesize($filetxt));
fclose($fh);
echo $theData;
}else{
echo "Invalid File: Please Upload a Valid CSV File";
}
header("Location: index.php");
}
?>
My knowledge of PHP is not great but this is my best attempt.
Any help would be greatly appreciated.
There are several issues in your code. Let's start with the regular expressions and your error checking:
Some of your expressions are invalid. Note that each expression needs a delimiting character at the beginng and ending of the expression. In some of your expressions (like ^[0-9]) these delimiters are missing. Please also note that using ^ as a delimiter for a regular expression is not a good choice, because the ^ character also has a special meaning in regular expressions.
This should actually cause PHP Warnings. I see that you have error_reporting enabled; you should also have a look at your display_errors setting.
As mentioned in my comment, you do not assign any values to the $errors array. The statement $errors['strProductName'] in itself does not change the array; this means that $errors will always be empty. You probably mean to do something like:
$errors['strProductName'] = TRUE;
You're actually checking count($errors > 0) where you should be checking count($errors > 0). count($errors > 0) translates to either count(TRUE) or count(FALSE) which both equal 1.
Some other notes:
Some times, you check for $_GET['strProductCode'], but then use $_POST['strProductCode'].
You do not reset the $errors array for each iteration. That means that for each line that you read, the $errors variable will still contain the errors from the previous iteration. As a result, the first invalid line will cause all following lines to be recognized as invalid, too.
You register an error when one of the parameters is of an invalid format, but not when one of them is not set at all (i.e. when isset($_POST[...]) is FALSE). Each of them should probably be sth. like this:
if (isset($_POST['strProductCode'])) {
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode'])) {
$errors['strProductCode'] = TRUE;
}
} else {
$errors['strProductCode'] = TRUE;
}
I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>
I have been debugging some php code today and have run into a very strange problem. A function that I have to check if a password is valid stops executing part way through the function. No errors are generated either by PHP or by the web server itself.
Here is the function in question:
//Common Registration Functions
function checkPassword($password)
{
$bLen = strlen($password);
echo $bLen."\n";
echo $password."\n";
//Remove any illegal characters
$vPWord = preg_replace("/[^\!\#\#\\\$\%\&\*\-\_\,\.a-zA-Z0-9]/","",$password);
$aLen = strlen($vPWord);
echo $aLen."\n";
echo $vPWord."\n";
//If the password length before santization is different than after then the user used illegal characters
if ($bLen <> $aLen)
{
return "pass_charfail";
}
echo "pass length check 1 \n";
//Check sanitized password length
if (strlen($vPWord) < 6)
{
return "pass_short";
}
echo "pass length check 2 \n";
if (strlen($vPWord) > 10)
{
return "pass_long";
}
echo "pass length check 3 \n";
//Check password strength
$strength = 0;
if (preg_match("/[^a-z]/",$vPWord))
{
$strength += 1;
}
if (preg_match("/[^A-Z]/",$vPWord))
{
$strength += 1;
}
if (preg_match("/[^0-9]/",$vPWord))
{
$strength += 2;
}
if (preg_match("/[^\!\#\#\\\$\%\&\*\-\_\,\.]/",$vPWord))
{
$strength += 4;
}
if ($strength > 6)
{
echo $strength."\n";
return true;
}
else
{
echo $strength."\n";
return "pass_weak";
}
}
Here is the output I get from my error checking setup (my webhost will not enable php debugging for an entire site so I have to go through a separate file which I will post the code from later):
4
Mast
4
Mast
{"success":"noerror"}
Here is the way I have to check for errors:
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
include("register.php");
?>
And here is the function which calls the function in question above:
function register($username, $password, $email, $squestion, $sanswer)
{
//First check if the email is valid
$data = eVerify($email);
//If email is not valid
if (!$data)
{
return "email_fail";
}
//If email is valid then check if it already exists and the verification status
else
{
//See if the email already exists
$data = getUID($email,"email",true);
//echo $data."\n";
if ($data)
{
//Get user ID for later use
$id = getUID($email,"email",false);
//If the email exists, see if it has been verified or not
$data = checkVer($id);
//echo $data."\n";
//If email exists but has not been verified
if (!$data)
{
rSVCode($username,$email,$id);
return "exists1";
exit();
}
//If email exists and has been verified
else if ($data)
{
return "exists2";
exit();
}
}
//If email does not exist, continue registration process
else
{
//Check to see if username has been used
$data = getUID($username,"username",true);
if ($data)
{
return "un_exists";
exit();
}
//Check password strength, chars, and length
else
{
$data = checkPassword($password);
if ($data)
{
//Create user account
$data = cAccount($username, $password, $email, $squestion, $sanswer);
if ($data)
{
//Get user's ID for use later
$id = getUID($username,"username",false);
//Generate email verification code
$data = cVCode($username,$email,$id);
//Send verification email
$data = sendEVar($email,$username,$data);
if ($data)
{
return "true";
exit();
}
else
{
return $data;
exit();
}
}
else
{
return $data;
exit();
}
}
else
{
return $data;
exit();
}
}
}
}
}
The triple === makes sure the return is of the same type.
In your function you don't always return boolean, sometimes you return strings, and that could be an issue.
For example this snippet:
$data = "pass_charfail";
if($data){
echo 'true';
}else{
echo 'false';
}
this will echo true because $data is not an empty string.
But the following will echo false, because $data is not a true boolean.
$data = "pass_charfail";
if($data === true){
echo 'true';
}else{
echo 'false';
}
One more example in your register function you have
if ($data)
{
return "true";
exit();
}
if this value gets return, then false will be echo from the following code:
if($data === true){
echo 'true';
}else{
echo 'false';
}
because $data is now a string which is not of type boolean.
hope it makes sense to you!
I got it working again but I am not sure why the change I made makes a difference. If someone could respond to this answer or post their own answer explaining it would be appreciated.
How I fixed it was changing the if ($data) line after checkPassword is called to if ($data === true) and it reported the correct error message instead of claiming a successful registration.
I think this post may appear to be as an "off" topic to others. But it'll be a great thank if you help me out with this.
I found some email verification code on the web. Somehow, I find it confusing at first but when I began to understand it and put it on my code. There's a error and I don't know how.
Problems:
The email verification code.
Proper syntax/use of the code.
Code:
<?php
if(isset($_POST['submit']))
{
$a = $_POST['username'];
$b = $_POST['password'];
$c = $_POST['firstname'];
$d = $_POST['lastname'];
$e = $_POST['month'];
$f = $_POST['day'];
$g = $_POST['year'];
$h = $_POST['contact'];
$i = $_POST['email'];
$j = $_POST['confirm'];
$code = md5(uniqid(rand()));
include("dbconnect.php");
$query = "SELECT * FROM `users`.`info` WHERE `username`='".$a."' AND `email_address`='".$i."'";
$queryQuery=$con->query($query);
$checker = mysqli_num_rows($queryQuery);
if (($a && $b && $c && $d && $h && $i && $j) == "")
{
print "<script type=text/javascript>
alert('All fields are required');
</script>";
}
else
{
if ($checker == 0 && $b != $j)
{
print "<script type=text/javascript>
alert('Password Mismatch');
</script>";
}
else if($checker == 0)
{
//print $a,$b,$c,$d,$e,$f,$g,$h,$i;
$insertQuery="INSERT INTO `users`.`info` (`username`,`password`,`firstname`,`lastname`,`month`,`day`,`year`,`contact_number`,`email_address`,`confirm_code`) VALUES ('$a','$b','$c','$d','$e','$f','$g','$h','$i','$code')";
$insertQueryResult=$con->query($insertQuery);
if ($insertQueryResult)
{
// send e-mail to ...
$to=$i;
// Your subject
$subject="Your confirmation link here";
// From
$header="From Admins of Publisita.com";
// Your message
$message="Your Comfirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.gmail.com/confirmation.php?passkey=$code";
// send email
$sentmail = mail($to,$subject,$message,$header);
}
// if not found
else
{
print "<script type=text/javascript>
alert('Not found your email in our database')
</script>";
}
// if your email succesfully sent
if($sentmail)
{
print "<scrpit type=text/javascript>
alert('Your Confirmation link Has Been Sent To Your Email Address')
</script>";
}
else
{
print "<script type=text/javascript>
alert('Cannot send Confirmation link to your e-mail address')
</script>";
}
}
print "<script type=text/javascript>
alert('Successfully Registered');
</script>";
}
else
{
print "<script type=text/javascript>
alert('Information are already been used');
</script>";
}
}
}
?>
It'll be a great thing if someone helped me out
This line:
if (($a && $b && $c && $d && $h && $i && $j) == "")
is not valid syntax. If you want to make sure these values aren't empty you will need to check them individually (you also want to use or (||) since only one has to be empty for you to show your error. Your current code would require all of them to be empty):
if ($a == "" || $b == "" ....) // or if (empty($a) || empty($b) ....)
or come up with a more concise way to do this:
$fields = array($a, $b, $c, $d, $h, $i, $j);
if (count(array_filter($fields)) !== count($fields))
The code above takes all of the values to be checked an puts them into an array. It then calls array_filter() to remove any values that are false (an empty string is type juggled to be Boolean false). If the number of remaining elements doesn't equal the starting number of elements then one or more were empty and you need to show your error.
As pointed out by #NicolasDefranoux you are wide open to SQL injections. Make sure you close that hole before publishing your code.
Hi this is a simple question, however I have now stared at it long enough to realise im simply not seeing the error. If anyone can see where this is going wrong I would be very thankful.
public function create()
{
$this->load->model('ticket_model');
if($_POST)
{
// validate form
if($this->_validate())
{
// save updates
foreach($_POST as $key => $value){if(!is_array($value)) $_POST[$key] = htmlspecialchars($value);}
if ($_POST['subject'] == '') $body_data['error'][] = "You did not enter a subject.";
if ($_POST['priority'] == '') $body_data['error'][] = "You did not select a priority.";
if ($_POST['status'] == '') $body_data['error'][] = "You did not select a status.";
if ($_POST['ipAddress'] == '') $body_data['error'][] = "You did not enter a ipAddress.";
if ($_POST['text_area'] == '') $body_data['error'][] = "You did not enter a message.";
else
{
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == FALSE) $body_data['error'][] = "IP Address is not valid IPV4 Address.";
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) == FALSE) $body_data['error'][] = "IP Address cannot be from RFC1918 private space.";
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) $body_data['error'][] = "IP Address cannot be from reserved range.";
}
if ($_FILES['filename']['name'] != '')
{
if ($_FILES['filename']['size'] > '1024000')
{
$body_data['error'][] = "The file you uploaded is too large.";
unlink($_FILES['filename']['tmp_name']);
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
else
{
//the file is under the specified size. so copy it from temp to import folder and proccess
$thisFileHumanName = $_FILES['filename']['name'];
$thisFileSize = $_FILES['filename']['size'];
$thisServerFileName = strtoupper(uniqid('A'));
$thisFileType = $_FILES['filename']['type'];
$temp_file_location = $this->config->item('rootpath').'/assets/ticketuploads/'.$thisServerFileName;
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $temp_file_location))
{
$body_data['error'][] = "File could not be moved due to a permissions error.";
unlink($_FILES['filename']['tmp_name']);
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
}
}
//clean error array
$body_data['error'] = array_filter($body_data['error']);
if ($body_data['error'])
{
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
unlink($_FILES['filename']['tmp_name']);
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
else
{
$_POST['userId'] = $this->session->get_user_id();
$thisMessageId = $this->ticket_model->save_message($_POST);
if ($_FILES['filename']['name'] != '')
{
//set variables for save
$_POST['file_path'] = $temp_file_location;
$_POST['file_name'] = $thisFileHumanName;
$_POST['file_size'] = $thisFileSize;
$_POST['file_type'] = $thisFileType;
$_POST['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($_POST);
}
$this->ticket_model->save_ticket($_POST);
redirect(base_url().'ticket/');
return;
}
}
}
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['message_list'] = $this->ticket_model->list_message($ticket_id);
$body_data['customer_list'] = $this->ticket_model->list_customers();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$foot_data['contact_search'] = true;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/create',$body_data);
$this->load->view('foot',$foot_data);
return;
}
This is my code, and everything is going well, except for the section where i save the upload, as nothing seems to be firing the model, even thought there is a file being posted from the from submit and there for the filename being posted is != ''......
e.g
if ($_FILES['filename']['name'] != '')
{
//set variables for save
$_POST['file_path'] = $temp_file_location;
$_POST['file_name'] = $thisFileHumanName;
$_POST['file_size'] = $thisFileSize;
$_POST['file_type'] = $thisFileType;
$_POST['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($_POST);
}
my apologies if this is silly mistake.
Why are you doing it this way? Codeigniter has a built in class for uploading files. You also should be using the input class instead of $_POST.
It will make it a lot easier!
As for your code. You're actually setting the $_POST variable and trying to use that in save_ticket. You can't do that.
The predefined $_POST variable is used to collect values from a form
sent with method="post"
You're trying to use it the other way around.
So to make it work, change the $_POST into $something and it should work, but it's still not the way to go.
//set variables for save
$something['file_path'] = $temp_file_location;
$something['file_name'] = $thisFileHumanName;
$something['file_size'] = $thisFileSize;
$something['file_type'] = $thisFileType;
$something['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($something);
didn't have this set.......enctype="multipart/form-data"
red face on this end.