PHP - Problems With Ctype_alnum() Input Validation
I tried to use ctype_alnum as input validation for the name and the password, so that only letters and numbers are allowed with no spaces.
If I use ctype_alnum only with the nickname, then the nickname will not get entered properly into the database, it will get entered as "1" into the database. And the password does not make it past the elseif statement: Code: [Select] // check password char length } elseif (strlen($password) > 25 || strlen($password) < 6) { Here's the script: Code: [Select] /* REGISTER FORM */ // check if submit button has been clicked if (isset($_POST['submit_signup'])) { // process and assign variables after post submit button has been clicked $user_email = strip_tags($_POST['email']); $user_email = filter_var($user_email, FILTER_VALIDATE_EMAIL); $nickname = ctype_alnum(strip_tags($_POST['nickname'])); $password = ctype_alnum($_POST['password']); $repassword = ctype_alnum($_POST['repassword']); $month = $_REQUEST['month']; $day = $_REQUEST['day']; $year = $_REQUEST['year']; $dob = $year . "-" . $month . "-" . $day; $find_us_question = strip_tags(trim($_POST['find_us_question'])); // connect to database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $check_query = "SELECT * FROM user WHERE nickname = '$nickname'"; $check_connect = mysqli_query($dbc, $check_query) or die(mysqli_error($dbc)); $check_count = mysqli_num_rows($check_connect); // Check if the email exists twice $query_get = "SELECT email FROM user WHERE email = '$user_email'"; $query_run = mysqli_query($dbc, $query_get); $num_rows = mysqli_num_rows($query_run); if(!$nickname) { echo 'Please do fill out the name in letters and numbers only, without spaces and special characters.'; } elseif(!$password || !$repassword) { echo 'Please choose a password which conists of letters and numbers only, without spaces and special characters.'; // check if username is already taken }elseif ($check_count != 0) { echo "Username already exists!"; } elseif ($num_rows != 0) { echo "This email address is already registered in the database, you can not register it twice."; // check if fields are empty } elseif (empty($user_email) || empty($nickname) || empty($password) || empty($day) || empty($month) || empty($year)) { echo "Please fill out all the fields!"; // check char length of input data } elseif (strlen($nickname) > 30 || strlen($user_email) > 50) { echo "Maximum allowed character length for nickname/firstname/lastname are 30 characters!"; // check password char length } elseif (strlen($password) > 25 || strlen($password) < 6) { echo "Your password must be between 6 and 25 characters!"; // check if passwords match with each other } elseif ($password != $repassword) { echo "Please make sure your passwords are matching!"; } else { // encrypt password $password = sha1($password); // generate random number for activation process $random = rand(1212121212, 9854241752); // write into database Any ideas why I am getting these problems with ctype_alnum() ? Similar TutorialsWhere in the PHP manual can I find information about input validation? I looked and I seem to not find it. I am intending to create my own email input validation. Hello Guys... I need help about my validate scripts... $(document).ready(function(){ //Validation jQuery.validator.addMethod('validIPurl', function(value) { var ip = '^([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$'; var URL = /^(http|https)?:\/\/[a-zA-Z0-9-\.]+\.[a-z]{2,4}/; //HOW TO JOIN AND VALIDATE BOTH VARIABLE IP AND URL???? } }, 'Invalid Address'); //if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i) $(".myfirstform").validate( { rules: { ip: { validIPurl: true } }, ); },I use jquery.validate javascripts to validate user input.. I also try to create if..else to join IP and URL but the control statement not working Hope you guys can help for the solution... i'm really sorry, if there is a word that makes you confused. Code: [Select] <?php $ip = $_SERVER['REMOTE_ADDR']; if($_POST['hapus']=='Hapus') { $qDelDetail = mysql_query("DELETE FROM tbl_u_pekerjaan WHERE id_u_pekerjaan = '".$_POST['id_u_pekerjaan']."'"); } ?> <!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=iso-8859-1" /> <title>Untitled Document</title> <style> .suggestion { position:absolute; background-color:#eee; border:1px solid #CCC; display: none; width:400px; } .suggestion ul{ margin : 0 ; padding : 5px 5px ; } .suggestion ul li{ padding-top : 2px ; cursor : pointer ; list-style : none ; } .suggestion ul li:hover{ cursor : pointer ; list-style : none ; color : red ; /*font-weight : bold ;*/ } #form1 #pagu1 { border: 1px solid #999999; height: 21px; width: 355px; } </style> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="border_all" height="34" bgcolor="#CCCCCC"><strong><img src="image/icon_1.png" align="absmiddle" width="22" height="22" /> Pemeliharaan Komputer </strong></td> </tr> <tr> <td><hr size="1" color="#999999" /></td> </tr> <tr> <td> <table width="100%" border="0" cellspacing="2" cellpadding="3"> <form id="form1" name="form1" method="post" action=""> <tr> <td width="30%">Tahun Anggaran</td> <td width="2%">:</td> <td width="68%"><select name="thn_anggaran" id="thn_anggaran"> <?php $thn_on = date("Y"); ?> <option value="<?=$thn_on;?>"><?=$thn_on;?></option> <?php for($i = 2000; $i <= $thn_on; $i++) { ?> <option value="<?=$i;?>"><?=$i;?></option> <?php } ?> </select></td> </tr> <tr> <td width="30%">Jenis Anggaran</td> <td width="2%">:</td> <td width="68%"><select name="id_jns_anggaran"> <?php include "conn_ra.php"; ?> <?php $qRea = mysql_query("SELECT * FROM tbl_jns_anggaran ORDER BY id_jns_anggaran ASC"); while($dtRea = mysql_fetch_array($qRea)) { ?> <option value="<?=$dtRea['id_jns_anggaran'];?>"><?=$dtRea['nm_jns_anggaran'];?></option> <?php } ?> </select></td> </tr> <tr> <td align="left" valign="top">Nama Program</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_program" name="kd_program" size="8" onkeyup="javascript:suggestme('program');" autocomplete="off" /> <input type="text" id="nm_program" name="nm_program" size="50" onkeyup="javascript:suggestme('program');" autocomplete="off" /> <div id="suggestion_program" class="suggestion"></div></td> </tr> <tr> <td align="left" valign="top">Nama Kegiatan</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_kegiatan" name="kd_kegiatan" size="8" onkeyup="javascript:suggestme('kegiatan');" autocomplete="off" /> <input type="text" id="nm_kegiatan" name="nm_kegiatan" size="50" onkeyup="javascript:suggestme('kegiatan');" autocomplete="off" /> <div id="suggestion_kegiatan" class="suggestion"></div></td> </tr> <tr> <td align="left" valign="top">Nama Sub Kegiatan</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_sub_kegiatan" name="kd_sub_kegiatan" size="8" onkeyup="javascript:suggestme('sub_kegiatan');" autocomplete="off" /> <input type="text" id="nm_sub_kegiatan" name="nm_sub_kegiatan" size="50" onkeyup="javascript:suggestme('sub_kegiatan');" autocomplete="off" /> <div id="suggestion_sub_kegiatan" class="suggestion"></div></td> </tr> <tr> <td align="left" valign="top">MAK</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_mak" name="kd_mak" size="8" onkeyup="javascript:suggestme('mak');" autocomplete="off" /> <input type="text" id="nm_mak" name="nm_mak" size="50" onkeyup="javascript:suggestme('mak');" autocomplete="off" /> <div id="suggestion_mak" class="suggestion"></div></td> </tr> <!-- <tr> <td align="left" valign="top"><strong>Pagu</strong></td> <td align="left" valign="top"><strong>:</strong></td> <td align="left" valign="top"><div id="pagu1"></div> <input name="pagu" type="text" id="pagu" size="60" maxlength="250" /></td> </tr> --> <tr> <td width="30%"> Komputer </td> <td width="2%">:</td> <td width="68%"><select name="id_inventaris" id="id_inventaris"> <?php include "conn.php"; if(isset($_POST['id_inventaris'])) { $qKomputer = mysql_query("SELECT a.id_inventaris, a.nmr_inventaris, a.merk, a.type, a.processor_type FROM v_inventaris a WHERE id_inventaris = '".$_POST['id_inventaris']."'"); $dtKomputer = mysql_fetch_array($qKomputer); ?> <option value="<?=$dtKomputer['id_inventaris']?>"><?=$dtKomputer['nmr_inventaris'];?> | <?=$dtKomputer['merk'];?> <?=$dtKomputer['type'];?> <?=$dtKomputer['processor_type'];?></option> <?php }else { ?> <option>-Pilih Komputer-</option> <?php } ?> <?php $qKomputer = mysql_query("SELECT a.id_inventaris, a.nmr_inventaris, a.merk, a.type, a.processor_type FROM v_inventaris a WHERE EXISTS ( SELECT b.id_inventaris FROM tbl_memiliki b WHERE a.id_inventaris = b.id_inventaris ) ORDER BY id_inventaris ASC"); while($dtKomputer = mysql_fetch_array($qKomputer)) { ?> <option value="<?=$dtKomputer['id_inventaris']?>"><?=$dtKomputer['nmr_inventaris'];?> | <?=$dtKomputer['merk'];?> <?=$dtKomputer['type'];?> <?=$dtKomputer['processor_type'];?></option> <? } ?> </select> </td> </tr> <tr> <td>Jenis Pemeliharaan </td> <td>:</td> <td><select name="id_jenis" id="id_jenis"> <?php include "conn.php"; if(isset($_POST['id_jenis'])) { $qJenis = mysql_query("SELECT * FROM tbl_jenis WHERE id_jenis = '".$_POST['id_jenis']."'"); $dtJenis = mysql_fetch_array($qJenis); ?> <option value="<?=$dtJenis['id_jenis'];?>"><?=$dtJenis['nm_jenis'];?></option> <?php }else { ?> <option>-Pilih Jenis Pemeliharaan-</option> <?php } ?> <?php $qJenis = mysql_query("SELECT * FROM tbl_jenis ORDER BY id_jenis ASC"); while($dtJenis = mysql_fetch_array($qJenis)) { ?> <option value="<?=$dtJenis['id_jenis'];?>"><?=$dtJenis['nm_jenis'];?></option> <? } ?> </select> </td> </tr> <tr> <td>No. Surat/Memo</td> <td>:</td> <td><input name="no_surat" type="text" id="no_surat" size="50" /></td> </tr> <tr> <td>Tanggal Surat/Memo </td> <td>:</td> <td><input name="tgl_surat" type="text" id="tgl_surat" size="10" value="<?=$_POST['tgl_surat'];?>" /> <script language="JavaScript" type="text/javascript"> new tcal ({ // form name 'formname': 'form1', // input name 'controlname': 'tgl_surat' }); </script></td> </tr> <tr> <td>Asal Surat </td> <td>:</td> <td><input name="asal_surat" type="text" id="asal_surat" size="50" /></td> </tr> <tr> <td>Penanggung Jawab Pemeliharaan </td> <td>:</td> <td><select name="nip" id="nip"> <?php if(isset($_POST['nip'])) { $qNip = mysql_query("SELECT * FROM tbl_pegawai WHERE nip = '".$_POST['nip']."'"); $dtNip = mysql_fetch_array($qNip); ?> <option value="<?=$dtNip['nip'];?>"><?=$dtNip['nama'];?></option> <?php }else { ?> <option>-Pilih Penanggung Jawab Pemeliharaan-</option> <?php } ?> <?php $qNip = mysql_query("SELECT * FROM tbl_pegawai ORDER BY nama ASC"); while($dtNip = mysql_fetch_array($qNip)) { ?> <option value="<?=$dtNip['nip'];?>"><?=$dtNip['nama'];?></option> <? } ?> </select> </td> </tr> <tr> <td>No. SPK/Kuitansi </td> <td>:</td> <td><input name="no_spk" type="text" id="no_spk" size="50" /></td> </tr> <tr> <td>Tanggal SPK/Kuitansi </td> <td>:</td> <td><input name="tgl_pemeliharaan" type="text" id="tgl_pemeliharaan" size="10" value="<?=$_POST['tgl_pemeliharaan'];?>" /> <script language="JavaScript" type="text/javascript"> new tcal ({ // form name 'formname': 'form1', // input name 'controlname': 'tgl_pemeliharaan' }); </script></td> </tr> <tr> <td align="left" valign="top">Nama Rekanan </td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input name="nm_rekanan" value="<?=$_POST['nm_rekanan'];?>" type="text" id="nm_rekanan" size="35" /></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Simpan" /></td> </tr> <?php if($_POST['Submit']=='Simpan') { // data sudah ada atau belum $qCr = mysql_query("SELECT id_pemeliharaan FROM tbl_pemeliharaan WHERE tgl_pemeliharaan = STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y') AND id_jenis = '".$_POST['id_jenis']."' AND nm_rekanan = '".$_POST['nm_rekanan']."' AND id_pemeliharaan = '".$_POST['id_pemeliharaan']."'"); $dtCr = mysql_num_rows($qCr); if($dtCr <= 0) { /* $qId = mysql_query("SELECT id_pemeliharaan FROM tbl_pemeliharaan ORDER BY id_pemeliharaan DESC"); $dtId = mysql_fetch_array($qId); $id_pemeliharaan = $dtId[0] + 1; $id_realisasi_anggaran = $dtId[0] + 1; $qInsertData = mysql_query("INSERT INTO tbl_pemeliharaan(id_pemeliharaan, id_inventaris, id_jenis, nip, tgl_input, tgl_pemeliharaan, nm_rekanan, no_surat, tgl_surat, asal_surat, no_spk) VALUES('".$id_pemeliharaan."', '".$_POST['id_inventaris']."', '".$_POST['id_jenis']."', '".$_POST['nip']."', CURRENT_DATE(), STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'), '".$_POST['nm_rekanan']."', '".$_POST['no_surat']."', STR_TO_DATE('".$_POST['tgl_surat']."','%m/%d/%Y'), '".$_POST['asal_surat']."', '".$_POST['no_spk']."')")or die(mysql_error()); include "include/conn_ra.php"; $qInsertData = mysql_query("INSERT INTO tbl_realisasi_anggaran(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, tgl_realisasi) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_bas']."', STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'))")or die(mysql_error()); */ $qId = mysql_query("SELECT id_pemeliharaan FROM tbl_pemeliharaan ORDER BY id_pemeliharaan DESC"); $dtId = mysql_fetch_array($qId); $id_pemeliharaan = $dtId[0] + 1; include("conn_ra.php"); $kd_sub_sistem = "PMKOM-".$id_pemeliharaan; //kd sub sistem di sistem anggaran $queryAlokasi = "SELECT alokasi_anggaran FROM tbl_alokasi_anggaran WHERE thn_anggaran = '".$_POST['thn_anggaran']."' AND id_jns_anggaran = '".$_POST['id_jns_anggaran']."' AND kd_program = '".$_POST['kd_program']."' AND kd_kegiatan = '".$_POST['kd_kegiatan']."' AND kd_sub_kegiatan = '".$_POST['kd_sub_kegiatan']."' AND kd_bas = '".$_POST['kd_mak']."' AND pj_anggaran = 'Bagian Sistem Informasi'"; $qAlokasi = mysql_query($queryAlokasi); $dtAlokasi = mysql_fetch_array($qAlokasi); $queryRealisasi = "SELECT realisasi_anggaran FROM tbl_realisasi_anggaran WHERE thn_anggaran = '".$_POST['thn_anggaran']."' AND id_jns_anggaran = '".$_POST['id_jns_anggaran']."' AND kd_program = '".$_POST['kd_program']."' AND kd_kegiatan = '".$_POST['kd_kegiatan']."' AND kd_sub_kegiatan = '".$_POST['kd_sub_kegiatan']."' AND kd_bas = '".$_POST['kd_mak']."' AND pj_anggaran = 'Bagian Sistem Informasi'"; $qRealisasi = mysql_query($queryRealisasi); $dtRealisasi = mysql_fetch_array($qRealisasi); $sisaAnggaran = $dtAlokasi['alokasi_anggaran'] - $dtRealisasi['realisasi_anggaran']; $qInsertAnggaran = mysql_query("INSERT INTO tbl_realisasi_anggaran(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, kd_sub_sistem, pj_anggaran, tgl_realisasi) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_mak']."', '".$kd_sub_sistem."', 'Bagian Sistem Informasi', STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'))") or die(mysql_error()); mysql_close($link1); include("conn.php"); /* $qInsertData = mysql_query("INSERT INTO tbl_pemeliharaan(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, id_pemeliharaan, id_kendaraan, id_jenis, nip, tgl_input, tgl_pemeliharaan, nm_bengkel, no_surat, tgl_surat, asl_surat, no_spk, pagu) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_mak']."','".$id_pemeliharaan."', '".$_POST['id_kendaraan']."', '".$_POST['id_jenis']."', '".$_POST['nip']."', CURRENT_DATE(), STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'), '".$_POST['nm_bengkel']."', '".$_POST['no_surat']."', STR_TO_DATE('".$_POST['tgl_surat']."','%m/%d/%Y'), '".$_POST['asl_surat']."', '".$_POST['no_spk']."', '".$sisaAnggaran."')") or die(mysql_error()); */ if(empty($_POST['thn_anggaran']) OR empty($_POST['id_jns_anggaran']) OR empty($_POST['kd_program']) OR empty($_POST['kd_kegiatan']) OR empty($_POST['kd_sub_kegiatan'])OR empty($_POST['kd_mak'])OR empty($_POST['id_inventaris'])OR empty($_POST['id_jenis'])OR empty($_POST['no_surat'])OR empty($_POST['tgl_surat'])OR empty($_POST['asal_surat'])OR empty($_POST['nip'])OR empty($_POST['no_spk'])OR empty($_POST['tgl_pemeliharaan'])OR empty($_POST['nm_rekanan'])) { echo '<script>alert("Data masih ada yang kosong!");</script>'; echo '<html><head> <meta http-equiv="refresh" content="0;url=index.php?p=tambah_pemeliharaan"> </head></html>'; } elseif($qInsertData = mysql_query("INSERT INTO tbl_pemeliharaan(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, id_pemeliharaan, id_inventaris, id_jenis, nip, tgl_input, tgl_pemeliharaan, nm_rekanan, no_surat, tgl_surat, asal_surat, no_spk) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_mak']."','".$id_pemeliharaan."', '".$_POST['id_inventaris']."', '".$_POST['id_jenis']."', '".$_POST['nip']."', CURRENT_DATE(), STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'), '".$_POST['nm_rekanan']."', '".$_POST['no_surat']."', STR_TO_DATE('".$_POST['tgl_surat']."','%m/%d/%Y'), '".$_POST['asal_surat']."', '".$_POST['no_spk']."')") or die(mysql_error())) /*if($qInsertData) {*/ ?>{ <script type="text/javascript"> var answer = confirm("Input data berhasil, Lanjutkan ke uraian pekerjaan ?") if (answer) { window.location = "index.php?p=u_pekerjaan&id_pemeliharaan=<?=$id_pemeliharaan;?>"; } else{ window.location = "index.php?p=pemeliharaan"; } </script> } <? /*}else { echo ("<script> alert (\"Input data gagal dilakukan !!\");</script><br>"); echo "<html><head> <meta http-equiv='refresh' content='0;url=index.php?p=tambah_pemeliharaan'> </head></html>"; }*/ } else { echo ("<script> alert (\"Data yang dimasukkan sudah ada\");</script><br>"); echo "<html><head> <meta http-equiv='refresh' content='0;url=index.php?p=pemeliharaan'> </head></html>"; } } ?> </form> </table> </td> </tr> <tr> <td><hr size="1" color="#999999" /></td> </tr> </table> </body> </html> This doesnt' work: Code: [Select] if (!empty($b_house) && !empty($b_postcode) && !empty($b_city) && !empty($b_country) && !empty($d_house) && !empty($d_postcode) && !empty($d_city) && !empty($d_country)){ ... } replacing !empty with isset doesn't work either. I just want to say if all of them are not empty, do the if statement. Any solutions? I can't get this validation to work with my form: Code: [Select] if (!isset($b_house) && !isset($b_postcode) && !isset($b_city) && !isset($b_country)){ echo '<div class="wrong">Please enter all of the billing information.</div>'; } The error message will just not show up at all, any ideas whats wrong? I have Gender, Date of Birth, and Captcha validations. Though they are not working. Lets start with gender. Then captcha, then DOB. I call the Gender check via doing if(user::isValidGender($this->gender) == FALSE) $errors[] = "Invalid gender"; "user" is another class. The function isValidGender() is as follows public function isValidGender($gender) { $validGenders = array("male", "female", "mtf", "ftm", "androgyne", "intersex"); if(in_array($gender, $validGenders) == FALSE) return false; } When I do if(in_array($gender, $validGenders) == FALSE) die("error"); it doesn't die. It displays "Invalid Gender" which means that if it doesn't do the die() it returns true. Though it checks if the function returns false when calling "isValidGender()". If I put the die() above the if, it dies. So it obviously is returning true, but why is it displaying the error? I am trying to use PEAR VALIDATION for a registration form an am not able to get it to work. require 'Validate/US.php'; $email = $_REQUEST['email']; $validate = new Validate(); if (!$validate->email("$email")) { echo "Invalid email"; } is what I am using. and I $email is defined earlier in the code as the user input for email. here is the rest of the code. <?php if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "studentofstone@gmail.com"; $email_subject = "$first_name"; function died($error) { // your error code can go here echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br /><br />"; echo $error."<br /><br />"; echo "Please go back and fix these errors.<br /><br />"; die(); } // validation expected data exists if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['address']) || !isset($_POST['city']) || !isset($_POST['state']) || !isset($_POST['zip']) || !isset($_POST['email']) || !isset($_POST['telephone']) || !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $first_name = $_POST['first_name']; // required $last_name = $_POST['last_name']; // required $address = $_POST['address']; // required $city = $_POST['city']; // required $state = $_POST['state']; // required $state = $_POST['zip']; // required $email_from = $_POST['email']; // required $telephone = $_POST['telephone']; // not required $comments = $_POST['comments']; // required $error_message = ""; $email_exp = "^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$"; if(!eregi($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.<br />'; } $string_exp = "^[a-z .'-]+$"; if(!eregi($string_exp,$first_name)) { $error_message .= 'The First Name you entered does not appear to be valid.<br />'; } $string_exp = "^[a-z .'-]+$"; if(!eregi($string_exp,$last_name)) { $error_message .= 'The Last Name you entered does not appear to be valid.<br />'; } require 'Validate/US.php'; $email = $_REQUEST['email']; $validate = new Validate(); if (!$validate->email("$email")) { echo "Invalid email"; } // $phoneNumber = '$telephone'; $result = Validate_US::phoneNumber($phoneNumber); echo 'Test ' . $phoneNumber .' : <br />'; var_export($result); echo '<br />'; if(strlen($comments) < 2) { $error_message .= 'The Comments you entered do not appear to be valid.<br />'; } if(strlen($error_message) > 0) { died($error_message); } header( "Expires: Mon, 20 Dec 1998 01:00:00 GMT" ); header( "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" ); header( "Cache-Control: no-cache, must-revalidate" ); header( "Pragma: no-cache" ); $email_message = "Form details below.\n\n"; $email_message = date("m/d/Y") . "\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "First Name: ".clean_string($first_name)."\n"; $email_message .= "Last Name: ".clean_string($last_name)."\n"; $email_message .= "address: ".clean_string($address)."\n"; $email_message .= "city: ".clean_string($city)."\n"; $email_message .= "state: ".clean_string($state)."\n"; $email_message .= "zip: ".clean_string($zip)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Telephone: ".clean_string($telephone)."\n"; $email_message .= "Comments: ".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); header("Location: https://www.paypal.com/"); @mail($email_to, $email_subject, $email_message, $headers); ?> <!-- include your own success html here --> Thank you for contacting us. We will be in touch with you very soon. <? } ?> I hope I can explain what is happening. I have created two forms in PHP. The first 'almost' works, i.e. it shows the data. But I have two problems - 1) the second pulldown menu is always empty and 2) $value from the first pulldown menu ALWAYS equals the last entry thus the last 'if' in the function subdomains ($domains) is always called (but still empty). The code may explain this better than me:
<!DOCTYPE html> <html> <body> <!-- processDomains.php is this file - it calls itself (for testing purposes so I can see what is happening) --> <form action="processDomains.php" method="post"> <?php // create the domains array (there are actually several entries in the array but I cut it down for testing) $domains = array (1 => 'Decommission', 'Migration'); echo "Select Domain:"; echo "<br>"; // Make the domain pull-down menu - this displays correctly echo '<select name="domain">'; foreach ($domains as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; // input doesn't matter what is 'submitted', always goes to last $value echo '<input type="submit" name="submit" value="Submit">'; // call function subdomains subdomains ($value); function subdomains ($domains) { // define values for each array - each array contains available choices for the subdomain pulldown menu $migration = array (1 => 'Application Migration', 'Application Patch', 'Application Upgrade'); $decommission = array (1 => 'Applications', 'Servers', 'Storage'); if ($domains === 'Migration') { echo "Select subdomain:"; echo "<br>"; // Make the Migration pull-down menu echo '<select name="migration">'; foreach ($migration as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; } else if ($domains === 'Decommission') { /* === * since 'Decommission' is the last entry in the 'Domains' pulldown list, $value ALWAYS equals * 'Decommission' and $domains equals $value. So this menu SHOULD work but is always * empty. Thus, two problems - the pulldown menu is always empty and $value isn't based * upon user input. */ echo "Select subdomain:"; // this prints so I know I'm in 'Decommission (I eliminated the echo "$domain" to show I'm always coming here)' echo "<br>"; // Make the 'Decommission' pull-down menu echo '<select name="decommission">'; foreach ($decommission as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; echo '<input type="submit" name="submit" value="Submit">' ) // end of 'if-else' } // end of function 'subdomain' ?> </form> </body> </html>Let me say thank you in advance and I appreciate the help! I know I'm doing something (or more than one thing) wrong and I hope someone can tell me what it is. Best Regards! Edited by mac_gyver, 19 January 2015 - 09:37 PM. code tags around posted code please I am writing a script that will parse my PHP classes and check for things like coupling, visualize my objects and connections, dependencies, check for convention usage, etc.
So, I have a simple file upload. I'm never saving the files, just get contents and dump the file and work with the string version.
I'm writing it for me, but I figure I might want to open it for others to use in the future, so I may as well write it that way to begin with -- so I need to validate user input. Problem is, the user input is supposed to be valid PHP code. I'm thinking that, as long as I'm careful, I shouldn't be executing any code contained in strings, but I'm no security expert and I want a warm fuzzy that my thought on this is correct. What kinds of things do I need to look out for? Is it possible to inject when working with strings?
My initial thought is to regex the entire file and replace key portions with known replacements. So ( and ) would become !* and !^ or $ would become @~ (combinations that -- I think -- don't make sense to php?) But that may be completely unnecessary processing time if I'm not in any danger, here. Thanks ahead of time for any help.
PS - as a side question -- what's the best way to verify a file is a php file? I know of getimagesize for images, but should I just check for <? to verify it's php? That seems like it would be too easy to fool -- then again, it might not matter much.
-Adam
I have a calendar select date function for my form that returns the date in the calendar format for USA: 02/16/2012. I need to have this appear as is for the form and in the db for the 'record_date' column, but I need to format this date in mysql DATE format (2012-02-16) and submit it at the same time with another column name 'new_date' in the database in a hidden input field. Is there a way to do this possibly with a temporary table or something? Any ideas would be welcome. Doug class curl2{ private $curl_init; private $CURLOPT_URL; public function connect(){ $this->curl_init = curl_init(); } public function debug(){ curl_setopt($this->curl_init, CURLOPT_VERBOSE, TRUE); $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); } public function setUrl($url = null){ $this->CURLOPT_URL = $url; curl_setopt($this->curl_init, CURLOPT_URL, $this->CURLOPT_URL); } public function execute(){ $out = curl_exec($this->curl_init); curl_close($this->curl_init); return $out; } } $curl2 = new curl2; $curl2->connect(); $curl2->setUrl("http://www.linuxformat.co.uk"); $curl2->debug(); echo $curl2->execute(); It display a blank page like attachment result1.jpg, but if I move the $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); from function debug() and join it with function execute() like this: public function execute(){ $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); $out = curl_exec($this->curl_init); curl_close($this->curl_init); return $out; } it return me Linuxformat content ( expected result ) like result2.jpg below is the working code : class curl2{ private $curl_init; private $CURLOPT_URL; public function connect(){ $this->curl_init = curl_init(); } public function debug(){ curl_setopt($this->curl_init, CURLOPT_VERBOSE, TRUE); } public function setUrl($url = null){ $this->CURLOPT_URL = $url; curl_setopt($this->curl_init, CURLOPT_URL, $this->CURLOPT_URL); } public function execute(){ $fp = fopen("curl2.txt", "w"); curl_setopt($this->curl_init, CURLOPT_STDERR, $fp); curl_setopt($this->curl_init, CURLOPT_RETURNTRANSFER, TRUE); $out = curl_exec($this->curl_init); curl_close($this->curl_init); return $out; } } $curl2 = new curl2; $curl2->connect(); $curl2->setUrl("http://www.linuxformat.co.uk"); $curl2->debug(); echo $curl2->execute(); Why I couldn't split "CURLOPT_STDERR, CURLOPT_RETURNTRANSFER" with "curl_exec" Hi people, I really hope you guys can help me out today. I'm just a newbe at php and i'm having real trouble. Bassically all I want to do is have a user type in a company name in a html form. If what the user types in the form matches the company name in my php script i want the user to be sent to another page on my site. If what the user types in the form doesnt match the company name in my php script i want the user to be sent to a differnt page like an error page for example. this is my html form: Code: [Select] <form id="form1" name="form1" method="post" action="form_test.php"> <p>company name: <input type="text" name="company_name" id="company_name" /> </p> <p> <input type="submit" name="button" id="button" value="Submit" /> </p> </form> And this is the php code I'm trying to process the information on: Code: [Select] <?php $comp_name = abc; if(isset ($_POST["company_name"])){ if($_POST["company_name"] == $comp_name){ header("Location: http://www.hotmail.com"); exit(); } else{ header("Location: http://www.yahoo.com"); exit(); } } ?> The thing is i'm getting this error when i test it: Warning: Cannot modify header information - headers already sent by (output started at D:\Sites\killerphp.com\form_test.php:10) in D:\Sites\killerphp.com\form_test.php on line 17 Please can some one help me out, i'm sure this is just basic stuff but i just cant get it to work Cheers. im looking to validate an email address before it gets sent to mysql database currently my code checks if an email address is present and if an email address already exists how do you check to see if an address contains a . and a @ symbol? Code: [Select] if($email == '') { $errmsg_arr[] = 'Email is missing'; $errflag = true; } if($email != '') { $qry = "SELECT * FROM users WHERE email='$email'"; $result = mysql_query($qry); if($result) { if(mysql_num_rows($result) > 0) { $errmsg_arr[] = 'Email address already in use'; $errflag = true; } @mysql_free_result($result); } else { die("Query failed"); } } Thanks in advance I have a form validation script which is written in php.. I want to add a validation (in registration form) that if the desired username contains either admin or owner keyword user will have to change his user name.. I made the following code but it does not work.. if(strpos($user_name, "admin")>=0 || strpos($user_name, "moderator")>=0 || strpos($user_name, "owner")>=0) { $error=$error."You are not allowed to take such Username<br>"; $bool=false; } In this code i am not able to enter any username.. And if i change >= to > then "admin123" username is going to be valid... I am troubled .... help me out guyzzz -pranshu.a.11@gmail.com Hi, I have a mistmatched tag <messagesss></message> BUT it still displays "Validated XML!" BUT then proceeds to the else that outputs each XML error! here is the XML: Code: [Select] <?xml version="1.0" encoding="utf-8"?> <email> <messagesss> <to> <toFirstName>Tove</toFirstName> <toLastName toType="common" style="swag">Smith</toLastName> </to> <from><fromdd/> <fromFirstName>Jani</fromFirstName> <fromLastName fromType="unique">Dravison</fromLastName> </from> </message> </email> Code: [Select] <?php $dom=new DOMDocument(); $dom->load("emailSimple.xml"); $isValidated=false; $dom->formatOutput = true; $dom->saveXML(); $errors=libxml_get_errors();//Returns array where each XML file line is an elem if(!file_exists("emailSimple.xml")) print "no such file!"; else if(strlen(file_get_contents("emailSimple.xml"))==0) print "File is empty!"; else if($dom) {//IF file exists and has content if(empty($errors)) print "Validated XML!";//isValidated=true so now shred! else { //CHECK if current XML file is Well-formed foreach($errors AS $error) {//FOR EACH ERROR OF CURRENT XML FILE TO CHECK echo "Error Code: ".$error->code."<br />"; echo "Error message: ".$error->message; //Column is the end of the line where error is echo "line".$error->line.", column".$error->column."<br />"; echo "----------------------------------------------<br /><br />"; } } libxml_clear_errors(); } ?> Hi, Im making a form that contains 3 textboxes.. now i want my textboxes to contain only letters.. i used is_numeric for the validation but when i put' like.. "JUSHIRO1" my code will still accept it. can someone help me make a code that will validate my textbox to only accept letters. and one more.. when the user input in the textbox with a number a popup box will appear. I am really new to using php validation, I think I may be on to what I am looking for but not very sure. I am trying to validate my form fields just incase someone forgets (name, subject, message, and email). Here is what I have so far. I was looking at an example on how to validate a phone number. Code: [Select] <!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>Contact</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <?php $first_name=$_POST['name']; $email_address=$_POST['email']; $subject=$_POST['subject']; $message=$_POST['text']; if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['email']) != ) { echo "The email field was invalid<BR>"; } else if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['name']) != "") { echo "The name field was invalid<BR>"; } else if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['subject']) != "") { echo "The subject field was invalid<BR>"; } else { mail("myemailaddress@gmail.com","Subject: $subject", $message, "From: $first_name <$email_address>"); echo "Thank you for using our mail form.<br/>"; echo "Your email has been sent."; } ?> </body> </html> So Im in the weird place where my age validation is not working, any ideas: $dob = strtotime($_POST['dob']); //855993600 Feb 15th 1997 $age_req = strtotime('-13 year', $dob); //445680000 Feb 15th 1984 $time = time(); //1292007621 if ($time < $age_req){} Chaps, as a beginner developing his first web app in PHP, I have done fairly well.
However, I am struggling when it comes to validation.
I have written different ELSEIF statements as seen below which would actually carry out the validation itself.
// First name must be filled and in correct format. if(empty($FirstName)) { $errFirstName = '<p class="errText"> Please enter a value</p>'; echo $errFirstName; }elseif(!preg_match('/^[a-z]+$/i',$FirstName)){ $errFirstName = '<p class="errText">Name may not start with a dash. Letters, spaces and dashes are accepted.</p>'; echo $errFirstName; }The problem is that I do not know how to make them "pop up" when the user makes a mistake. I have a form in addteam.php seen below: <form action="pushteam.php" method="post"> <p>Team name: <input type="text" name="TeamName" /></p> <p>Description: </p> <p><textarea name="Description" rows="4" cols="50">Add your description here.</textarea></p> <p><input type="submit"/></p> </form>And a pushplayer.php script that pushes it to a mysql database: // Get values from form $TeamName=$_POST['TeamName']; $Description=$_POST['Description']; } // Insert data into database $sql="INSERT INTO Teams(TeamName, Description)VALUES('$TeamName', '$Description')"; $result=mysql_query($sql); //If successful return to success.php else print error if($result){ header( 'Location: success.php'); } else { header( 'Location: failure.php'); }The scripts function properly. I would really appreciate if someone could guide me in the right direction here. Make the error pop up and make sure the data is not input. At the moment, if I add my ELSEIF statements, it will carry on and insert the data anyway and redirect me. Thanks |