Printing only once IF statement - php

Below is a php file used within my e-commerce website (prototype) to write the item(s) selected by a customer and storing their choices in a flat file database. The logic works fine although the echo "Order Submitted!; is printed for every item selected e.g. if 4 items are selected this line is printed 4 times, I only require it to be printed once. Any idea how this could be accomplished?
<body>
<table>
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
} else {
echo "<h1>Transaction Completed!</h1>";
}
date_default_timezone_set('Europe/London');
$now = date(' d/m/y H:i:s ');
$visitor = $_POST['visitor'];
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
exit;
} else {
echo "<p>Order Submitted!</p>";
fclose($fh);
}
}
}
}
?>
</table>
<input type="button" onClick="parent.location='home.php'" value="Return Home">
<input type="button" onClick="parent.location='items.php'" value="New Purchase">
If 2 items are selected the output is:
Transaction Completed
Order Submitted!
Order Submitted!

Keep track of if there's an error and move the else outside the loop.
$error=false;
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
$error=true;
exit;
}
}
}
}
if(!$error) {
echo "<p>Order Submitted!</p>";
fclose($fh);
}
Although, the way you have it written, you don't even need a conditional surrounding "Order submitted" because it will never execute if there's an error. (Due to the exit.)
Also you can move $myfile out of the loop if it doesn't change.
Second version:
$myFile = "purchases.txt";
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
exit;
}
}
}
}
echo "<p>Order Submitted!</p>";
fclose($fh);

before foreach loop:
$printed=false;
then instead of
else {
echo "<p>Order Submitted!</p>";
fclose($fh);
}
use
else {
if(!$printed)
{
echo "<p>Order Submitted!</p>";
$printed=true;
}
fclose($fh);
}

You should remove the echo from the else branch and put it right after the first foreach closing bracket

You can use a counter and see if more the one was submitted
like:
$count=0;
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
exit;
} else {
$count++;
fclose($fh);
}
}
}
}
if ($count>0)
echo "<p>Order Submitted! $count Times</p>";

Related

How to echo a position of a .txt?

I'm doing a code based on two .txt, one with names and the other with birthdays. I'm reading them and when the day date coincides with the date.txt, the name in the coincident line of the names.txt will be shown, but when I do the comparison, only the last line of the names.txt appears.
That's the code:
<?php
$nome = fopen("nome.txt", "r");
while(!feof($nome)){
$pessoa = fgets($nome);
} fclose($nome);
$current = date("d-m");
$content = fopen("data.txt", "r");
while (!feof($content)){
$linha = fgets($content);
if (strtotime($linha) == strtotime($current)) {
echo $pessoa;
echo '<br>';
}
} fclose($content);
?>
Content of the .txt:
nome.txt:
teste
teste1
teste2
teste3
data.txt:
12-12
18-12
12-12
12-12
You can process line by line from both files at the same time
<?php
$nome = fopen("nome.txt", "r");
$content = fopen("data.txt", "r");
$current = date("d-m");
while(!feof($nome) && !feof($content)){
$pessoa = fgets($nome);
$linha = fgets($content);
if (trim($current) == trim($linha)) {
echo $pessoa;
echo '<br>';
}
}
fclose($content);
fclose($nome);
?>
Or you can read entire file into an array using file function but this may be slower
<?php
$nome = file("nome.txt");
$content = file("data.txt");
$current = date("d-m");
foreach($content as $key => $linha)
if (trim($current) == trim($linha)) {
echo $nome[$key];
echo '<br>';
}
?>
You can open the files and load them in to arrays and use foreach with $key to output them in sync.
$names = explode(PHP_EOL,file_get_contents("none.txt"));
$dates = explode(PHP_EOL,file_get_contents("data.txt"));
Foreach($names as $key => $name){
Echo $name . " " . $dates[$key] . "\n";
}
https://3v4l.org/59ao6
Another way is to combine the two arrays in to one.
This however has a flaw, you can not have two people with the same name.
$days = array_combine($names, $dates);
// Days is now an associate array with name as key and date as birthday.
Foreach($days as $name => $date){
Echo $name . " " . $date . "\n";
}

