What's wrong with this preg_match() usage? I want to check steam lobby link and if it's matching then write to database. If not, just echo the error. I am doing this through ajax. Is it better to do this with ajax or $_SERVER["REQUEST_METHOD"] == "POST"?
<?php
require("../includes/config.php");
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^((steam?:)+(/joinlobby\/730\/)+([0-9]{17,25}\/.?)+([0-9]{17,25})/$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
else {
$rank = "Golden";
$mic = "No";
try {
$stmt=$db->prepare("INSERT INTO created_lobby (lobby_link, current_rank, have_mic) VALUES (:lobby_link, '$rank', '$mic')");
$stmt->execute(array(
':input_link' => $_POST['lobbyLink']
));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
My Problem:
When I execute this code, it will give me false.
Thank you for help.
This works:
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^(steam?:)+(//joinlobby/730/)+([0-9]{17,25}/.?)+([0-9]{17,25}$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
I changed /joinlobby to //joinlobby, and remove the / at the end. I also removed the unnecessary () around everything.
I suspect you also shouldn't have (...)+ around steam?: and //joinlobby/730/. They'll cause repeated uses of those prefixes to be accepted as correct, e.g. steam:steam:...
Related
I am trying to create a profile editing setup. It seems as though the information is edited only when an image is being uploaded. I found out that allowing the error message to be a condition allows for some more manipulation so I attempted it now my condition statement is not working as it should.
if($_FILES['files']['error']==0) {
print_r($_FILES['files']['error']);
echo "if";
foreach($_FILES['files']['name'] as $file => $name) {
$filename = $name;
try{
if(move_uploaded_file($_FILES['files']['tmp_name'][$file],'uploads/'.$filename)) {
$updateInfo = $db->prepare("UPDATE users SET image = :image, aboutme = :aboutme WHERE id = :id");
$updateInfo->bindParam(":image", $filename);
$updateInfo->bindParam(":id", $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
}
} catch(Exception $e) {
echo $e;
}
}
} elseif($_FILES['files']['error'] == 4) {
print_r($_FILES['files']['error']);
echo "Elseif";
try{
$updateInfo = $db->prepare("
UPDATE users
SET
aboutme = :aboutme
WHERE id = :id
");
$updateInfo->bindParam(':id', $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
} catch(Exception $e) {
echo $e;
}
} else{
print_r($_FILES['files']['error']);
echo "else";
}
}
When I check what array is being sent, its the correct one but the wrong condition, ie: it would run the else statement no matter the file check.
My question:
Is there something wrong with my code, with the exception of any security or efficiency flaws?
$_FILES['files']['error'] returns error code along with the file array. There are different type of error codes, all codes are mentioned in following link with details:
Please check by
print_r($_FILES['files'])
and see what are you getting in response.
As you posted your array response, you can get error code by $_FILES['files']['error'][0] or use switch case as mentioned in following link.
See here for more details:
http://php.net/manual/en/features.file-upload.errors.php
Also regarding debugging, always debug code step by step from top to bottom. Check $_POST, $_FILES, $_SERVER etc details if you get some problem particular related to data process.
this is my coding
i think there is something wrong in the validation part.
can plz anyone help me?
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("school", $con);
$student_fname=$_POST['student_fname'];
$student_lname=$_POST['student_lname'];
$student_ic=$_POST['student_ic'];
$student_age=$_POST['student_age'];
$student_race=$_POST['student_race'];
$student_gender=$_POST['student_gender'];
$student_phone=$_POST['student_phone'];
$student_class=$_POST['student_class'];
$student_email=$_POST['student_email'];
$student_add=$_POST['student_add'];
$student_city=$_POST['student_city'];
$student_state=$_POST['student_state'];
$student_postcode=$_POST['student_postcode'];
$student_id=$_POST['student_id'];
$student_pswd=$_POST['student_pswd'];
$student_cpswd=$_POST['student_cpswd'];
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false) {
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
}
if (ctype_alpha(str_replace(' ', '', $student_lname)) === false) {
echo "<script language='Javascript'>alert('Student Last Name must only contain letters!');
location.href='rstudent.php'</script>";
}
if (ctype_alpha(str_replace(' ', '', $student_city)) === false) {
echo "<script language='Javascript'>alert('City must only contain letters!');
location.href='rstudent.php'</script>";
}
if($student_pswd==$student_cpswd)
{
$sql="INSERT INTO student (student_fname, student_lname, student_ic, student_age,
student_race, student_gender, student_phone, student_class, student_email, student_add,
student_city, student_state, student_postcode, student_id, student_pswd, student_cpswd)
VALUES
('$_POST[student_fname]', '$_POST[student_lname]', '$_POST[student_ic]', '$_POST[student_age]',
'$_POST[student_race]', '$_POST[student_gender]', '$_POST[student_phone]',
'$_POST[student_class]', '$_POST[student_email]', '$_POST[student_add]', '$_POST[student_city]',
'$_POST[student_state]', '$_POST[student_postcode]', '$_POST[student_id]',
'$_POST[student_pswd]', '$_POST[student_cpswd]')";
}
else
{
echo "<script language='Javascript'>alert('Password must match!');
location.href='rstudent.php'</script>";
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<script language='Javascript'>alert('The Student Profile Has been Successfully
Registered!!!');
location.href='srecords.php'</script>";
mysql_close($con)
?>
why is my validation for only letters, when inserted numbers it still add in the database?
It's because the script continues it's normal execution when one of the validation statements fails.
Meaning, you are just echo-ing some javascript but this won't do anything to the normal php flow. The javascript will be outputed after php has done it's processing and inserted the values in the database.
In the IF statements you must take another action that will prevent the script in reaching the DB insert part.
Simplest solution for your case:
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false)
{
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
exit;
}
Notice the "exit" in the IF statement. This will cause the script to end execution when the validation fails, preventing the insert.
A better solution would be to have something like:
$form_validation = true;
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false)
{
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
$form_validation = false;
}
if($form_validation == false)
{
echo 'Form validation failed';
exit;
}
else
{
/* insert the values in the DB */
}
The solution above would allow you to check all statements before ending execution.
It would also be best to redirect using header('Location: rstudent.php'); exit; but this would require you to save the message in the $_SESSION and then check them.
So the best solution would be to save all error messages in an array, check the array if it's empty at the end of validation and if it's not save the error messages in the user $_SESSION, redirect the page using header('Location: rstudent.php''); exit; and in that page check for errors, display them to the user and clear them so that they won't show again :)
Nothing in this code remembers when a value was identified as invalid. You're generating some javascript, but not telling PHP to do anything else. Remember, by the time the javascript is rendered in the browser, the PHP server has already finished processing the PHP.
Create a variable such as $passes_validation=true;, Then everywhere you have a validation step, set $passes_validation=false; when the validation fails. Something like this:
$passes_validation=true;
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false) {
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
$passes_validation=false;
}
Then, only execute the sql if $passes_validation==true. Something like this:
if($passes_validation){
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
}
I've been playing around with a php class I found on the net called Config Magik that I use to store some info in a INI file but have recently run into some problems when using removeKey. I wanted to know if someone can point me to a similar class that would work as well or better. Or if there is a better way to go about this.
This is my function right now, after playing around with it like crazy, so it is probably very faulty.
require_once('class.ConfigMagik.php');
$config = new ConfigMagik('config.ini', true, true);
if(!empty($_GET)){
if(!is_writeable('config.ini')){
echo 'Could not write to config.ini';
return false;
}
//if there is no section parameter, we will not do anything.
if(!isset($_GET['section'])){
echo false; return false;
} else {
$section_name = $_GET['section'];
unset($_GET['section']); //Unset section so that we can use the GET variable to manipulate the other parameters in a foreach loop.
if (!empty($_GET)){
foreach ($_GET as $var => $value){
echo $var.'='.$_GET[$var].'<br />';
//Check if said variable $var exists in the section.
if($config->get($var, $section_name) !== NULL){
//Set variable value.
try{
$config->set($var, $value, $section_name);
echo 'Setting variable '. $var.' to '.$value.' on section '.$section_name;
} catch(Exception $e) {
echo 'Could not set variable '.$var;
echo $e;
return false;
}
} else {
echo $var.' does not exist <br />';
}
}
}
try{
$section = $config->get($section_name); //Get the entire section so that we can manipulate it.
echo '<pre>';print_r($section);echo '</pre>';
foreach ($section as $title=>$value){
if(!isset($_GET[$title]) && isset($section[$title])){
try{
$config->removeKey($title, $section_name);
echo '<b>'.$title.'</b>: removed <br />';
} catch(Exception $e){
echo $e;
}
}
}
} catch(Exception $e){
echo $e;
}
$config->save();
//echo $config->toString('HTML');
echo true;
return true;
}
} else { RUN SOME HTML }
It basically saves the settings I pass on from the GET parameters and if the parameters are not there it is supposed to delete it. When I get to $config->removeKey($title, $section_name); in the last try catch statement it won't save automatically (as it should), so I tried running $config->save() and I ended up with a ini file that had section = array everywhere. Any advice will be appreciated as I've been learning PHP on the web for the last few weeks so I believe I've got a ways to go.
I have definitely isolated the problem to the $config->save() part, just don't know how to solve it.
Thanks in advance.
I have been using Zend_Config_Ini and Zend_Config_Writer_Ini in the past and was satisfied with the features. You will have extract the whole library/Zend/Config folder from Zend Framework and make Zend_Exception available though.
....
else {
$affiliate->setStatus('D');
echo "Before load";die;
if($affiliate->load())
{
echo $affiliate->getUsername();
die(($affiliate->getUsername())."Success to load affiliate");
}
else
{
$chkaffiliate= new Pap_Api_Affiliate($session);
$chkaffiliate->setUsername($_POST['txt_email']);
if($chkaffiliate->load())
{
echo $chkaffiliate->getUsername();
}
die("Failed to load affiliate");
}
die("Failed to process payment,account request declined. <br><br>Please try again using a different email OR Contact our support team to manually approve your account.".$response->error_message);
}
I get the output Failed to process payment...that is, the last die() in the above code, however I don't get the Before Load in the first echo, while both are in the same block. Any ideas?
This is just not possible.
if (something){
die();
}
else{
die();
}
dies everytime, in any case. Search for other die("Failed to process payment"); function calls
Your problem is with this line:
echo "Before load";die;
You die immediately after the echo statement so no other processing will take place!
when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}