Posts Tagged php

Error 101 upload (net::ERR_CONNECTION_RESET) when Uploading large files on Drupal

Wow, now this was one of those problems that really makes you want to put your head through a wall.

Soo, I was uploading a large file to my CMS through drupal and at about 35%(of a 40MB file) I would get booted to an error page with the following message.  I looked high and low and while I found a solution that told me to go into mysql and set the wait_timeout like this: “set wait_timeout = 28800″ (for some reason my host had it set to 45) it was still occurring.

The other thing was to put this: mysqli.reconnect = On in my php.ini file which didn’t work but then I tried this isntead: mysql.reconnect = On and I’m not 100% sure if that was what did it but the last thing I did was I bypassed my router and plugged the cable modem into the laptop directly and guess what?  Bloody file went through..

2 hours later I get my life back

Funny enough now I’v

Tags: , , , , ,

ATTN FreeBSD users – Throw Zend in the trash as that shit won’t work at all in 3 months

Well as some of you may or may not know php 5.2 is going to be going the way of the dinosaur come March, it’s already been depreciated and no longer being supported but in March it’s being removed from the port tree all together from what I understand.  This brings me to the topic of today’s post which is that the kind folks over at Zend have made it abundantly clear(Refer to this) that they have no intention of supporting FreeBSD at all in the future with their new products, Zend Guard in particular.  The catch here is that Zend Optimizer, the one product that does work with FreeBSD is also depreciated and does not work with php 5.3.  Come March, unless you plan on using a completely vulnerable and exploitable version of php Zend Optimizer will no longer work at all.

So the moral and point of this whole post is to give you a little warning so you can make arrangements.  It means getting rid of this Zend bullshit and make sure that you account for all your software currently encoded with Zend and get onto something not governed by such old world profit driven business models to something more progressive like Ioncube.

 

Prepare ye mortals, the end is nigh! 

Tags: , , , , , ,

How to have wordpress load plugins in a specific order

Or more specifically in this example how to get wordpress to load a specific  plugin before all others.  By default wordpress will load your plugins in alphabetical order as for the most part 99.99% of people could care less and are unaffected by plugin execution order.  However for that .01% of us(don’t you feel special now?) it can cause some serious havoc to have one plugin do it’s thang before another.  In order to give one plugin priority and load first you need to stick the following code in that plugin’s main php file:

 

function this_plugin_first() {
// ensure path to this file is via main wp plugin path
$wp_path_to_this_file = preg_replace('/(.*)plugins\/(.*)$/', WP_PLUGIN_DIR."/$2", __FILE__);
$this_plugin = plugin_basename(trim($wp_path_to_this_file));
$active_plugins = get_option('active_plugins');
$this_plugin_key = array_search($this_plugin, $active_plugins);
if ($this_plugin_key) { // if it's 0 it's the first plugin already, no need to continue
array_splice($active_plugins, $this_plugin_key, 1);
array_unshift($active_plugins, $this_plugin);
update_option('active_plugins', $active_plugins);
}
}
add_action("activated_plugin", "this_plugin_first");

Many thanks to jsdalton in this thread: http://wordpress.org/support/topic/how-to-change-plugins-load-order for posting up the solution and make sure you check out that thread for more discussions on the topic

 

Alternatively there is a handy little plugin that helps you do this and more found here: http://wordpress.org/extend/plugins/plugin-organizer/

Tags: , , , , ,

How to do a global search and replace within a DB across all Tables

As part of my take over the world campaign I’ve run into the need to automatically do a global Search and replace within a Mysql Database covering all tables.  For this you need a little php magic and luckily enough I found just that magic right here.

I’ll save you the looking up time and paste it below but make sure to thank to the original author on their blog:

 

<?php
// Find and replace facility for complete MySQL database
//
// Written by Mark Jackson @ MJDIGITAL
// Can be used by anyone - but give me a nod if you do!
// http://www.mjdigital.co.uk/blog

// SEARCH FOR
$search        = '**__FIND_THIS__**';

// REPLACE WITH
$replace    = '**__REPLACE_WITH_THIS__**'; // (used if queryType below is set to 'replace')

// DB Details
$hostname = "__DB_HOST__";
$database = "__DB_DATABASE__";
$username = "__DB_USER__";
$password = "__DB_PASSWORD__";