PHP variable as hyperlink

I'm trying to set the php variables linked to one of my page in the folder, index.html. However, I am getting an error of Name&lang=en"> Any help?
if (isset($result_array)) {
foreach ($result_array as $result) {
$name = preg_replace("/" . $search . "/i", "<b class='high'>" . $search . "</b>", $result['Name']);
$url = '<a href="index.html">' . urlencode($result['Name']) . '&lang=en';
$out = str_replace('nameS', $name, $html);
$out = str_replace('urlS', $url, $out);
$_SESSION[$search] = $result['Name'];
echo($out);
}
}

How to bring array values out of foreach loop?

I have a foreach loop like this.
if ( is_object($res_two)) {
if($res_two->num_rows() == 0) {
echo "No Records Found";}
else if( $res_two->num_rows() > 0) {
foreach ($res_two->result() as $row ) {
echo $row->js_id."\t". $row->designation."\t".$row->full_name."\t".$row->location."\t".$row->graduated_in."\t";
$mail2 = $row->email;
echo $mail2 ;
?> Download Resume <br/><br/> <?php
}
}
}
?>
Now I want to extract $mail2 details. However echoing $mail2 out of the code giving only one value instead of an array(if foreach loop iterates, it should have multiple values?).
How to get the multiple values of $mail2 outside the code?
<?php
if (is_object($res_two)) {
if ($res_two->num_rows() == 0) {
echo "No Records Found";
} else if ($res_two->num_rows() > 0) {
foreach ($res_two->result() as $row) {
echo $row->js_id . "\t" . $row->designation . "\t" . $row->full_name . "\t" . $row->location . "\t" . $row->graduated_in . "\t";
$mail2[] = $row->email;
?> Download Resume <br/><br/> <?php
}
}
}
print_r($mail2);
?>

foreach loop does not work with include

