How to create a .csv file from the results of an array? - javascript

I'm using a PHP class to Check the email validity in real-time,
The PHP Script works fine: Check the emails and print the results in the same page creating a <td> element for each validated email.
My problem is I'm trying to validate around 200,000 emails... the result of the script is a huge list causing my browser to stop working.
Is it possible to create a .csv file with the results instead of just print them on the page? If so, how can I do this?
Here is my source code:
index.php <-- this is the file that shows the results.
emailvalid.php <-- This is the PHP Class
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>EmailValid</title>
<!-- Meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="favicon.ico">
<link href='http://fonts.googleapis.com/css?family=Lato:300,400,300italic,400italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!-- Global CSS -->
<link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css">
<!-- Plugins CSS -->
<link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css">
<link rel="stylesheet" href="assets/plugins/prism/prism.css">
<!-- Theme CSS -->
<link id="theme-style" rel="stylesheet" href="assets/css/styles.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body data-spy="scroll">
<!---//Facebook button code-->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!-- ******PROMO****** -->
<section id="promo" class="promo section offset-header">
<div class="container text-center">
<h2 class="title">Email<span class="highlight">Valid</span></h2>
<p class="intro">Check the email validity in real-time
<form method="post">
<textarea rows="10" cols="150" style="color:black" name="email" placeholder="Insert here your text. The robot will extract all the emails from the text"></textarea>
</p>
<div class="btns">
<input type="submit" value="Check" name="Check" class="btn btn-cta-secondary">
</div>
</form>
<?php include 'assets/emailvalid.php'; ?>
<ul class="meta list-inline">
</ul><!--//meta-->
</div><!--//container-->
</section><!--//promo-->
<!-- Javascript -->
<script type="text/javascript" src="assets/plugins/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="assets/plugins/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="assets/plugins/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/plugins/jquery-scrollTo/jquery.scrollTo.min.js"></script>
<script type="text/javascript" src="assets/plugins/prism/prism.js"></script>
<script type="text/javascript" src="assets/js/main.js"></script>
</body>
</html>
<?php
$show_details ='yes'; // choice : 'yes' or 'no'
$disposable_email ='yes'; // choice : 'yes' or 'no'
$check_mx ='yes'; // choice : 'yes' or 'no'
if(!empty($_POST['Check'])){
if(!empty($_POST['email'])){
$emails = get_email($_POST['email']);
require_once('emailvalidclass.php'); //include emailvalidclass.php file
$emailChecker = new emailChecker; // Make a new instance
if($show_details=='yes'){ $emailChecker->supress_output = 0; }else{ $emailChecker->supress_output = 1; }
if($disposable_email=='yes'){ $emailChecker->filter_dea = 1; }else{ $emailChecker->filter_dea = 0; }
if($check_mx=='yes'){ $emailChecker->check_mx = 1; }else{ $emailChecker->check_mx = 0; }
$emailChecker->smtp_test = 0;
$emailsubmited=count($emails);
echo '<br><b>Emails : </b>'.$emailsubmited;
echo '<hr><table cellpadding="10" cellspacing="10" border="1" style="margin-top: 15px;">
<tr style="font-size:20px;background-color:black;color:white">
<td>Email</td>
<td>Passed</td>';
if($show_details=='yes'){
echo '<td style="text-align:left">Email valid ?</td>';
if($disposable_email=='yes'){
echo '<td>Disposable ?</td>';
}
if($check_mx=='yes'){
echo '<td>Domain MX Check ?</td>';
}
}
echo ' </tr>';
$array_good_emails=array();
$array_bad_emails=array();
$array_good_no_duplicate_emails=array();
foreach((array)$emails as $key=>$e){
if(empty($e)) continue;
$e = $emailChecker->check($e);
$e = $e['result'];
// echo '<pre>';
// print_r($e);
// echo '</pre>';
if($e['success']){
$array_good_emails[]=htmlspecialchars($e['query']);
}else{
$array_bad_emails[]=htmlspecialchars($e['query']);
}
?>
<tr>
<td><?php echo htmlspecialchars($e['query']); ?></td>
<?php if($e['success']){
echo '<td style="background-color:green">yes</td>';
}else{
echo '<td style="background-color:red">no</td>';
}
?>
<td>
<?php if(!empty($e['report']['validate_email'])){
echo 'yes';
}elseif(!empty($e['errors']['validate_email'])){
echo 'no';
}
?>
</td>
<?php if($show_details=='yes'){ ?>
<?php if($disposable_email=='yes'){ ?>
<td>
<?php if(!empty($e['report']['filter_dea'])){
echo 'no';
}elseif(!empty($e['errors']['filter_dea'])){
echo 'yes';
}else{
echo '-';
}
?>
</td>
<?php } ?>
<?php if($check_mx=='yes'){ ?>
<?php if(!empty($e['report']['check_mx'])){
echo '<td>yes</td>';
}elseif(!empty($e['errors']['check_mx'])){
echo '<td>no</td>';
}else{
echo '<td>-</td>';
}
?>
<?php } ?>
<?php } ?>
</tr>
<?php
}
echo '</table><br><br>';
?>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">Show Passed/Good Emails</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse in" style="height: auto;">
<div class="panel-body" style="color:black">
<?php echo implode("<br>",$array_good_emails); ?>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h6 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="collapsed">Show Bad Emails</a>
</h6>
</div>
<div id="collapseOne" class="panel-collapse collapse" style="height: 0px;">
<div class="panel-body" style="color:black">
<?php echo implode("<br>",$array_bad_emails); ?>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseFour" class="collapsed">Show Passed/Good Emails (without duplicate emails) </a>
</h4>
</div>
<div id="collapseFour" class="panel-collapse collapse">
<div class="panel-body" style="color:black">
<?php $array_good_no_duplicate_emails=array_unique($array_good_emails);
echo implode("<br>",$array_good_no_duplicate_emails); ?>
</div>
</div>
</div>
<?php
}else{
echo 'Email field empty. Please, try again';
}
}
function get_email($text) {
## Regex taken from http://bit.ly/Tq2PYP PHP's FILTER_VALIDATE_EMAIL function.
$email_pattern = "/(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))/i";
$raw = $text;
$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
$content = str_replace($newlines, "----", html_entity_decode($raw));
$content2 = preg_replace("/\s/", "-", $content);
$content2 = preg_replace("/\-+/", "|", $content2);
$content2 = explode("|", $content2);
$emails = array();
foreach( $content2 as $line) {
preg_match("/#/", $line, $match);
if( count($match) > 0 ) {
preg_match_all($email_pattern, $line, $email_match);
if( count($email_match) > 0 ) {
foreach($email_match[0] as $key=>$email) {
$emails[] = $email;
}
}
}
}
return $emails;
}
?>
I try to follow the instructions given on the answers from #jason and it works now the resulting emails are saved on a CSV file... but the csv file has repeated information and the headers from my index.php are printed as a columns.
Here is my code:
<?php
$show_details ='no'; // choice : 'yes' or 'no'
$disposable_email ='no'; // choice : 'yes' or 'no'
$check_mx ='no'; // choice : 'yes' or 'no'
if(!empty($_POST['Check'])){
if(!empty($_POST['email'])){
$emails = get_email($_POST['email']);
require_once('emailvalidclass.php'); //include emailvalidclass.php file
$emailChecker = new emailChecker; // Make a new instance
if($show_details=='yes'){ $emailChecker->supress_output = 0; }else{ $emailChecker->supress_output = 1; }
if($disposable_email=='yes'){ $emailChecker->filter_dea = 1; }else{ $emailChecker->filter_dea = 0; }
if($check_mx=='yes'){ $emailChecker->check_mx = 1; }else{ $emailChecker->check_mx = 0; }
$emailChecker->smtp_test = 0;
$emailsubmited=count($emails);
$fileName = 'emails.csv';
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");
$fh = #fopen( 'php://output', 'w' );
$headerDisplayed = false;
$array_good_emails=array();
$array_bad_emails=array();
foreach((array)$emails as $key=>$e){
// Add a header row if it hasn't been added yet
if(empty($e)) continue;
$e = $emailChecker->check($e);
$e = $e['result'];
if($e['success']){
$array_good_emails[]=htmlspecialchars($e['query']);
}else{
$array_bad_emails[]=htmlspecialchars($e['query']);
}
// Put the data into the stream
fputcsv($fh, $array_good_emails);
}
// Close the file
fclose($fh);
// Make sure nothing else is sent, our file is done
exit;
}
}else{
}
function get_email($text) {
## Regex taken from http://bit.ly/Tq2PYP PHP's FILTER_VALIDATE_EMAIL function.
$email_pattern = "/(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))/i";
$raw = $text;
$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
$content = str_replace($newlines, "----", html_entity_decode($raw));
$content2 = preg_replace("/\s/", "-", $content);
$content2 = preg_replace("/\-+/", "|", $content2);
$content2 = explode("|", $content2);
$emails = array();
foreach( $content2 as $line) {
preg_match("/#/", $line, $match);
if( count($match) > 0 ) {
preg_match_all($email_pattern, $line, $email_match);
if( count($email_match) > 0 ) {
foreach($email_match[0] as $key=>$email) {
$emails[] = $email;
}
}
}
}
return $emails;
}
?>
And this is produced csv file:
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>EmailValid</title>
<!-- Meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="favicon.ico">
<link href='http://fonts.googleapis.com/css?family=Lato:300 400 300italic 400italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400 700' rel='stylesheet' type='text/css'>
<!-- Global CSS -->
<link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css">
<!-- Plugins CSS -->
<link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css">
<link rel="stylesheet" href="assets/plugins/prism/prism.css">
<!-- Theme CSS -->
<link id="theme-style" rel="stylesheet" href="assets/css/styles.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body data-spy="scroll">
0
<!-- ******PROMO****** -->
<section id="promo" class="promo section offset-header">
<div class="container text-center">
<h2 class="title">Email<span class="highlight">Valid</span></h2>
<p class="intro">Check ZSBox email list validity in real-time
<form method="post">
<textarea rows="10" cols="150" style="color:black" name="email" placeholder="Insert here your text. The robot will extract all the emails from the text"></textarea>
</p>
<div class="btns">
<input type="submit" value="Check" name="Check" class="btn btn-cta-secondary">
</div>
</form>
aksboneyard#sbcglobal.net
aksboneyard#sbcglobal.net al__franco#sbcglobal.net
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com akula_6#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com akula_6#yahoo.com akurt79#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com akula_6#yahoo.com akurt79#yahoo.com al81g#hotmail.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com akula_6#yahoo.com akurt79#yahoo.com al81g#hotmail.com alaguvenkat#yahoo.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com akula_6#yahoo.com akurt79#yahoo.com al81g#hotmail.com alaguvenkat#yahoo.com al.jones#aig.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com akula_6#yahoo.com akurt79#yahoo.com al81g#hotmail.com alaguvenkat#yahoo.com al.jones#aig.com alagu6#hotmail.com
aksboneyard#sbcglobal.net al__franco#sbcglobal.net aladydot#aol.com alabama_annie#yahoo.com alac471#yahoo.com akulovvpshark#yahoo.com akw408#yahoo.com aksingh#bnr.ca aksnownow#mytalk.com aktiva#c2i.net alaa_al_saeed#yahoo.com aks0355#aol.com alabamaalex#yahoo.com al77blackwolf7#email.com akula_6#yahoo.com akurt79#yahoo.com al81g#hotmail.com alaguvenkat#yahoo.com al.jones#aig.com alagu6#hotmail.com
Any help on this matter will be much appreciated.
Thank you.