// Query Type: 'search' or 'replace'
$queryType = 'replace';

// show errors (.ini file dependant) - true/false
$showErrors = true;

//////////////////////////////////////////////////////
//
//        DO NOT EDIT BELOW
//
//////////////////////////////////////////////////////

if($showErrors) {
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);
}

// Create connectio to DB
$MJCONN = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database,$MJCONN);

// Get list of tables
$table_sql = 'SHOW TABLES';
$table_q = mysql_query($table_sql,$MJCONN) or die("Cannot Query DB: ".mysql_error());
$tables_r = mysql_fetch_assoc($table_q);
$tables = array();

do{
$tables[] = $tables_r['Tables_in_'.strtolower($database)];
}while($tables_r = mysql_fetch_assoc($table_q));

// create array to hold required SQL
$use_sql = array();

$rowHeading = ($queryType=='replace') ?
'Replacing \''.$search.'\' with \''.$replace.'\' in \''.$database."'\n\nSTATUS    |    ROWS AFFECTED    |    TABLE/FIELD    (+ERROR)\n"
: 'Searching for \''.$search.'\' in \''.$database."'\n\nSTATUS    |    ROWS CONTAINING    |    TABLE/FIELD    (+ERROR)\n";

$output = $rowHeading;

$summary = '';

// LOOP THROUGH EACH TABLE
foreach($tables as $table) {
// GET A LIST OF FIELDS
$field_sql = 'SHOW FIELDS FROM '.$table;
$field_q = mysql_query($field_sql,$MJCONN);
$field_r = mysql_fetch_assoc($field_q);

// compile + run SQL
do {
$field = $field_r['Field'];
$type = $field_r['Type'];

switch(true) {
// set which column types can be replaced/searched
case stristr(strtolower($type),'char'): $typeOK = true; break;
case stristr(strtolower($type),'text'): $typeOK = true; break;
case stristr(strtolower($type),'blob'): $typeOK = true; break;
case stristr(strtolower($field_r['Key']),'pri'): $typeOK = false; break; // do not replace on primary keys
default: $typeOK = false; break;
}

if($typeOK) { // Field type is OK ro replacement
// create unique handle for update_sql array
$handle = $table.'_'.$field;
if($queryType=='replace') {
$sql[$handle]['sql'] = 'UPDATE '.$table.' SET '.$field.' = REPLACE('.$field.',\''.$search.'\',\''.$replace.'\')';
} else {
$sql[$handle]['sql'] = 'SELECT * FROM '.$table.' WHERE '.$field.' REGEXP(\''.$search.'\')';
}

// execute SQL
$error = false;
$query = @mysql_query($sql[$handle]['sql'],$MJCONN) or $error = mysql_error();
$row_count = @mysql_affected_rows() or $row_count = 0;

// store the output (just in case)
$sql[$handle]['result'] = $query;
$sql[$handle]['affected'] = $row_count;
$sql[$handle]['error'] = $error;

// Write out Results into $output
$output .= ($query) ? 'OK        ' : '--        ';
$output .= ($row_count>0) ? '<strong>'.$row_count.'</strong>            ' : '<span style="color:#CCC">'.$row_count.'</span>            ';
$fieldName = '`'.$table.'`.`'.$field.'`';
$output .= $fieldName;
$erTab = str_repeat(' ', (60-strlen($fieldName)) );
$output .= ($error) ? $erTab.'(ERROR: '.$error.')' : '';

$output .= "\n";
}
}while($field_r = mysql_fetch_assoc($field_q));
}

// write the output out to the page
echo '<pre>';
echo $output."\n";
echo '<pre>';
?>

Tags: , , , , ,

Not all Javascript popup boxes are created equal

I was implementing a feature onto one of my networks today and needed to use a javascript popup box to bring up a booking table.  You know those cool boxes that darken the rest of the screen and popup a slick looking window?  Well I needed one and apparently they all such except the one titled: “A pop-up window that doesn’t suck“.  You can skip this article and go straight to it here if you want: http://orangoo.com/labs/greybox/installation.html

 