Would someone of you know why I'm not able to use a (long)piece of code within a foreach loop?
The code in the foreach loop is only executed once.
This code at topictweets.php works fine on its own but I want to repeat it for each forum.
The foreach loop works fine without the include. I also tried to have the code from topic tweets.php plainly in the foreach loop, this didn't work either of course.
The code it includes is used to get topics of a forum from the database and find related tweets, and save those in the database.
Is there some other way to do this?
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
include 'topictweets.php';
/////////
////////
}
online version: http://oudhollandsedrop.nl/webendata/FeedForum/fetchtweets.php
bunch of code in topic tweets.php
<?php
//?/ VVVV ---- SELECT TOPICS FOR CURRENT FORUM ----- VVVV ////
echo $fID;
$sql = "SELECT Topics_TopicID
FROM Topics_crosstable
WHERE Forums_ForumID = '$fID'";
$result = mysql_query($sql);
if (!$result) {
//echo 'The topiclist could not be displayed, please try again later.';
} else {
if (mysql_num_rows($result) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($result)) {
//display post data
// echo $row['Topics_TopicID'];
// echo': ';
$topic = "SELECT Name
FROM Topics
WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID']);
$topicname = mysql_query($topic);
if (!$topicname) {
// echo 'The topic could not be displayed, please try again later.';
} else {
if (mysql_num_rows($topicname) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($topicname)) {
//display post data
// echo $row['Name'];
// echo'<br>';
$topiclist[] = $row['Name'];
}
}
}
}
}
}
foreach ($topiclist as $key => $value) {
$terms .= "" . $value . ",";
}
//echo'<p>';
//echo rtrim($terms, ",");
//echo'<p>';
//echo'<p>';
//echo $terms;
//$terms="vintage";
//Twitter account information
$username = "Username";
$password = "Password";
while (true) {
//$terms="vintage";
//echo "search terms: " . substr_replace($terms, "", -1) . "\n";
$url = "https://stream.twitter.com/1/statuses/filter.json";
$cred = sprintf('Authorization: Basic %s', base64_encode("$username:$password"));
$param = "track=" . urlencode(substr_replace($terms, "", -1));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => $cred,
'content' => $param,
'Content-type' => 'application/x-www-form-urlencoded'),
'ssl' => array('verify_peer' => false)
);
$ctx = stream_context_create($opts);
$handle = fopen($url, 'r', false, $ctx);
//var_dump($handle);
$content = "";
$flag = true;
while ($flag) {
$buffer = fread($handle, 100);
//$buffer = stream_get_line($handle, 1024, "\n");
$a = explode("\n", $buffer, 2);
$content = $content . $a[0];
#var_dump($a);
if (count($a) > 1) {
#echo $content;
#echo "\n";
$r = json_decode($content, true);
#var_dump($r);
// echo '<p>';
// echo "text: " . $r["text"];
// echo '<br>';
// echo "\nrceated_at: " . $r["created_at"];
// echo '<br>';
// echo "\nuser screen name: " . $r["user"]["screen_name"];
// echo '<br>';
// echo "\nuser id: " . $r["user"]["id"];
// echo '<br>';
// echo "\nid : " . $r["id"];
// echo '<br>';
// echo "\nin_reply_to_status_id: " . $r["in_reply_to_status_id"];
// echo '<p>';
// echo "\n\n";
$created_at = $r["created_at"];
$created_at = strtotime($created_at);
$mysqldate = date('Y-m-d H:i:s', $created_at);
//
// echo'<p>';
foreach ($topiclist as $key => $value) {
// echo'getshere!';
//$whichterm = $r["text"];
$whichterm = '"' . $r["text"] . '"';
//echo $whichterm;
if (stripos($whichterm, $value) !== false) {
// echo 'true:' . $value . '';
//find topicid
$whattopic = "SELECT TopicID
FROM Topics
WHERE Name = '$value'";
//var_dump($whattopic);
$tID = mysql_query($whattopic);
//var_dump($tID);
if (!$tID) {
// echo 'topic id not found.';
} else {
if (mysql_num_rows($tID) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($rec = mysql_fetch_assoc($tID)) {
$inserttweets = "INSERT INTO
Tweets(Topics_TopicID, AddDate, Tweetcontent)
VALUES('" . mysql_real_escape_string($rec['TopicID']) . "',
'" . mysql_real_escape_string($mysqldate) . "',
'" . mysql_real_escape_string($r["text"]) . "')";
//WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID'])
}
}
$addtweet = mysql_query($inserttweets);
if (!$addtweet) {
//something went wrong, display the error
//echo 'Something went wrong while adding tweet.';
//echo mysql_error(); //debugging purposes, uncomment when needed
} else {
echo 'Succesfully added tweet';
}
}
}
}
die();
$content = $a[1];
}
}
fclose($handle);
}
?>
"Pasting" a bunch of code inside a loop isn't a great practice. In fact, what you're looking for is a function or the use of a defined class. So, if you can, define a function in your topictweets.php that will contain your code and use it in your loop:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
processYourForums($fID);
/////////
////////
}
try include_once()
however, why not have a loop within topictweets.php?
you can do the query, etc.. in this page, but then loop through it in the include
This should work fine:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
}
You only need to include once.

Faster Rackspace cloud upload

