Writing Wordpress Data into a txt file - php

I have a custom post with up to 13 images. Beside some other information, I write the image names and titles into a txt-file, whereby each post information is stored on a separate line.
So far everything works fine execept when the first post has eg. 8 images and the second post has 5 images, than in the txt-file I have the first 5 images from the second post but also the 3 last images from the first post, even though they should be "empty" in the second line in the txt-file.
To get the image information from the wordpress database I have following code:
foreach($images as $image)
{
$path = parse_url(wp_get_attachment_url( $image ), PHP_URL_PATH);
$files_all['images'][] = $files['images'][] = ABSPATH . $path;
$files['title'][] = get_the_title($image);
$files['imagename'][] = basename(ABSPATH . $path);
}
if(!empty($files['imagename'][0]))
{
$pic1_filename = $files['imagename'][0];
$pic1_title = $files['title'][0];
}
if(!empty($files['imagename'][1]))
{
$pic2_filename = $files['imagename'][1];
$pic2_title = $files['title'][1];
}
if(!empty($files['imagename'][2]))
{
$pic3_filename = $files['imagename'][2];
$pic3_title = $files['title'][2];
}
if(!empty($files['imagename'][3]))
{
$pic4_filename = $files['imagename'][3];
$pic4_title = $files['title'][3];
}
if(!empty($files['imagename'][4]))
{
$pic5_filename = $files['imagename'][4];
$pic5_title = $files['title'][4];
}
if(!empty($files['imagename'][5]))
{
$pic6_filename = $files['imagename'][5];
$pic6_title = $files['title'][5];
}
if(!empty($files['imagename'][6]))
{
$pic7_filename = $files['imagename'][6];
$pic7_title = $files['title'][6];
}
if(!empty($files['imagename'][7]))
{
$pic8_filename = $files['imagename'][7];
$pic8_title = $files['title'][7];
}
if(!empty($files['imagename'][8]))
{
$pic9_filename = $files['imagename'][8];
$pic9_title = $files['title'][8];
}
if(!empty($files['imagename'][9]))
{
$pic10_filename = $files['imagename'][9];
$pic10_title = $files['title'][9];
}
if(!empty($files['imagename'][10]))
{
$pic11_filename = $files['imagename'][10];
$pic11_title = $files['title'][10];
}
if(!empty($files['imagename'][11]))
{
$pic12_filename = $files['imagename'][11];
$pic12_title = $files['title'][11];
}
if(!empty($files['imagename'][12]))
{
$pic13_filename = $files['imagename'][12];
$pic13_title = $files['title'][12];
}
The txt-File code looks as follows:
$txt .= "IDX3.01#Wordpress_4.6.2#".$proptype."#".$prop_label."#".$prop_status."#".$property_id."###".$address."#".$zip."#".$propcity."##".$country."###".$avail_from."#".$title.'#'.$post_description."#".$sale_price."#".$rent_price."##SELL#CHF###".$rooms."##".$property_size."#".$property_land."###".$property_year."#######".$garage."###".$distance_public_transport."#".$distance_shop."#".$distance_kindergarten."#".$distance_school1."#".$distance_school2."#".$pic1_filename."#".$pic2_filename."#".$pic3_filename."#".$pic4_filename."#".$pic5_filename."#".$pic1_title."#".$pic2_title."#".$pic3_title."#".$pic4_title."#".$pic5_title."######".$videos_name."#".$videos_title."##".$docname."#".$doctitle."##".$object_link."#agncyidxxxccc#Mischler Immobilien AG###Moosmattstrasse 23#6005#Luzern#CH#0413620101###info#mischler-immobilien.ch##".$agent_name."#0413620101#####".$pic6_filename."#".$pic7_filename."#".$pic8_filename."#".$pic9_filename."#".$pic6_title."#".$pic7_title."#".$pic8_title."#".$pic9_title."################################################".$pic10_filename."#".$pic11_filename."#".$pic12_filename."#".$pic13_filename."#".$pic10_title."#".$pic11_title."#".$pic12_title."#".$pic13_title."##################################".PHP_EOL;
The # are just separators within the file.
What did I miss here?

