Jump to content

is_string() not working as i expected


Ugluth

Recommended Posts

Hello I want to check that a variable the user enters is not empty and that it is a string (no numbers). Here is what i have written:

 

<?php
include('css/layout.css.php');
include('css/menu.css');
if (isset($_POST['submit'])) {
include('includes/dbconn.php');
if (is_string($_POST['name']) && strlen($_POST['name']) > 0) {
	$name = mysql_real_escape_string($_POST['name']);
} else {
	echo "Category name must be a word!<br />";
}
if (isset($name)) {
	echo $name;
} else {
	echo "something";
}
}
?>

 

and this is the form i'm getting the data from:

 

		<form action="category_add.php" method="post">
		<table class="table-view">
		  <tr>
		    <td><label for="name">Category Name</label></td>
		    <td><input type="text" name="name" id="name"></td>
		  </tr>
		  <tr>
		  	<td><input type="submit" value="Save changes" name="submit" id="submit"></td>
		  </tr>
		</table>
     </form>

 

If i enter nothing it works fine, if i enter a string it also works fine, the problem is when i enter 123 in the textbox, i dont get the "Category name must be a word!" as i expected i would. Could someone help me with this one please?

 

Thanks in advance.

Link to comment
Share on other sites

is_string() will not tell you whether all characters are letters. is_string() only tells you whether what you passed to it is a string. a string can include numbers. for example, this is a string: "hello 123 world";

 

If you want to tell whether there are any numbers, I would use preg_replace like this:

 

if (!empty($_POST['name'])) && strlen(preg_replace("/[\D]/","",$_POST['name'])) == 0) {
       // $_POST['name'] contains no numbers
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.