What is best way to optimize code and query? - php

I have hundreds of response from php IMAP (fetching email), I wanted to insert all the fetched email into database. Problem is that on server stay time is 40 second (Host provider said to me) and my script is taking more than 40 second. Due to the fetching records and insert queries server returning the following error.
[an error occurred while processing this directive]
Here is Php Code
$imap = #imap_open("{mail.******.com:143/novalidate-cert}", '*****#***.com', '*****');
if(isset($imap)){
$message_count = #imap_num_msg($imap);
$array_mail = array();
if($message_count > 0){
for ($m = 1; $m <= $message_count; ++$m){
//$header = #imap_header($imap, $m);
$header = #imap_rfc822_parse_headers(imap_fetchheader($imap, $m));
$email[$m]['from'] = $header->from[0]->mailbox.'#'.$header->from[0]->host;
$from = $email[$m]['fromaddress'];
$from_email = $email[$m]['from'];
$array_mail[] = $from_email;
if(isset($header->cc)){
$hedCC = $header->cc;
foreach($hedCC as $s){
//echo $s->mailbox.'#'.$s->host.'<br />';
$array_mail[] = $s->mailbox.'#'.$s->host;
}
}
if(isset($header->to)){
$hedTO = $header->to;
foreach($hedTO as $t){
//echo $t->mailbox.'#'.$t->host.'<br />';
$array_mail[] = $t->mailbox.'#'.$t->host;
}
}
}
$i = 0;
if (!empty($array_mail)) {
$insertCount = 0;
foreach($array_mail as $m_){
// INSERT HERE
//echo $m_.'<br />';
$isExistWithID = $this->isExistWithID($user_id,$m_);
$email_err = $this->isValidEmail($m_);
$isValid = 0;
if($email_err == false){
$isValid = 1;
}
if($isExistWithID==0 && $isValid==0){
$insert = $this->pdoConnection->prepare("
INSERT INTO ws_email (
u_id,
we_email,
date_added
)
VALUES(
:u_id,
:we_email,
:date_added
)
");
$insert->bindParam(':u_id', $u_id);
$insert->bindParam(':we_email', $we_email);
$insert->bindParam(':date_added', $date_added);
// Insert Data
$u_id = $_SESSION['USERID'];
$we_email = $m_;
$date_added = date("Y-m-d H:i:s");
if($insert->execute()){
$insertCount++;
}
}
$i++;
}// end foreach
$response['success'] = $insertCount.'Email address(s) fetched successfully.';
}
//echo $i;
//
}else{
$response['error'] = 'No record found';
}
}else{
$response['error'] = 'IMAP does not connect';
}
}//end if error is equal to 0
/************ END NEW 29 SEP *************/
echo json_encode($response, JSON_PRETTY_PRINT);
I tried to optimize the code as i can, but still taking long time and due to this server returning the error.
I would like to request to you kindly guide me how can i optimize it. Thank You.

Related

depending on condition show error message in php