I have used to the Rackspace API to upload files to the RackSpace cloud. But this method seems to be a little on the slow side. Is there a better or faster way to upload a file to the cloud(curl, http adapters, etc)?
I am currently uploading with PHP and using the provided API.
Here is my solution how to make it fast:
I'm uploading only missing files using simple PHP script below. Thanks to it I do it in just one click and in just a few seconds.
PHP source code:
function UploadMissingFilesToRackFileCDN($file_paths_to_upload, $b_force_upload = false)
{
include_once("cloudfiles.php");
// Connect to Rackspace
$username = cloudfile_username; // username
echo "Connecting to CDN..." . date("H:i:s") . "<br>"; ob_flush();
$key = cloudfile_api_key; // api key
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
echo " Connected!" . date("H:i:s") . "<br>"; ob_flush();
// Get the container we want to use
$container_name = 'vladonai';//'test_container';
echo "Obtaining container $container_name..." . date("H:i:s") . "<br>"; ob_flush();
$container = $conn->get_container($container_name);
echo " The container is obtained." . date("H:i:s") . "<br>"; ob_flush();
if (!$b_force_upload)
{
echo "Receiving container objects list..." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names = $container->list_objects();
$existing_files_count = count($existing_object_names);
echo " Objects list obtained: $existing_files_count." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names_text .= "\r\n";
foreach ($existing_object_names as $obj_name)
{
$existing_object_names_text .= $obj_name . "\r\n";
}
}
// upload files to Rackspace
$uploaded_file_n = 0;
$skipped_file_n = 0;
$errors_count = 0;
foreach ($file_paths_to_upload as $localfile_path => $file_info)
{
$filename = basename($localfile_path);
if (!file_exists($localfile_path))
{
echo "<font color=red>Error! File $localfile_path doesn't exists!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
} else
if (is_dir($localfile_path))
{
//simply skip it
} else
if (strpos($existing_object_names_text, "\r\n" . $filename . "\r\n") !== false)
{
//file is already uploaded to CDN (at least file name is present there). Would be good to have date/size checked, but CDN api has no such feature
//echo "<font color=gray>Skipped file $localfile_path - it already exists!</font><br>"; ob_flush();
$skipped_file_n ++;
} else
{
echo "<font color=green>Uploading file $localfile_path (file #$uploaded_file_n)..." . date("H:i:s") . "</font><br>"; ob_flush();
try
{
$object = $container->create_object($filename);
$object->load_from_filename($localfile_path);
$uploaded_file_n ++;
}
catch (Exception $e)
{
echo "<font color=red>Error! Caught exception: ", $e->getMessage(), " on uploading file <strong>$localfile_path</strong>!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
}
}
// if ($uploaded_file_n >= 10)
// break;
}
echo "Done! $uploaded_file_n files uploaded. Disconnecting :)" . date("H:i:s") . "<br>"; ob_flush();
echo "Skipped files: $skipped_file_n<br>"; ob_flush();
if ($errors_count > 0)
echo "<font color=red>Erorrs: $errors_count</font><br>"; ob_flush();
}
function UploadChangedImagesToRackFileCDN($b_force_upload = false)
{
$exclude = array
(
'.',
'..',
'*.html',
'*.htm',
'*.php',
'*.csv',
'*.log',
'*.txt',
'*.cfg',
//'*sub/forum/files/*',
);
$files_array_images = get_dirlist("/var/www/html/vladonai.com/images/", '*', $exclude, false);
$files_array = array_merge(get_dirlist("/var/www/html/vladonai.com/js/", '*', $exclude, false), $files_array_images);
UploadMissingFilesToRackFileCDN($files_array, $b_force_upload);
}
function get_dirlist($path, $match = '*', $exclude = array( '.', '..' ), $b_short_path = true)
{
$result = array();
if (($handle = opendir($path)))
{
while (false !== ($fname = readdir($handle)))
{
$skip = false;
if (!empty($exclude))
{
if (!is_array($exclude))
{
$skip = fnmatch($exclude, $fname) || fnmatch($exclude, $path . $fname);
} else
{
foreach ($exclude as $ex)
{
if (fnmatch($ex, $fname) || fnmatch($ex, $path . $fname))
$skip = true;
}
}
}
if (!$skip && (empty($match) || fnmatch($match, $fname)))
{
$file_full_path_and_name = $path . $fname;
//echo "$file_full_path_and_name<br>";
$b_dir = is_dir($file_full_path_and_name);
$b_link = is_link($file_full_path_and_name);
$file_size = ($b_dir || $b_link) ? 0 : filesize($file_full_path_and_name);
$file_mod_time = ($b_dir || $b_link) ? 0 : filemtime($file_full_path_and_name);
$new_result_element = array();
if ($b_short_path)
$file_name = str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name);//'[' . str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name) . ']';
else
$file_name = $file_full_path_and_name;
$result[$file_name] = array();
$result[$file_name]['size'] = $file_size;
$result[$file_name]['modtime'] = $file_mod_time;
if ($b_dir && !$b_link)
{
//recursively enumerate files in sub-directories
$result = array_merge(get_dirlist($file_full_path_and_name . "/", $match, $exclude, $b_short_path), $result);
}
}
}
closedir($handle);
}
return $result;
}

Categories