To create a CSV line from an array, use $csv_line = implode(',',$array_line);
Spit that out to a file with CSV extension and viola!
Also, could give a more in depth answer if I saw a print_r() example of the arrays you are working with(ie if any loops are needed, etc).

You will probably have up the max execution to stop it from timing out.
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
This code will generate the csv you'll have to modify it for your needs:
<?php
function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
}
// Using the function
$sql = "SELECT * FROM table";
// $db_conn should be a valid db handle
// output as an attachment
query_to_csv($db_conn, $sql, "test.csv", true);
// output to file system
query_to_csv($db_conn, $sql, "test.csv", false);
?>

Here's what you need:
$fileName = 'emails.csv';
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");
$fh = #fopen( 'php://output', 'w' );
$headerDisplayed = false;
foreach ( $your_emails_array as $data ) {
// Add a header row if it hasn't been added yet
if ( !$headerDisplayed ) {
// Use the keys from $data as the titles
fputcsv($fh, array_keys($data));
$headerDisplayed = true;
}
// Put the data into the stream
fputcsv($fh, $data);
}
// Close the file
fclose($fh);
// Make sure nothing else is sent, our file is done
exit;

Related

how to restrict the user not to post again on the same page if already posted

I have the below code for User Rating & Comment system which is working fine, but user can post and rate again and again.
I want that if a user posted comment already he/she should not see the comment box but a message that " You have already posted comment on this page".
I tried by using the query in the Add-Comment.php but did not worked.
Need help to solve this issue. Thanks
URL: index.php?id=1
Add-Comment.php
<?php
session_start();
$ipaddress = $_SERVER["REMOTE_ADDR"];
$users = session_id();
if(!empty($_POST)){
extract($_POST);
if($_POST['act'] == 'add-com'):
$comment = htmlentities($comment);
$rating = htmlentities($rating);
// Connect to the database
require_once '../../inc/db.php';
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
$sql = "INSERT INTO rest_rating (rate, comment, sr_id, ip, user)
VALUES ('$rating', '$comment', '$id_post', '$ipaddress', '$users')";
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt = $db->query($sqls);
if ( $tt['user'] == $users ) {
echo '<font size="3" color="red">You Have Already Rated For This Restaurant</font>';
}elseif ( $db->query($sql)==true) {
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<!--<h5><?php echo $name; ?></h5>-->
<b>Rating : </b><?php echo $rating; ?>
<span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>
<?php } ?>
index.php
<?php
require_once '../../inc/db.php';
$id=$_GET['id'];
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/example.css">
<link href="css/star-rating.css" media="all" rel="stylesheet" type="text/css"/>
<script src="js/star-rating.js" type="text/javascript"></script>
<div class="container">
<h3>Comments</h3>
<?php
$id_post = $id;
?>
<div class="cmt-container" >
<?php
session_start();
$users = session_id();
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = $id_post");
foreach ($results as $affcom) {
$comment = $affcom['comment'];
$rating = $affcom['rate'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
?>
<div class="cmt-cnt">
<div class="thecom">
<input id="input-5a" class="rating" value="<?php echo $rating; ?>" data-size="xs" data-show-clear="false" data-show-caption="false" data-readonly="true">
<span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt=$db->query($sqls);
$userT=$tt['user'];
?>
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var starrating = $('#starrating');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&rating='+starrating.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
starrating.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
</div>
You can construct a query to check whether the user has already posted a comment on that particular page or not, and display the rating and comment box accordingly. Here's the code snippet,
// your code
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = '". $id_post . "' AND user ='". $users . "'");
if($results->num_rows){
// user has already posted a comment
echo '<p>You have already posted comment on this page</p>';
}else{
// user hasn't posted any comment on this page yet
// display rating and comment box
?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
}
// your code

Form should not reload

I built a Feedback form with PHP. There is a Popup from Foundation 5 included.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style type="text/css">
.auto-style1 {
margin-left: 1px;
}
.auto-style2 {
margin-left: 0px;
}
.auto-style3 {
text-align: center;
}
.auto-style4 {
text-align: center;
font-size: x-large;
}
.auto-style5 {
color: #FF0000;
}
.auto-style6 {
color: #000000;
}
.auto-style7 {
text-align: left;
}
</style>
<title>Rating</title>
<!-- Sterne Scripts -->
<script src='jquery.js' type="text/javascript"></script>
<script src='jquery.MetaData.js' type="text/javascript" language="javascript"></script>
<script src='jquery.rating.js' type="text/javascript" language="javascript"></script>
<!-- Popup Scripts -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/foundation.css">
<!-- If you are using the gem version, you need this only -->
<link rel="stylesheet" href="css/app.css">
<script src="js/vendor/modernizr.js"></script>
<link rel="stylesheet" href="css/app.css">
<script src="js/vendor/modernizr.js"></script>
<link href='jquery.rating.css' type="text/css" rel="stylesheet"/>
</head>
<body style="background-image: url('img/body-bg.jpg')">
<?php
$send = false;
$error = $text = '';
if ($_SERVER['REQUEST_METHOD'] === "POST") {
$to = 'kontakt#schoenholz.eu';
$subject = "Feedback vom ".date("d.m.Y");
$antispam = $_POST['access'];
$name = $_POST['star1'];
$select = $_POST['Select'];
$text = $_POST['TextArea1'];
$message = "Bewertung: ".$name. "\r\n" . "Warum die Bewertung?: " .$text . "\r\n" . "Woher kennen Sie uns?: " .$select;
$success = true;
if ($antispam != 'irregeheim') {
$success = false; //Fehlerflag setzen
$error .= 'Kein Spam erwünscht!<br>'; // Fehlertext
}
if ($name == '') {
$success = false;
$error .= '"<em>Wie bewerten Sie uns</em>" wurde nicht ausgefüllt';
}
if ($select == "- Bitte auswählen -") {
$success = false; //Fehlerflag setzen
$error .= '<br>"<em>Wie haben Sie uns gefunden</em>" wurde nicht ausgefüllt</br>'; // Fehlertext
}
// ist alles ok ? dann senden
if($success === true) {
if (#mail($to,$subject,$message)) {
$send = true;
echo 'Danke für Ihr Feedback!';
} else {
$error .= 'Ihr Feedback konnte leider nicht gesendet werden. Bitte versuchen sie es später erneut';
}
}
}
if ($send === false) {
?>
Feedback<br/>
<div id="firstModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="auto-style4" style="width: 477px"><strong>Feedback </strong></p>
<p class="auto-style7" style="width: 477px">Bitte füllen Sie alle mit
<span class="auto-style6">*</span> gekennzeichneten Felder aus</p>
<label id="Label1"></label>
<fieldset style="width: 476px"><legend>Wie bewerten Sie uns?
<span class="auto-style5">*</span></legend>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Sehr schlecht") echo "checked";?> value="Sehr schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Schlecht") echo "checked";?> value="Schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Durchschnittlich") echo "checked";?> value="Durchschnittlich"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Gut") echo "checked";?> value="Gut"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Hervorragend") echo "checked";?> value="Hervorragend"/> </fieldset>
<p style="height: 36px"> Grund Ihrer Bewertung?</p>
<textarea class="auto-style1" name="TextArea1" style="width: 505px; height: 105px"><?php echo htmlspecialchars($text, ENT_QUOTES);?></textarea>
<p>Wie haben Sie uns gefunden? <span class="auto-style5">*</span></p>
<p>
<select name="Select" style="width: 151px">
<option <?php if($select== "- Bitte auswählen -") echo "selected"; ?>>- Bitte auswählen -</option>
<option <?php if($select== "Familie/Freunde") echo "selected"; ?>>Familie/Freunde</option>
<option <?php if($select== "Suchmaschinen (Google etc.)") echo "selected"; ?>>Suchmaschinen (Google etc.)</option>
<option <?php if($select== "Zeitungen") echo "selected"; ?>>Zeitungen</option>
<option <?php if($select== "Örtliche") echo "selected"; ?>>Örtliche</option>
<option <?php if($select== "Werbung") echo "selected"; ?>>Werbung</option>
<option <?php if($select== "Sonstiges") echo "selected"; ?>>Sonstiges</option>
</select>
</p>
<input type="hidden" name="access" value="irregeheim">
<p class="auto-style3" style="width: 498px">
<input class="auto-style2" name="Submit1" type="submit" value="Senden"></p>
</form>
<?php
}
if (!empty($error)) {
echo $error;
}
?>
<a class="close-reveal-modal" aria-label="Close">×</a>
</div>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
The problem is that if I push the Feedback button and miss a field, the page reloads and I have to push the Feedback Button again. I already figured out that I have to use ajax and Javascript to handle this but I dont know how I should rewrite my script so it works. Can somebody help me with that?
I use this approach:
1) Create the form on html and put an id on each input element, then I put a span or something to display error message, like this:
<input type="text" name="email" id="email">
<span id="email-message" class="hidden"></span>
2) On your php script, you need to create an array, validate each input and send json data. My array looks like this:
$data = array(
'message' => null,
'form' => array(
'has_errors' => false, // put true if there are input errors
'email' => array(
error => false,
message => null
);
);
);
header("Content-Type: application/json");
echo json_encode($data);
exit;
on this way, you add inputs to $data['form'] as you need. $data['message'] it's a general error like 'Impossible to save now. Try again'.
3) And finally, on your javascript file on success method (after json request to validate form), you check if "data.message" has a general error and if not you use a for each of the data.form to check each input and show the error message if it's necessary:
$('#my-form').on("submit", function(event){
event.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr("action"),
type: 'POST',
data: $form.serialize(),
dataType: 'json',
cache: false
}).done(function(data) {
if(data.message) {
// show general error
} else if(data.form.has_errors){//Si hay errores de formulario
//Recorremos todos los errores
$.each(data.form, function(key, value){
if(value.error) {
$('#' + key + '-msg').html(value.message).removeClass('hidden');
} else {
$('#'+key+'-msg').html('').addClass('hidden');
}
});
} else {
// no errors on form so show info message or whatever you need
}
});
});