Related

Foreach loop not working properly in my Laravel 9 Code?

Screen Shot of HTML Form.
Can you suggest me where am I doing mistakes in my Laravel app, each time i am uploading multiple files throug the form, files is uploading perfectly in given location, but only 1 records are being inserted into database table. Here is my code...
// Upload bg_certificateArr photo
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
initialize $ac_bg for every foreach loop.
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
$ac_bg = new AccountBankGuarantee; // like this
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
You haven't posted full code here, but I believe before loop you somehow set $ac_bg variable. So looking at your code you create one record and update it in every next loop iteration.
So to fix this you should probably do something like this:
foreach ($request->file('bg_certificate') as $key => $file) {
$ac = new Ac(); // don't know what's the exact model class here
Then in every loop iteration you will create new record instead of updating it.

PHP add unique User array to newly created array while iterating over Episode authors object

Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}

Minimize efforts with foreach

I'm trying to build a script that will download users from a db table and attach a new random IP to each user based on his state.
The problem is that I wrote a lot of code and there is still much Copy/Paste job to be done if I keep it with this approach.
Can someone point me to the right direction on how to properly do that?
So first I have 50 of these:
$California_Text = file_get_contents('state/California.txt');
$California_textArray = explode("\n", $California_Text);
$Idaho_Text = file_get_contents('state/Idaho.txt');
$Idaho_textArray = explode("\n", $Idaho_Text);
$Illinois_Text = file_get_contents('state/Illinois.txt');
$Illinois_textArray = explode("\n", $Illinois_Text);
$Indiana_Text = file_get_contents('state/Illinois.txt');
$Indiana_textArray = explode("\n", $Indiana_Text);
$Iowa_Text = file_get_contents('state/Iowa.txt');
Then I have 50 of these:
while($row = $result->fetch_assoc()) {
if (isset($row["state"])) {
foreach ($row as $value){
$California_randArrayIndexNum = array_rand($California_textArray);
$p_California = $California_textArray[$California_randArrayIndexNum];
$Texas_randArrayIndexNum = array_rand($Texas_textArray);
$p_Texas = $Texas_textArray[$Texas_randArrayIndexNum];
$Alabama_randArrayIndexNum = array_rand($Alabama_textArray);
$p_Alabama = $Alabama_textArray[$Alabama_randArrayIndexNum];
$Alaska_randArrayIndexNum = array_rand($Alaska_textArray);
$p_Alaska = $Texas_textArray[$Alaska_randArrayIndexNum];
$Arizona_randArrayIndexNum = array_rand($Arizona_textArray);
$p_Arizona = $California_textArray[$Arizona_randArrayIndexNum];
.....
Then I have 50 of these:
if ($row["state"] == "california") {
$stateip = $p_California;
}
else if ($row["state"] == "texas") {
$stateip = $p_Texas;
}
else if ($row["state"] == "alabama") {
$stateip = $p_Alabama;
}
else if ($row["state"] == "alaska") {
$stateip = $p_Alaska;
}
I'm pretty much sure that it's a bad approach.. Maybe there's a way to do all this with like 3 lines of foreach?
Something like this:
// holds your content
$state_content = [];
while($row = $result->fetch_assoc()) {
// check do we have state set
if (!empty($row["state"])) {
$stateip = getStateIpByName($row["state"]);
}
}
/**
* Returns random IP
*/
function getStateIpByName($state_name) {
$content = getStateContent($state_name);
return $content[array_rand($content)];
}
/**
* Returns your's state content by state name
*/
function getStateContent($state_name) {
// checks do we already have content for this state
if(!isset($state_content[$state_name])) {
// generate file name
$file_name = "state/";
$file_name .= str_replace(" ", "", ucwords($state_name));
$file_name .= ".txt";
$state_text = file_get_contents($file_name);
$state_content[$state_name] = explode("\n", $state_text);
}
return $state_content[$state_name];
}
There are probably some errors but you will get idea.
Store all states in an array and do all operations within a foreach block
$states=['california',..];
foreach($states as $state){
//Your code for one state
//Replace state name with $state variable
}

How To Add An RSS Feed To My Search.php file?

I'm running a social network and right now my search.php shows results for people, and tags. How can I add an RSS Feed? I own a blog and I wanted to add my RSS Feed to the search so whenever someone searches for a topic it will show up on the search page.
Here's the search.php code:
$feed = new feed();
$feed->db = $db;
$feed->url = $CONF['url'];
if(isset($_SESSION['username']) && isset($_SESSION['password']) || isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$verify = $loggedIn->verify();
if($verify['username']) {
$feed->user = $verify;
$feed->username = $verify['username'];
$feed->id = $verify['idu'];
if(isset($_GET['tag'])) {
$skin = new skin('shared/top'); $top = '';
$TMPL['theme_url'] = $CONF['theme_url'];
$TMPL['private_message'] = $verify['privacy'];
$TMPL['avatar'] = $verify['image'];
$TMPL['url'] = $CONF['url'];
$top = $skin->make();
}
}
}
$feed->per_page = $settings['perpage'];
$feed->time = $settings['time'];
$feed->censor = $settings['censor'];
$feed->smiles = $settings['smiles'];
$feed->c_per_page = $settings['cperpage'];
$feed->c_start = 0;
$feed->l_per_post = $settings['lperpost'];
$TMPL_old = $TMPL; $TMPL = array();
$skin = new skin('shared/rows'); $rows = '';
if(empty($_GET['filter'])) {
$_GET['filter'] = '';
}
// Allowed types
if(isset($_GET['tag'])) {
// If the $_GET keyword is empty [hashtag]
if($_GET['tag'] == '') {
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$hashtags = $feed->getHashtags(0, $settings['qperpage'], $_GET['tag'], null);
$TMPL['messages'] = $hashtags[0];
} else {
// If the $_GET keyword is empty [user]
if($_GET['q'] == '') {
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$TMPL['messages'] = $feed->getSearch(0, $settings['qperpage'], $_GET['q'], $_GET['filter']);
}
$rows = $skin->make();
$skin = new skin('search/sidebar'); $sidebar = '';
if(isset($_GET['tag'])) {
$TMPL['trending'] = $feed->sidebarTrending($_GET['tag'], 10);
} else {
$TMPL['genre'] = $feed->sidebarGender($_GET['filter'], $_GET['q']);
}
$TMPL['ad'] = generateAd($settings['ad6']);
$sidebar = $skin->make();
$TMPL = $TMPL_old; unset($TMPL_old);
$TMPL['top'] = $top;
$TMPL['rows'] = $rows;
$TMPL['sidebar'] = $sidebar;
if(isset($_GET['logout']) == 1) {
$loggedIn->logOut();
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$TMPL['url'] = $CONF['url'];
if(isset($_GET['tag'])) {
$TMPL['title'] = '#'.$_GET['tag'].' - '.$settings['title'];
} else {
$TMPL['title'] = $LNG['title_search'].' - '.$_GET['q'].' - '.$settings['title'];
}
$skin = new skin('shared/timeline_x');
return $skin->make();
Please help :)
Try this example
<?php
$articles = $pages->find('blog')->children()->visible()->flip()->limit(10);
snippet('feed', array(
'link' => url('blog'),
'items' => $articles,
'descriptionField' => 'text',
'descriptionLength' => 300
));
?>
link:
This is the main link in our feed, which takes the visitor back to our site. In this case we want them to get back to our blog, so we build an url to our blog with the url() helper function.
items:
As items for our feed, we pass the set of $articles we found in the first line. The feed snippet will automatically take care of getting the right info out of those $articles (like title, url, etc.)
descriptionField:
If you want to show a description for each item in your feed, you need to specify a field, which is available in any item and should be used for the description.
descriptionLength:
This is maximum number of characters the description will have. An excerpt is automatically generated by the feed snippet.

MySQL:Update (not uploading image)

Think of simple profile page. User must editing. So, I've created basic php page. But, it is doesn't upload image. Why is it not uploading? I don't understand.
<?php
if((array_key_exists("degistir",$_GET) && $_GET['degistir'] == "dogru") && (array_key_exists('uyeId',$_GET) && $_GET['uyeId'] == md5(#$_SESSION['uyeGiris_skype'])))
{
if(isset($_POST['duzenlemeBitir']))
{
$uyeUrl_ = "inc/imj/uye/".$_SESSION['uyeGiris_skype'];
if(!is_dir($uyeUrl_)){mkdir($uyeUrl_);
$profilResim = $uyeUrl."/".$FILES['profilResim']['name'];
move_uploaded_file($_FILES['profilResim']['tmp_name'],$profilResim) or die(mysql_error());
$galeri = array();
for($s=1; $s<9; $s++)
{
$uyeUrlLink = $uyeUrl_."/".$_FILES['galeri'.$s]['name'];
$uyeUrlAdi = $_FILES['galeri'.$s]['name'];
move_uploaded_file($_FILES['galeri'.$s]['tmp_name'],$uyeUrlLink) or die(mysql_error());
$galeri[$s] = $uyeUrlLink;
}
if(!isset($_FILES['profilResim']['value']))
{
$_FILES['profilResim']['value'] = $uyeDetay['profilResim'];
}
if(!isset($_FILES['galeri1']['value']))
{
$_FILES['galeri1']['value'] = $uyeDetay['galeri1'];
}
if(!isset($_FILES['galeri2']['value']))
{
$_FILES['galeri2']['value'] = $uyeDetay['galeri2'];
}
if(!isset($_FILES['galeri3']['value']))
{
$_FILES['galeri3']['value'] = $uyeDetay['galeri3'];
}
if(!isset($_FILES['galeri4']['value']))
{
$_FILES['galeri4']['value'] = $uyeDetay['galeri4'];
}
if(!isset($_FILES['galeri5']['value']))
{
$_FILES['galeri5']['value'] = $uyeDetay['galeri5'];
}
if(!isset($_FILES['galeri6']['value']))
{
$_FILES['galeri6']['value'] = $uyeDetay['galeri6'];
}
if(!isset($_FILES['galeri7']['value']))
{
$_FILES['galeri7']['value'] = $uyeDetay['galeri7'];
}
if(!isset($_FILES['galeri8']['value']))
{
$_FILES['galeri8']['value'] = $uyeDetay['galeri8'];
}
$ekle = mysql_query("UPDATE uye SET skype='".$_POST['skype']."', msn='".$_POST['msn']."', facebook='".$_POST['facebook']."', yas='".$_POST['yas']."', boy='".$_POST['boy']."', kilo='".$_POST['kilo']."', hakkinda='".$_POST['hakkinda']."', profil_resim='".$profilResim."', galeri_1='".$galeri[1]."', galeri_2='".$galeri[2]."', galeri_3='".$galeri[3]."', galeri_4='".$galeri[4]."', galeri_5='".$galeri[5]."', galeri_6='".$galeri[6]."', galeri_7='".$galeri[7]."', galeri_8='".$galeri[8]."' WHERE e_posta = '".$_SESSION['uyeGiris_ePosta']."' AND sifre='".$_SESSION['uyeGiris_sifre']."'") or die(mysql_error());
}
}
?>
Notice: This codes have mysql_error() functions but I can't see error the simple profil editing page..
Thank you for your interest.
Good works..
Clerical error..
$uyeUrl = blabla..
if(!is_dir($uyeUrl_)){mkdir($uyeUrl_);}
$profilResim = $uyeUrl_."/".$FILES['profilResim']['name'];

Categories