i have code like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
if(!preg_match("/^(?=.*[0-9])(?=.*[a-z])(\S+)$/i", $_POST['password']))
{
$errorMessage="don't allow spaces";
}
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}
else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
so i want to write condition like another if condition
if ( $chk_secret->status='0' ) {
$errorMessage = "your access code deactivated..";
}
if not they can register
i tried..but i didn't get idea where i have to add that if..
before i have condition like if number>used it will show some error message like your accesscode limit completed
can anyone help me..
thanks in advance..
= is for value assignment
== is compare two operands
so you need to change
if ( $chk_secret->status='0' ) {
to
if ( $chk_secret->status=='0' ) {
UPDATE:
your query SELECT * FROM {accesscode} WHERE random_no= ? and status=1
which means it going to return only status == 1
you can check with number of rows returned is ZERO then through status zero error message.
Or else
Get rows only based on random_no exists and then check status key

How can i fix [an error occurred while processing this directive]?

I'm trying to fetch email from inbox using php imap(). In localhost function works fine but on our bluehost based dedicated server it showing following error
[an error occurred while processing this directive]
Php Code
$imap = #imap_open("{mail.******.com:143/novalidate-cert}", "a****i#*****.com", "******");
if(isset($imap)){
$message_count = #imap_num_msg($imap);
$array_mail = array();
if($message_count > 0){
for ($m = 1; $m <= $message_count; ++$m){
//$header = #imap_header($imap, $m);
$header = #imap_rfc822_parse_headers(imap_fetchheader($imap, $m));
$email[$m]['from'] = $header->from[0]->mailbox.'#'.$header->from[0]->host;
//$email[$m]['fromaddress'] = $header->from[0]->personal;
//$email[$m]['to'] = $header->to[0]->mailbox;
//$email[$m]['cc'] = $header->cc[0]->mailbox;
//$email[$m]['subject'] = $header->subject;
//$email[$m]['message_id'] = $header->message_id;
//$email[$m]['date'] = $header->udate;
//$from = $email[$m]['fromaddress'];
$from_email = $email[$m]['from'];
$array_mail[] = $from_email;
if(isset($header->cc)){
$hedCC = $header->cc;
foreach($hedCC as $s){
echo $s->mailbox.'#'.$s->host.'<br />';
//$array_mail[] = $s->mailbox.'#'.$s->host;
}
}
if(isset($header->to)){
$hedTO = $header->to;
foreach($hedTO as $t){
echo $t->mailbox.'#'.$t->host.'<br />';
//$array_mail[] = $t->mailbox.'#'.$t->host;
}
}
}
$i = 0;
if (!empty($array_mail)) {
$insertCount = 0;
foreach($array_mail as $m_){
// INSERT HERE
//echo $m_.'<br />';
$isExistWithID = $this->isExistWithID($user_id,$m_);
$email_err = $this->isValidEmail($m_);
$isValid = 0;
if($email_err == false){
$isValid = 1;
}
if($isExistWithID==0 && $isValid==0){
$insert = $this->pdoConnection->prepare("
INSERT INTO ws_email (
u_id,
we_email,
date_added
)
VALUES(
:u_id,
:we_email,
:date_added
)
");
$insert->bindParam(':u_id', $u_id);
$insert->bindParam(':we_email', $we_email);
$insert->bindParam(':date_added', $date_added);
// Insert Data
$u_id = $_SESSION['USERID'];
$we_email = $m_;
$date_added = date("Y-m-d H:i:s");
if($insert->execute()){
$insertCount++;
}
}
$i++;
}// end foreach
$response['success'] = $insertCount . ' Email address(s) fetched successfully.';
}
//echo $i;
//
}else{
$response['error'] = 'No record found';
}
}else{
$response['error'] = 'IMAP does not connect';
}
/************ END NEW 29 SEP *************/
echo json_encode($response, JSON_PRETTY_PRINT);
Can anyone kindly guide me where is the issue that i can fix. I would like to appreciate. Thank You.
EDITED
I added ticket to host provider. Following are the comments,
This error is because of a the FCGI timeout. This can be fixed by changing to suphp. You can change the php type in the whm to suphp on the Main >> Service Configuration >> Apache Configuration >> PHP and SuExec Configuration page. I suggest to closely watch the website with that to suphp as it makes the server more vulnerable to scripts running unchecked.

PHP API returning wrong response for android app

I am creating a API for android developer in PHP in which he want to delete some values from database and want to show a message after that.
Now the problem is this data is deleting successfully but this API always shows else part message after complete the process. If I remove the else part its return the null which crash the android app. So I just want to give a proper json message to the android developer
Here is the code which I am trying
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1)
{
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_count as $table_count)
{
$user_count = mysql_query("select * from $table_count where user_name = '$user_name'");
$total_user_count = mysql_num_rows($user_count);
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
}
}
I know there is something wrong with this logic. But I need expert advise where my logic is wrong and what I have to do make it success
Problem with your original code, is that you are setting success/failure inside the loop. One of the four table may/may not contain the username. And if the last table don't have that, then as per your logic you are getting "record not found" even if previous iteration of the loop deleted data from the tables where username exists.
<?php
$conn = mysqli_connect(.....);
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1) {
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
$userHistoryDeleted = 0;
foreach($tables_count as $table_count) {
//if history is found, then it will be deleted otherwise not
mysql_query("delete from $table_count where user_name = '$user_name'");
if(mysqli_affected_rows($conn)) {
$userHistoryDeleted = 1;
}
}
$msg = 'Record Not Found!';
if($userHistoryDeleted) {
$msg = 'Clear Successfully All History!';
}
$response['success'] = $userHistoryDeleted;
$response['user']['error_msg'] = $msg;
}
Change your code :
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
to this one
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
}
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}