The first box I tried was TinyBox which looks great,  probably the slickest looking of the boxes but it had problems loading a php file in an iframe properly.  You see I need it to load page.php?id=5555 where 5555 would go into certain areas of the page that get that url variable.  It loaded all the code properly it just wouldnt’ execute the php within the page.

The second one I found was Thickbox which worked out well enough again,it looks slick, not as cool as TinyBox but still nifty however unfortunately we encounter the same problem.  Php is loaded by not executed… Booooerns

The saying ‘third time’s the charm’ applies perfectly here because last but definitely not least I found GreyBox which is aptly titled: A pop-up window that doesn’t suck which turned out to be not just a euphamism but actually true because unlike the cool looking shitty boxes prior that wouldn’t execute my php Greybox worked like a bloody charm.  Unfortunately it doesn’t quite look as cool however I was able to customize the close button and change that grey gradiant so it at least looks a bit better.

Tags: , , , , , , ,

FreeBSD 8.1, Zend Optimizer, php52-extensions and the dreaded Segmentation Fault (Core Dumped)

So I haven’t slept in 43 hours, it’s been at least 10 years since I’ve pulled this kind of stunt before but as you know from my last blog post here my server blew up and then my lappy blew up, so lots and lots to keep me busy with.. Part of that fun was doing a brand new fresh OS install on my server, and getting everything working just as it was before is never a cakewalk.  Well it was looking like it was until I started seeing this little Segmentation Fault at the end of my php -v statement.  I mean not to mention the 5-6 hours I spent wresting with ZendOptimizer but that was resolved and wasn’t nearly as epic, nor as disappointing at the 20+ hours that went into figuring this god awful problem.

For whatever reason when php52-mysql or php52-pdo_mysql were installed there would always be a segmentation error in shell.  It didn’t affect the websites mind you, that ran fine but running anything with php through shell wasn’t not happening(there goes 1/2 my cron).  So what do I do? I hop on freenode, undernet and efnet and start asking around as well as googling my face off.  And man oh man there are a ton of reasons why this could be happening and trust you me I went through them all.. But the key problem with my problem solving was that I was looking in completely the wrong place.  You see early on I was convinced that this was a php problem.  Probably set that way as an impatient chap named GoMYSQL on #mysql on freenode quite quickly told me it was and to take my question out of his sacred and holy channel.  So for the next 30 hours or so I proceeded to rip the very fabric of php apart in search of what cuold be causing this.  I commented out everything in extensions.ini, in php.ini narrowing it all down to mysql.so or alternatively pdo_mysql.so caused the same problem.   There was talk about the order of the extensions in extensions.ini causing issue so I tried mysql.so in every single spot on that list to no avail, the only thing that made the seg fault go away was to comment out mysql.so itself but then that kind of left me without a slightly important piece of functionality.

Well guess the fuck what?  It isn’t a php issue at all, it is a problem with mysql55.  For whatever reason I installed mysql55 instead of mysql50(bigger is better right?) and whether it’s a conflict with mysql55 and Zend, or Zend, php52-mysql and mysql55, or all of the above and eaccelerator or what but having that version of mysql installed caused this whole mess in the first place.

So her I am, 43 hours later and probably at least a dozen pots of green tea, completely out of option I figure why the hell not try mysql50?  On this old server it’s a hell of a wait to deinstall and recompile but nothing else is working.  Lo and fucking behold the minute it’s up and php52-extentions and php52-mysql are recompiled along side all my worries dissapear.  No more zend seg faults, no more mysql.so seg faults nada, zip zilch.

And for whatever reason this will be the very first post/article anywhere offering this advice because everyone else is dealing with a php issue.  So if this is you, if you have just installed php52 and php52-mysql or php anything-mysql and you are seeing everything loading fine except for mysql.so causing a segmentation fault do yourself a big favor and check what version of mysql you have installed.   If you are running mysql55 and Zend, or eAccelerator and Zend and mysql or any combination of the bunch get rid of mysql55 and install mysql50.  After you’ve done that you’re going to need to recompile php52-mysql and/or php52-pdo_mysql(or whatever version of phpxx-mysql you’re running) and then go in and recompile php52-extensions.  After all that restart apache and go to sleep!

I know that’s exactly what I’m about to do

Tags: , , , , , , , , , , , , , ,

Getting wordpress to print the post date in a title of a post