Ajax call is inserting data on page in some other place

I am making use of ajax call to insert data in starting of my page. this is more like a wall post script. Whenever user posts something, the latest post is shown in the top of the posts page.
I am using JS, PHP and an HTML page.
here is my js code:
$(function() {
$("#tweet_submit").click(function()
{
var tweet = $("#tweet").val();
var x = $('.preview').attr('id');
if(x)
var z= x;
else
var z=0;
var dataString = 'tweet='+ tweet+ '&z=' +z;
if(tweet=='')
{
alert('Please type your tweet here');
}
else
{
alert('into post');
$.ajax({
type: "POST",
url: "WallPost/post_tweet1.php",
data: dataString,
cache: false,
success: function(html){
$("#tweet").val('');
$("#preview").hide();
$("#content").prepend(html);
}
});
}return false;
});
});
This is my PHP page:
post_tweet.php
<?php
include("includes/db.php");
include("session.php");
include_once 'includes/time_stamp.php';
//echo "request sent to post";
if($_POST)
{
$tweet=$_POST['tweet'];
$upload_id=$_POST['z'];
$time=time();
$query = "INSERT INTO tweets(tweet,time,upload_id,uid_fk) VALUES ('$tweet','$time','$upload_id','$uid')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
else
{
$msg ="<br> 1 record added";
}
echo "<br>".$msg;
$sql=mysqli_query($con,"select T.tid, T.tweet, T.time, T.upload_id, U.username, U.fullname, U.email FROM tweets T, users U WHERE T.uid_fk=U.uid and T.uid_fk='$uid' order by T.tid DESC LIMIT 1");
//$show_result=mysqli_query($sql);
while($row=mysqli_fetch_row($sql))
{
echo "data start here";
$tid= "$row[0]";
$tweet= "$row[1]";
$time = "$row[2]";
$img_id= "$row[3]";
$username="$row[4]";
$fullname = "$row[5]";
$email = "$row[6]";
$lowercase = strtolower($email);
$imagecode = md5( $lowercase );
$image_sql=mysqli_query($con,"select image_name from uploads where upload_id='$img_id'");
while($data=mysqli_fetch_row($image_sql))
{
$image_name="$data[0]";
$chars = 7;
$text = $image_name." ";
$text = substr($text,0,$chars);
$imgtext = "pic.twitter/".$text."...";
}
//echo "<div class='center'>";
echo "<div class='tweet_box' id='$tid'>";
echo "<div class='tweet_user'><img class='user_img' src='http://www.gravatar.com/avatar/$imagecode?s=50'></div>";
echo "<div class='tweet_body'>";
?>
<div class='tweet_time'><?php time_stamp($time);?></div>
<?php
echo "<div><b><a href='http://twitter.com/$username'>$fullname</a></b> <span class='uname'>#$username</span></div>";
echo "<div class='tweet_text'>$tweet ";
if($img_id!=0)
{
echo "<a href=''/>$imgtext</a></div>";
}
else
{
echo "</div>";
}
echo "<div class='tweet_options'><div class='first_option'><a href='#'>Expand</a> </div><div class='sub_options'> <a href='#'>Reply</a> <a href='#'>Retweet</a> <a href='#'>Favourite</a></div></div>";
if($img_id!=0)
{
?>
<div class="tweet_image" id="tweetimage<?php echo $tid; ?>">
<center><img src="uploads/<?php echo $image_name; ?>" class="image_show"/></center></div>
<?php
}
echo "</div></div>";
?>
<div class="tweet_reply_box" id="replybox<?php echo $tid;?>">
<div><textarea rel="<?php echo $tid;?>" id="replytext<?php echo $tid;?>" class="reply" name="reply"
maxlength="140">#<?php echo $username;?> </textarea></div>
<div class="reply_button_bar" id="replybutton<?php echo $tid;?>">
<div><input type="submit" value=" Reply " class="reply_btn" id="<?php echo $tid;?>"/></div>
</div>
</div>
<div id="reply_load<?php echo $tid;?>" class="reply_load">
</div>
<?php
}
}
else { }
?>
And this is my HTML page:
Wallpost.php
<!doctype html>
<html>
<head>
<title>Design Modo - Code-pal | eCommerce Website Template - Dead Stocker</title>
<link rel="shortcut icon" href="http://www.code-pal.com/wp-content/themes/codpeal-new/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/check_style.css" />
<link rel="stylesheet" href="css/wallpost/wtfdiary.css">
<link rel="stylesheet" href="css/wallpost/tipsy_title.css">
<script type="text/javascript" src="WallPost/js/jquery.min.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.tipsy.js"></script>
<script src="WallPost/js/twitter.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.form.js"></script>
</head>
<body>
<div class="page-wrap">
<div class="clear"></div>
<?php include("header.php"); ?>
<div class="clear"></div>
<div class="body-contents">
<?php include("left-body1.php"); ?>
<div class="center">
<br>
<div class="txthead"><strong>Share thoughts here</strong></div>
<?php
include("WallPost/index.php");
?>
</div>
</div>
<?php include("right-body.php"); ?>
<div class="clear"></div>
</div>
<!-- eo .body-content -->
<?php include("footer.php"); ?>
</div><!-- eo .page-wrap-->
Here is the code where i post tweet:
index.php under WallPost folder:
<?php
include("includes/db.php");
include("session.php");
include("includes/time_stamp.php");
?>
<html>
<head>
<link rel="stylesheet" href="css/wtfdiary.css">
<link rel="stylesheet" href="css/tipsy_title.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.tipsy.js"></script>
<script type="text/javascript" src="js/twitter.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
<div id="container">
<div id="sidebar_container">
<div id="sidebar">
<div id='logo'><img src='images/1.png'></div>
<div id="box">
<div><textarea id="tweet" name="tweet" placeholder="Compose new Tweet..."></textarea></div>
<div id='preview'></div>
<div id="button_bar">
<div id="icons">
<div class="filebutton" title="Image Upload">
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<span><input type="file" name="photoimg" id="photoimg"/></span>
</form>
</div>
</div>
<div><input type="submit" value=" Tweet " class="btn" id="tweet_submit"/></div>
</div>
</div>
</div>
</div>
<!-- <div id="main"> -->
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id='heading'>Tweets</div>
<div id='content'>
<?php include("loads_tweets1.php");?>
<!-- </div> -->
</div>
</div>
</body>
</html>
So after i make use of all these code, Post is shown in my page, but the way it is shown is not correct.
The post is inserted at some random place. (I couldn't attach image due to less reputation)
Can someone please tell what is going wrong, and i am not able to get this data in correct place where my other posts are listed.
Thanks in advance!!!
Your input helped me and i was able to solve it. Content was being called at two places, and ajax inserted the data on first location and i was not getting it placed where i needed it.
Thanks.

Why the AJAX don't work here?

i'm trying to learn to use AJAX, so i search a tut about make a crappy login system with ajax and start to learn, the thing is i do some little modifications to it, (PDO instead my_sql for example) and is not working, seeing that tut over and over again doesn't seems to show why there is not working.
What happend than doesn't work?
Well, it moves me from the index.php page to the admin.php page instantly, it musn't be that way, if i'm correct, it must bring the data back to the index.php right?
it works if the AJAX doesn't exist, instead of bring the data from admin.php, it makes me move to that page, like if it was pure PHP and none AJAX involved in the script.
The PHP is not calling the AJAX, it just use header(location
Thats the problem.
Here is the code of all files:
index.php
<?php
session_start();
if($_POST){
include("3325d7a55a4550ee85156f5f9a6762bede9d3021.php");
$nombre = $_POST['login'];
$pw = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tuser WHERE USER = :USER");
$rslt = $stmt->execute(array(':USER' => $nombre));
$stmt->bindParam(':USER', $nombre, PDO::PARAM_STR);
$usuario = $stmt->fetch();
if ($usuario) {
$_SESSION['usuario_logeado'] = $usuario;
header('Location: admin.php');
} else {
$error = 'Usuario y/o password incorrecto.';
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Temporis</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$('#login-form').submit(function(e) {
e.preventDefault();
$.post('ajax.php', $(this).serialize(), function(resp) {
if(!resp.error) {
var html= '<h3>Hola, ' + resp.['NOMBR1'] + ' ' + resp.['NOMBR3'] + '!</h3>' + '<p>' +
'Logout' +
'</p>';
$('.sidebar').html(html);
} else {
var error = '<p class="error">' + 'Usuario y/o password incorrecto.' + '</p>';
$('#login-form .error').remove();
$('.actions').before(error);
};
}, 'json');
});
});
</script>
</head>
<body>
<h5>INDEX!!!</h5>
<center>
<?php if(!isset($_SESSION['usuario_logeado'])): ?>
<form id="login-form" action="" method="post" class="form-stacked">
<input type="text" name="login" id="login">
<input type="password" name="pwd" id="pwd">
<?php if(isset($error)): ?>
<p>
<?php echo $error ?>
</p>
<?php endif;?>
<input type="submit" value="Login" id="btn">
</form>
<?php else :?>
<h3>Hola, <?php echo $_SESSION['usuario_logeado']['NOMBR1'] .' '. $_SESSION['usuario_logeado']['NOMBR3'] ?></h3>
Logout
<?php endif;?>
<br />
<br />
<div class="sidebar"></div>
<br />
<br />
<div class="actions"></div>
<br />
<br />
Admin
<br />
<br />
<div id="RBUG"> Si tienes cualquier duda, problema tecnico o quieres dar una sugerencia usa el
<a href=RBuGFm.php>Reporte de Bugs</a> </div>
</center>
</body>
</html>
admin.php
<?php
session_start();
if(!$_SESSION['usuario_logeado']){
header('Location: index.php');
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Temporis</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/menu.js"></script>
</head>
<body>
<center>
<h4>TROLOLOLOLO!</h4>
<h3>Hola, <?php echo $_SESSION['usuario_logeado']['NOMBR1'] .' '. $_SESSION['usuario_logeado']['NOMBR3'] ?></h3>
Logout
<div id="RBUG"> Si tienes cualquier duda, problema tecnico o quieres dar una sugerencia usa el
<a href=RBuGFm.php>Reporte de Bugs</a> </div>
</center>
</body>
</html>
ajax.php
<?php
session_start();
include("3325d7a55a4550ee85156f5f9a6762bede9d3021.php");
$nombre = $_POST['login'];
$pw = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tuser WHERE USER = :USER");
$rslt = $stmt->execute(array(':USER' => $nombre));
$stmt->bindParam(':USER', $nombre, PDO::PARAM_STR);
$usuario = $stmt->fetch();
if ($usuario) {
$_SESSION['usuario_logeado'] = $usuario;
echo json_encode($usuario);
} else {
echo json_encode(array('error' => true));
}
?>
3325d7a55a4550ee85156f5f9a6762bede9d3021.php (conection.php)
<?php
$host = "localhost";
$user = "root";
$pss = "password";
$db = "somedb_name";
$authz = "authc";
// Los comandos auxiliares estan comentados para que no funcionen a menos que sean necesarios
// var_dump($_POST);
try{
$con = new PDO('mysql:host='.$host.';dbname='.$db,$user,$pss);
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
// $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Success ";
}catch(PDOException $e){
echo $e->getMessage;
}
?>
logout.php
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
I don't know what can be the problem and i'm running out of ideas, so i'm trusting in your eyes and experience to solve my problem and learn how to do this stuff correctly..
Any comment, suggestion, question improvement or question about it for clarification, please feel free to say it, and i try to edit the post with the answer as soon as i can.
Thanks in advance

PHP messages aren't being written to the log file - tutsplus.com tutorial

tutsplus, there you will find a tutorial which guides you through the steps on how to create a simple web chat. I tried to follow all that was said, yet I noticed a problem when testing. It seems that the usermsg is not being posted to the log.html file.
here is the index.php, which in this case is named chat.php:
<?php
function loginForm() {
echo '
<div id="loginform">
<form action="chat.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="enter" id="enter" value="enter">
</form>
</div>
';
}
if(isset($_POST['enter'])) {
if($_POST['name'] != "") {
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}else {
echo '<span class="error">Please type in a name</span>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Chat Service</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" title="style" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<?php
if(!isset($_SESSION['name'])) {
loginForm();
}else{
?>
<div id="wrapper">
<div id="menu">
<div class="welcome">Welcome, <?php echo $_SESSION["name"]; ?></div>
<div class="logout">Exit Chat</div>
<div style="clear:both;"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0) {
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input type="text" name="usermsg" id="usermsg" size="63">
<input type="submit" name="submitmsg" id="submitmsg" value="Send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
//jQuery Document
$(document).ready(function() {
$("#exit").click(function() {
var exit = confirm("Are you sure you want to logout?");
if(exit == true) {
window.location = 'chat.php?logout=true';
}
});
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
console.log(clientmsg);
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url:"log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chatbox").animate({scrollTop: newscrollHeight}, 'normal');
}
}
});
}
setInterval(loadLog, 2500);
});
</script>
<?php
}
if(isset($_GET['logout'])) {
$fp = fopen("log.html", 'a');
fwrite($fp, '<div class="msgln"><i>User '.$_SESSION['name'].' has left the chat session.</i><br></div>');
fclose($fp);
session_destroy();
header("Location: chat.php");
}
?>
</body>
</html>
Here is the post.php:
<?php
session_start();
if(isset($_SESSION['name'])) {
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").")<b>".$_SESSION['name']."</b>:".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
I am using MAMP, and the files are located in the htdocs folder, so that's not the problem.
Thanks in advance for any help you can give me, and let me know if you need more info.
You should call session_start() in index.php.
(from Marc B in the comments)

Categories