I made a PHP page that looks up Constant Contact e-mail addresses in a database and returns a table listing their name, e-mail address, and mailing list they are in. You enter the addresses here: Contact Lookup Tool along with your Constant Contact user name and password.
For some reason, only the last row of the results page has a list of mailing lists. The other ones have the word "Array," which I stripped out, so now those rows are blank. Here is a screen shot of what I mean:
http://www.advantage-computer.com/images/ScreenCap.png
They're all in a list, though. Here's the code for search.php. The form submits to that file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>List of Contacts</title>
<style type="text/css">
.hdr
{
margin-bottom: 0px;
padding-bottom: 0px;
}
</style>
</head>
<body>
<table width="75%">
<tr>
<td class="hdr">Name</td>
<td class="hdr">E-mail address</td>
<td class="hdr">List(s)</td>
</tr>
<tr>
<td colspan="3">
<hr style="padding:0; margin:0">
</td>
</tr>
<?PHP
require_once('./class.cc.php');
/*VARIABLES*/
$cc = new cc($_POST['userName'], $_POST['password']);
if($cc)
{
$strEmails = $_REQUEST['emails'];
$aryEmails = explode("\n", $strEmails);
$page = (isset($_GET['page'])) ? $_GET['page'] : 'lists';
$lists = $cc->get_lists($page);
/*METHODS*/
foreach ($aryEmails as $email)
{
if($lists)
{
foreach($lists as $k => $v)
{
$list = $v['Name'];
$page = (isset($_GET['page'])) ? $_GET['page'] : 'members';
$members = $cc->get_list_members($v['id'], $page);
if($members)
{
foreach($members as $k => $v)
{
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
}
}
}
}
}
$strLists = str_replace("Array", "", $strLists);
$strLists = substr($strLists, 0, -2);
$contact = $cc->query_contacts(trim($email));
if($contact)
{
$strName = $contact['Name'];
if(is_array($strName))
{
$strName = "";
}
echo
(
"<tr><td>".$strName."</td>".
"<td>".$contact['EmailAddress']."</td>".
"<td>".$strLists."</td></tr>"
);
}
else
{
echo("<tr><td colspan='3'>Could not find {$email}.</td></tr>");
}
}
}
else
{
echo "Invalid user name or password";
}
?>
</table>
</body>
</html>
Here is the class.cc file: http://advantage-computer.com/tools/class.cc.txt
Firstly, you should break out of that loop once you have matched a record, and you are not using $k so we can remove that from the loop too, eg:
if($members)
foreach($members as $v)
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
break;
}
I would also add a line in there to debug whats in the $list variable when it is an array:
if (is_array($list))
var_dump($list);
I would say that whatever is setting "$_list['content']['ContactList']['Name']" in your class is not doing it correctly.
Thanks everyone for the replies. My brother found the problem. He changed
foreach ($aryEmails as $email){
...
}
to
foreach ($aryEmails as $tmpEmail){
$email = rtrim($tmpEmail);
...
}
It appears that it only matched the last line in the text area because there were still carriage returns in the e-mail array left over from the text area. He added rtrim to remove them.
Related
I created an HTML application form for my employer so that applicant's can apply online. However, I'm running into some issues with the PHP bit. I'd like for it to send me an email containing ALL of the forms field names along with their values (even if the value is left blank). It needs to be in this specific format so that I can quickly 'convert' that data programmatically from the email into an HCL Notes form.
However, when a checkbox on my HTML form is left unchecked, it is not sent to the $_POST array at all, which then obviously ends up breaking the bit that converts it as it can't find the correct field names.
I know this is a strange and very specific issue, but does anyone have any ideas as to how I can go about this successfully?
My PHP code currently (removed the parameters at the top for privacy):
<?php session_start();
?>
<!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>Results</title>
</head>
<body>
<?php
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = '';
// Your email address. This is where the form information will be sent.
$emailadd = '';
// Where to redirect after form is processed.
$url = '';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
$time = time();
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// handle the error accordingly with your other error checking
// or you can do something really basic like this
die('The code you entered was incorrect. Go back and try again.');
}
foreach ($_POST as $key => $value)
{
if ($key != "captcha_code"){
$j = strlen($key);
if ($j >= 40){echo "Name of form element $key cannot be longer than 39 characters";die;}
$j = 40 - $j;
for ($i = 1; $i <= $j; $i++)
{$space .= ' ';}
$value = str_replace('\n', "$line", $value);
$conc = "{$key}:$space{$value}$line";
$text .= $conc;
$space = ' ';
}
}
$text .= 'END OF APPLICATION';
mail($emailadd, $subject, $text, 'From: ');
echo '<script>alert("Application successfully submitted.");</script>';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
?>
</body>
</html>
Here's how the emails look, I need it to be just like this but with ALL fields regardless of if they have values or not:
Create an array that lists all the fields that should be in the email. Then instead of looping through $_POST, loop through that array. Display the corresponding $_POST field if it's filled in, otherwise show a blank value.
$fields = ['ReasonForReferral', 'FirstName', 'MiddleName', ...];
foreach ($fields as $field) {
$conc .= "$field: " . (isset($_POST[$field]) ? str_replace($_POST[$field], "\n", $line) : '') . $line;
}
Here i want to do read the xl file in php,here i displayed all datas that means in xl file i have four columns called Title,Url,Visitors,Accesses.but for me don't want like this , i want only title name how can do this ? View my answer
<?php
include 'excel_reader.php'; // include the class
// creates an object instance of the class, and read the excel file data
$excel = new PhpExcelReader;
$excel->read('test.xls');
function sheetData($sheet) {
$re = '<table>'; // starts html table
$row = 1;
while($row <= $sheet['numRows']) {
$re .= "<tr>\n";
$column = 1;
$cell = isset($sheet['cells'][$row][1]) ? $sheet['cells'][$row][1] : '';
$re .= " <td>$cell</td>\n";
$re .= "</tr>\n";
$row++;
}
return $re .'</table>';// ends and returns the html table
}
$nr_sheets = count($excel->sheets);// gets the number of sheets
$excel_data = ''; // to store the the html tables with data of each sheet
// traverses the number of sheets and sets html table with each sheet data in $excel_data
for($i=0; $i<$nr_sheets; $i++) {
//$excel_data .= '<h4>Sheet '. ($i + 1) .' (<em>'. $excel->boundsheets[$i]['name'] .'</em>)</h4>'. sheetData($excel->sheets[$i]) .'<br/>';
$excel_data .= sheetData($excel->sheets[$i]) .'<br/>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example PHP Excel Reader</title>
<style type="text/css">
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<?php
// displays tables with excel file data
echo $excel_data;
?>
</body>
</html>
By observing the $sheet array you will get Title at the position of 4,1 as follows.
By changing this line as shown
$cell = isset($sheet['cells'][4][1]) ? $sheet['cells'][4][1] : '';
But it looks like you have copied this code from somewhere. It is hard to identify your need and modify it. Change the code as per your requirement and if any error occurs then post your question on SO
as per your requirement your sheetData function should be like this
function sheetData($sheet) {
$re = '<table>'; // starts html table
$x = 1;
while($x <= $sheet['numRows']) {
$re .= "<tr>\n";
$cell = isset($sheet['cells'][$x][1]) ? $sheet['cells'][$x][1] : '';
if($cell != 'Title'){ // check for title here
$re .= " <td>$cell</td>\n";
$re .= "</tr>\n";
}
$x++;
}
return $re .'</table>'; // ends and returns the html table
}
I am trying to create a PHP file each time a user registers my website. I use the following code to create the file in my register.php :
The thing is, my create file function works but the variable $data doesn't give any result. When I run that $data as a single variable in a different PHP file it still doesn't work.
What did I do wrong about setting the variable.
// STARTING to create a file
$my_file = "$username.php";
$handle = fopen("give/$my_file", 'w') or die('Cannot open file: '.$my_file);
//----------- BEGINNING OF THE PHP DATA TO WRITE TO NEW FILE ----------
$data = "<?
require('../config.inc.php');
$damned_user = $username;
if ( $_COOKIE['damn_given'] != TRUE ) {
$sql = mysql_query(\"SELECT * FROM users WHERE username='$damned_user' LIMIT 1\");
if(mysql_num_rows($sql) == 1){
$row = mysql_fetch_array($sql);
// $row['field'];
$damned_user_id = $row['id'];
if($_SESSION['id'] == $damned_user_id) {
} else {
$taken = $row['taken_damns'];
$taken_damns = $taken + 1;
$taking_sql = \"UPDATE users SET taken_damns='$taken_damns' WHERE username='$damned_user' \";
if (mysql_query($taking_sql)) {
setcookie(\"damn_given\", TRUE, time()+3600*24);
$date = date(\"Y-m-d H:i:s\");
$ip = $_SERVER['REMOTE_ADDR'];
$damns_table = \"INSERT INTO damns (id, from_ip, user_damned, when_damned) VALUES ('','$ip','$damned_user','$date') \";
if ( mysql_query($damns_table)) {
} else {
echo \"Couldn't save damn to damns table in database!\";
}
if ( $_SESSION['logged'] == TRUE ) {
$session_id = $_SESSION['id'];
$giving_sql = \"UPDATE users SET given_damns='$taken_damns' WHERE id='$session_id'\";
if ( mysql_query($giving_sql ) ) {
} else {
echo ('Error giving damn!');
}
}
}
else
{
die (\"Error taking damn!\");
}
}
} else {
die(\"Error first sql!\");
}
}
?>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<link rel=\"stylesheet\" href=\"/_common.css\" />
<link rel=\"stylesheet\" href=\"/_col_white.css\" />
<link rel=\"shortcut icon\" href=\"/favicon.ico\" /> <title>DamnIt.tk - Damned!</title>
</head>
<body>
<div id=\"main\">
<div class=\"center\"><img src=\"/_bnr_white.png\" style=\"width: 500px; height: 100px;\" alt=\"DamnIt Banner\" /></div>
<table class=\"tmid\" style=\"width: 100%;\"><tr>
<td class=\"center\" style=\"width: 25%;\">Profile</td>
<td class=\"center\" style=\"width: 25%;\">Options</td>
<td class=\"center\" style=\"width: 25%;\">Stats</td>
<td class=\"center\" style=\"width: 25%;\">Log out</td>
</tr></table> <h1>Give a Damn</h1>
<?
if ( isset($_COOKIE['damn_given'])) {
?>
<h2>You have already given a Damn to <? echo $damned_user ?> today!</h2><h3>Couldn't damn - try again tomorrow.</h3>
<?
}
elseif ( $_SESSION['id'] == $damned_user_id ) {
?>
<h2>You cannot damn yourself!</h2>
<?
} else{ ?> <h2>Damn given!</h2><h3>You have given a Damn to <? echo $damned_user ?>.</h3> <? } ?>
</div></body>
</html>";
//------- END OF PHP WHICH MUST BE WRITTEN TO NEW FILE ---------
fwrite($handle, $data);
fclose($handle);
// finished with the file
Try NOWDOC:
$data = <<<'END'
Your PHP code here
END;
This will allow for any string, without need for escaping.
However, please consider what you're doing very carefully!
Also... you wouldn't happen to be trying to rip off this site of mine, would you? http://giveadamn.co.uk/
(source: giveadamn.co.uk)
Because if so, you're doing it wrong. .htaccess, mate ;)
RewriteEngine on
RewriteRule give/(.*) give.php?user=$1 [L]
I have a chart and a text file that is taking in some data. I would like to organize the data I have by putting the user with the highest score on the top of the table and coloring everything in their row blue. Any idea how I could do this?
file one:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>High Score</title>
</head>
<body>
form action="data.php" method="POST">
<table border="1">
<tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
<tr><td>Score</td><td><input type="text" name="score"</td></tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
Data.php:
<?php
$name = $_POST['name'];
$score = $_POST['score'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../phpdata/highscore.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
fwrite($fp, $name."|".$score."\n");
?>
<?php
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$players = file("$DOC_ROOT/../phpdata/highscore.txt");
echo "<table border='2'>";
echo "<tr> <td>Name</td> <td>Score</td> </tr>";
for($i = 0; $i < sizeof($players); $i++) {
list($name,$score) = explode('|', $players[$i]);
echo '<tr><td>'.$name.'</td><td>'.$score.'</td></tr>';
}
echo '</table>';
?>
Format all players/scores into arrays like array('name' => 'Bob', 'score' => 42):
foreach ($players as &$player) {
list($name, $score) = explode('|', $player);
$player = compact('name', 'score');
}
unset($player);
Sort the array by score (PHP 5.3 syntax):
usort($players, function ($a, $b) { return $b['score'] - $a['score']; });
Output the results, setting a class on the first row:
$first = true;
foreach ($players as $player) {
$class = $first ? ' class="highlight"' : null;
$first = false;
printf('<tr%s><td>%s</td><td>%s</td></tr>', $class, htmlspecialchars($player['name']), htmlspecialchars($player['score']));
}
Now highlight that class using CSS (or do it directly in the HTML, or whatever else you want to do).
I am new to OAuth, and want to create a page that gets the user's contact list from Google using the OAuth system so they don't have to login.
How do I do this? I am using php, so I would really appreciate if there is example code that does this. I can't seem to find it on Google.
Please help!
Thanks
For general OAuth principles to access Google, you might find Google's OAuth playground very useful (contacts are included there).
This is a very basic example (using the php oauth pecl extension and simplexml, it just prints out the names of the 25 first contacts):
<?php
$cons_key="your consumer key";
$cons_sec="your consumer secret";
$callback="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$req_token_url="https://www.google.com/accounts/OAuthGetRequestToken";
$auth_token_url="https://www.google.com/accounts/OAuthAuthorizeToken";
$acc_token_url="https://www.google.com/accounts/OAuthGetAccessToken";
$scope="https://www.google.com/m8/feeds/";
$scopes=urlencode($scope);
$req_scope_token_url=$req_token_url."?scope=".$scopes;
$endpoint="https://www.google.com/m8/feeds/contacts/default/full/";
session_start();
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
$oauth = new OAuth($cons_key,$cons_sec);
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$oauth = new OAuth($cons_key,$cons_sec);
$oauth->setRequestEngine(OAUTH_REQENGINE_CURL);
$request_token_info = $oauth->getRequestToken($req_scope_token_url,$callback);
if(!empty($request_token_info)) {
$_SESSION['token']=$request_token_info['oauth_token'];
$_SESSION['secret']=$request_token_info['oauth_token_secret'];
$_SESSION['state']=1;
header('Location: '.$auth_token_url.'?oauth_token='.$_SESSION['token']);
exit;
}
} else if($_SESSION['state']==1) {
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
$access_token_info = $oauth->getAccessToken($acc_token_url);
$_SESSION['state'] = 2;
$_SESSION['token'] = $access_token_info['oauth_token'];
$_SESSION['secret'] = $access_token_info['oauth_token_secret'];
}
$oauth->fetch($endpoint);
parseAtom($oauth->getLastResponse());
} catch(OAuthException $E) {
print_r($E);
}
function parseAtom($atomstring) {
global $oauth;
$atom=simplexml_load_string($atomstring);
foreach ($atom->entry as $entry) {
print $entry->title.", ";
}
}
?>
You can see the above code in action here.
Installing (configuring) the oauth pecl extension can be tricky, you may have to check your php.ini and/or specify a requestengine.
Hope my post helpful to all (Google contact list reader in PHP(Google OAuth))
http://anandafit.info/2011/03/08/google-contact-list-reader-in-php-google-oauth/
You need to start with Google Contacts Data API and OAuth, when you're done, this should be enough for a reference.
OK. first of all futtta i had some problems with pecl and pear stuff. so i decided to stick with ZEND. I do appreciate you posting though, your code still helped me :-)....
here is what i've got so far, taking some of the code from the ibm page posted above, but altering it to use oauth to get in.
<?php
session_start();
require_once 'common.php';
require_once 'Zend/Oauth/Consumer.php';
require_once 'Zend/Crypt/Rsa/Key/Private.php';
require_once 'Zend/Gdata.php';
require_once 'Zend/Gdata/Query.php';
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'consumerKey' => 'PUT KEY HERE',
'consumerSecret' => 'PUT KEY HERE',
'signatureMethod' => 'HMAC-SHA1',
'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
);
?>
<!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" xml:lang="en" lang="en">
<head>
<title>Listing contacts</title>
<style>
body {
font-family: Verdana;
}
div.name {
color: red;
text-decoration: none;
font-weight: bolder;
}
div.entry {
display: inline;
float: left;
width: 400px;
height: 150px;
border: 2px solid;
margin: 10px;
padding: 5px;
}
td {
vertical-align: top;
}
</style>
</head>
<body>
<?
$consumer = new Zend_Oauth_Consumer($oauthOptions);
if (!isset($_SESSION['ACCESS_TOKEN_GOOGLE'])) {
if (!empty($_GET)) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN_GOOGLE']));
$_SESSION['ACCESS_TOKEN_GOOGLE'] = serialize($token);
} else {
$token = $consumer->getRequestToken(array('scope'=>'http://www.google.com/m8/feeds'));
$_SESSION['REQUEST_TOKEN_GOOGLE'] = serialize($token);
$consumer->redirect();
exit;
}
} else {
$token = unserialize($_SESSION['ACCESS_TOKEN_GOOGLE']);
//$_SESSION['ACCESS_TOKEN_GOOGLE'] = null;
}
$http = $token->getHttpClient($oauthOptions);
$gdata = new Zend_Gdata($http);
$gdata->setMajorProtocolVersion(3);
$gdata->getHttpClient()->setRequestScheme(Zend_Oauth::REQUEST_SCHEME_QUERYSTRING);
$query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full?);
//$query->setMaxResults(10);
$feed = $gdata->getFeed($query);
?>
<h2><?php echo $feed->title; ?></h2>
<div>
<?php echo $feed->totalResults; ?> contact(s) found.
</div>
<?php
// parse feed and extract contact information
// into simpler objects
$results = array();
foreach($feed as $entry){
$xml = simplexml_load_string($entry->getXML());
$obj = new stdClass;
$obj->name = (string) $entry->title;
$obj->orgName = (string) $xml->organization->orgName;
$obj->orgTitle = (string) $xml->organization->orgTitle;
foreach ($xml->email as $e) {
$obj->emailAddress[] = (string) $e['address'];
}
foreach ($xml->phoneNumber as $p) {
$obj->phoneNumber[] = (string) $p;
}
foreach ($xml->website as $w) {
$obj->website[] = (string) $w['href'];
}
$results[] = $obj;
}
?>
<?php
// display results
foreach ($results as $r) {
?>
<div class="entry">
<div class="name"><?php echo (!empty($r->name)) ?
$r->name : 'Name not available'; ?></div>
<div class="data">
<table>
<tr>
<td>Organization</td>
<td><?php echo $r->orgName; ?></td>
</tr>
<tr>
<td>Email</td>
<td><?php echo #join(', ', $r->emailAddress); ?></td>
</tr>
<tr>
<td>Phone</td>
<td><?php echo #join(', ', $r->phoneNumber); ?></td>
</tr>
<tr>
<td>Web</td>
<td><?php echo #join(', ', $r->website); ?></td>
</tr>
</table>
</div>
</div>
<?php
}
?>
</body>
</html>
There are still some problems, for me it only posts 25 results and i cannot seem to get setmaxresults to work... there seems to be problems with ZEND for that... if someone knows a work around, please post.
b
Comment out the setRequestScheme method call and use max-results and you should be able to get more than 25 entries.
//$gdata->getHttpClient()->setRequestScheme(Zend_Oauth::REQUEST_SCHEME_QUERYSTRING);
$query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full/?max-results=999999');