Wow, getting wordpress to print a few bloody words in the title of a post turned out to be a massive ordeal here.  For one of my projects I have a post that uses php (thanks to php-exec for allowing php be to be run inside of a WP post) to pull rss feeds and populate the post body with it’s information.  So what I do with this is I just have wordpress repost the same post every day (thanks to the plugin ‘reposter reloaded) but what I want to happen is for the title of the post to be updated every day with the date of the repost.  So I can say something like ‘New info for January 13th 2010′ and the date in that title will be updated to January 14th 2010 when it gets reposted tomorrow and so on and so forth.

Weeellllllllll this proved to be way more complicated than expected.. I was hoping, as with the other stuff that I would just be able to insert something like ‘the_date();’ into the title box and have php-exec automatically take that and miraculously transform it into the date but oooh noo, for whatever reason php is not allowed to be executed in the title.  Sure I can execute it in the body of a post, the excerpt but the title is just a little too sacred for that.  This left me with the fun task of mucking around with the template however I only wanted the date tacked onto the end of titles for posts that were in a specific category, but to make things even more complicated I didn’t even want it to go with a certain category, what I needed was for it to apply only to posts in categories that contained a specific keyword.

So what I had to do was create this little script that would look at the category which this post belonged, check this category contained a certain word and if it did it would tack on the date to the end of the title for the post.  Sounds easy enough eh?  Well I imagine for someone with a modicum of php and wordpress hacking experience this would have been easy but I unfortunately have neither of those things.  So 15 hours later or so it’s finally working :)   And to save you the time here it is, over commented for others with similarly limited experience in these matters:

Open up /wp-content/themes/YOURTHEME/loop.php (you may also need to do the same in single.php but I’m not sure if it’s necessary)

<?php
// lets find out what category this post belongs to and apply that to a new variable

$category = get_the_category_list( ‘, ‘ );

// Lets do the same thing but with the date

$date = the_date();

// now we need to look at the $category variable and see if it contains a specific keyword, in this case the word is ‘job’

$pos = strpos($category, job);
// If it doesn’t contain this keyword then strpos will return a ‘false’ value, in which case we want it to append empty air to the end of the title

if ($pos === false) {
echo ” “;

// Now if the keyword is contained in our search parameters what strpos does is returns a numeric value indicatin the postition in our search terms where our keyword starts.  We dont’ really care about that, all we care about is that strpos is return a value, any value that isn’t false and if this is the case then we have our $date variable tacked echoed as seen below
} else    {
echo “$date” ;
}
?>

Now what I did is I placed all of this inside the <H1> title tags in the single.php file.  So normally it would look like this:

<h1><?php the_title(); ?> </h1>

But now it looks like this:

<h1><?php the_title(); ?>
<?php
$category = get_the_category_list( ‘, ‘ );
$date = the_date();
$pos = strpos($category, job);

if ($pos === false) {
echo ” “;
} else    {
echo “$date” ;
}
?>
</h1>

Tada…

Tags: , , , ,

Nginx 502 errors, php problems, wordpress, oh my!

Well today is a glorious day as I finally managed to fix a problem that had been haunting my server for a month or so.  In the end it was a solution that I’ve been taught countless times as something I should be doing by default when upgrading php but alas my mind is not on of the more expensive models and so it rarely does what it should..

So it all started with a fairly minor issue I noticed in WordPress.   When I would try to load up the media gallery I would be greeted with a nice 502  Nginx error.  I’m sure if I wasn’t running nginx then it would have a blank white page or an apache error.  So naturally I started with the nginx error logs which didn’t lead to much.. Then I setup php to log all errors and again that didn’t lead me to much, finally however I monitored my httpd-error.log and this lovely message turned up:

[warn] (2)No such file or directory: Cannot reinit SSLMutex
/libexec/ld-elf.so.1: /usr/local/lib/php/20060613/gd.so: Undefined symbol “zend_parse_parameters_none”

After some asking around on irc I was told that it was definitely a php problem.  Nothing more specific than that, just a php problem.  There were a bunch of forum posts saying it might have something to do with fastCGI but all the suggestions had no effect.  However there was one forum I foudn that through a suggestion out there that lit up a light bulb in my brain.  That being that if php5-extensions isn’t recompiled and reinstalled when php is updated sometimes the fit hits the shan.  Sure enough I had upgrade php5 a while back, and then again since then but hadn’t bothered to recompile the extensions.  Hell I hadn’t even recompiled Zend or Eaccelerator which is pretty standard.