Error while parsing JSON from Database for Android App. (No tag defined)

I have created a json for getting mysql data for a news app in android & ios. Whenever I am parsing the json.php file it returns "No tag defined" and the app stopped working both android and ios. Here is the code sample that I was trying to work out.
<?php
header('content-type: application/json; charset=utf-8');
$con = mysql_connect("localhost","####","###");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("###", $con);
$date = date('Y-m-d');
//$date = '2014-02-01';
$year = substr($date, 0, -6);
$month = substr($date, 5, -3);
$day = substr($date,-2, 10);
if($month==01) $month1="january";
else if($month==02) $month1="february";
else if($month==03) $month1="march";
else if($month==04) $month1="april";
else if($month==05) $month1="may";
else if($month==06) $month1="june";
else if($month==07) $month1="july";
else if($month==08) $month1="august";
else if($month==09) $month1="september";
else if($month==10) $month1="october";
else if($month==11) $month1="november";
else if($month==12) $month1="december";
$table=$month1.$year;
//$table = $february2014;
if(isset($_REQUEST['tag']) && $_REQUEST['tag'] != ''){
$tag = $_REQUEST['tag'];
if($tag =='category_page' && isset($_REQUEST['menu_id']) && $_REQUEST['menu_id'] !='' ) {
$menu_id = $_REQUEST['menu_id'];
try{
$i=0;
$query = mysql_query("SELECT * FROM $table WHERE menu_id=1 AND news_date ='$date'");
if($query === FALSE) {
die(mysql_error());
}
while($data=mysql_fetch_array($query)){
$responce[$i]['news_id'] = $data['news_id'];
$responce[$i]['news_title'] = str_replace("\t",'',str_replace("\r\n\t",'', substr(strip_tags($data['news_title']),0,110)));
$responce[$i]['news_reporter'] = str_replace("\t",'',str_replace("\r\n\t",'', substr(strip_tags($data['news_reporter']),0,110)));
$responce[$i]['news_details'] = str_replace("\t",'',str_replace("\r\n\t",'', substr(strip_tags($data['news_details']),0,110)));
$responce[$i]['photo'] = $data['photo'];
$responce[$i]['path'] = 'admin/'.str_replace('\\','',$data['path']);
$responce[$i]['menu_id'] = $data['menu_id'];
$responce[$i]['menu_type'] = $data['menu_type'];
$responce[$i]['news_publish_status'] = $data['news_publish_status'];
$responce[$i]['news_order'] = $data['news_order'];
$responce[$i]['news_date'] = $data['news_date'];
$responce[$i]['news_time'] = $data['news_time'];
$responce[$i]['added_by'] = $data['added_by'];
$responce[$i]['directory'] = $data['directory'];
$responce[$i]['read_number'] = $data['read_number'];
$responce[$i]['comment_number'] = $data['comment_number'];
$responce[$i]['news_comment_table_name'] = $data['news_comment_table_name'];
$i++;
}
} catch(Exception $e) {
$responce = 'Exception: '.$e->getMessage();
}
}else{
$responce = "category or Menu id is not Defined";
}
echo json_encode($responce);
}else{
echo json_encode("No tag Defined");
}
?>
not getting any way to fix it up. can any one help me out.Would appreciate your kind assistance.
Try this
if(isset($_REQUEST['tag'])){
Instead of
if(isset($_REQUEST['tag']) && $_REQUEST['tag'] != ''){

Resource id #6 error, Not sure how to fix it

I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.

Categories