So long story slightly shorter, I went in deinstalled and cleaned up my php5-extensions, reinstalled it and viola, problem solved!!

Tags: , , , , , ,

Your own free content spinner shell script in bash (fTW!)

So today I set out to modify my massive unique tweet and content generator for my Netsyphon network(ie: hotel-kelowna, innkelowna.com, kelownasrestaurants.com, etc etc) and add an inline content spinner to it.  To date there are a lot of search/replaces happening but they are all one time replaces and reference external files for the replace values..  Usually there were only one or two possible s/r results per line so I could handle it easily with gsub.

But now I wanted to be able to take a single article with a ton of spinnable content and have a script generate 10-20-100 different versions of this article.  I would have a sentence where 80% of the content was spinnable with infinite amount of results.  I could handle this with the old method but it would require creating a ton of external files for each search/replace possibility which would get insane.  Instead I knew that there had to be a relatively simple method with bash to make this happen, and much to my delight the boys over at #bash on irc.freenode came to the rescue

Big props out to \amethyst and geirha, my two heroes for the day.  Some useful info from #bash as well:

FAQ: http://mywiki.wooledge.org/BashFAQ | Guide: http://mywiki.wooledge.org/BashGuide | ref: http://tinyurl.com/txlv | http://bash-hackers.org/wiki/ | USE MORE QUOTES!: http://www.grymoire.com/Unix/Quote.html | Scripts and more: http://www.shelldorado.com/

And without further ado here are the scripts that were created by these two gents.

http://pastebin.com/xNgKaR2c:

FAQ: http://mywiki.wooledge.org/BashFAQ | Guide: http://mywiki.wooledge.org/BashGuide | ref: http://tinyurl.com/txlv | http://bash-hackers.org/wiki/ | USE MORE QUOTES!: http://www.grymoire.com/Unix/Quote.html | Scripts and more: http://www.shelldorado.com/

And without further ado here are the scripts that were created by these two gents.

The first by Geirha, is setup to read from an external file , and if not will take the input from stdin

http://pastebin.com/xNgKaR2c:

spinner_thingy ()
{
while read -r -d ‘{‘; do
printf “%s” “$REPLY”;
IFS=’|’ read -r -d ‘}’ -a words;
n=${#words[@]};
((n)) && printf “%s” “${words[RANDOM%n]}”;
done < “${1:-/dev/stdin}”;
printf “%s” “$REPLY”
}

The second by\amethyst can be found here: http://pastebin.com/tAXJ04L6

I went ahead and replaced the example line at the top with a reference to a filename

line=”$(<test.txt)”
makesentence ()
{
local line=”$1″
while [[ $line = *{*}* ]]; do
local -a choices
local prefix=${line%%{*} rest=${line#*{}
local choice=${rest%%\}*}
line=${rest#*\}}
IFS=’|’ read -a choices <<< “$choice”
[[ $choice = *"|" ]] && choices+=( “” )
printf “%s” “$prefix”
if (( ${#choices[@]} )); then
printf “%s” “${choices[RANDOM % ${#choices[@]}]}”
fi
done
printf “%s\n” “$line”
}
makesentence “$line”

So there you have it.. 30 minutes in IRC and the helpful boys over at #bash have me right as rain.. Again a big shout out, these guys have been integral in helping me with all of my scripting in this project.. I would have jack if it wasn’t for them.

As a parting gift I also found a way to do this with php, but alas I wanted a shell script that I could easily integrate into the mothership so it was all one nice neat package.. But for those php guys here it is:

<?php
$text = "The {quick|slow|reasonably paced} {brown|green|blue|pink} {fox|goat|rat|camel}
{jumped|walked|hopped} {over|past|under} the {lazy|tired|boring} {dog|cat|stoat}";
$count = 0;
while ($count++ < 100){
echo Spin($text);
echo "<br />";
}
?>

Now go generate some content!

Tags: , , , , , , , ,

Page optimized by WP Minify WordPress Plugin