multiple shorten url's issue - php

i have a code to shorten multiple links but that code ( with an Optional Suffix ) the code is work from the second link only:
$url_to_shorten = $_POST[links];
$ownshuff = $_POST[shuff];
$theurls = explode("\n",$url_to_shorten);
foreach($theurls as $urlmulti){
shortcreate($urlmulti,$shuffss,$ownshuff);
}
here is an example :
my links are
http://www.123.com
http://www.1234.com
http://www.1235.com
and my Suffix is : ( Hello_Man ).
with the above code it prints
http://www.mysite.com/IUo
http://www.mysite.com/kOl-Hello_Man
http://www.mysite.com/Rww-Hello_Man
and it not print the Suffix for the first link.
the shortcreate function is :
function shortcreate($url_long, $Suffix, $ownshuf){
global $db;
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
$url = $url_long;
$url = trim($url);
$url = mysql_real_escape_string($url);
if (!shortisThere($url)) {
$q = "INSERT INTO `shorturls` (url, unique_chars) VALUES ('" . $url . "', '" . $chars . "')";
//echo $q;
$r = $db->query($q);
if (mysql_affected_rows()):
$q = "SELECT * FROM `shorturls` WHERE `url`='" . $url . "'";
$r = $db->query($q);
$row = $db->fetch($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
else:
$the_url = NULL;
return false;
endif;
}
else {
$q = "SELECT * FROM `shorturls` WHERE `url` = '" . $url . "'";
$r = mysql_query($q);
$row = mysql_fetch_row($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
}
}
i need that code to work for all the links. any help
regards

I guess that the problem is in the next block of code:
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
You give the $chars variable the value of the suffix and you check if it's unique (guess not because it's getting into the loop) and that condition of $ownshuf != "" returns false from some reason (consider to share with us what's that parameter's value), otherwise the output of $chars would return a string with "-".
REMINDER: Share with us what's that parameter's value

Related

Creating unique slug using title of post

I have an add post form to add new post. I have taken post title as post_url or slug. I want unique post_url.
Here is what I have done so far -
$post_name = $this->input->post('post_title');
function clean($post_name) {
$name = trim($post_name);
$post_name = str_replace(' ', '-', $name);
return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
}
$post_url = clean($post_name);
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;
I am getting output as -
post-url
post-url-1
post-url-1-1
post-url-1-1-1
But I want output as -
post-url
post-url-1
post-url-2
post-url-3
What is a problem in my code?
Please help me.
Thanks.
function UniqueSlugGenerator($p){
include("conn.php");
$RowCou=0;
$slug = preg_replace('/[^a-z0-9]/', '-', strtolower(trim(strip_tags($p))));
$qq = mysqli_query($conn,"select Slug from ser_posts where Slug like '$slug%'") or die(mysqli_error($conn));
$RowCou = mysqli_num_rows($qq);
return ($RowCou > 0) ? $slug.'-'.(++$RowCou) : $slug;
}
Change your code in the following way
$post_url = clean($post_name);
$post_url1 = $post_url;
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
$post_url = $post_url1;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;

Why does the loop execute only once?

I have the following small code which manipulate tweets data. I expect my loop to iterate 10 times. However, what happens is that it iterates only once and then exits, with no sign of any error relating to MySQL or otherwise.
$query = "select data from tweets where `screen_name` = 'username' limit 10";
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
$tweets = mysqli_fetch_assoc($tweetsq);
$tweets_count = mysqli_num_rows($tweetsq);
echo $tweets_count . '<br />'; //See output
$count = 0;
foreach ($tweets as $raw_tweet) {
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
$is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0;
$is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0;
$entity_holder = array();
$has_hashtag = $has_url = $has_mention = $has_media = 0;
foreach ($tweet->entities as $type => $entity) {
if (is_array($entity) && count($entity) < 1) {
//continue;
} else {
$entity = array_pop($entity);
switch ($type) {
case 'hashtags' : $has_hashtag = 1; break;
case 'urls' : $has_url = 1; break;
case 'user_mentions' : $has_mention = 1; break;
case 'media' : $has_media = 1; break;
default :
}
}
}
echo 'Updating recorde... <br />';
$query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'";
$result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
var_dump($result); //See output
$count++;
echo '<br />';
}
echo $count;
Output:
10 //This is the value of $tweets_count
Updating recorde...
bool(true) //The result of the UPDATE query
1 //The value of $count at the end of script. It SHOULD be 10
mysqli_fetch_assoc fetches a single row as an associative array where the key is the column name and the value is the column value. The correct way to use it would be to iterate over the result set until the fetch returns NULL, indicating that there are no more rows to fetch:
while ($row = mysqli_fetch_assoc($tweetsq)) {
$raw_tweet = $row["data"];
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
# etc...

Why foreach enters into if only on first loop?

If I loop through foreach loop only on first time it enters into if and gets variable values, so each next time it still have old values. why?
If I print_r($i) and kill it responds:
A0A0A0A0A0A0A0A0A0A0A0A0A0A0TXTTXT16
Real amount is end of it(16). So that means it loops 16 times through loop but into if enters only on first loop of if $type changes. So $type doesn't get new value each time it runs through loop.
Code I have:
$recordTypes = array('CnameRecord', 'ARecord', 'MxRecord', 'TxtRecord');
foreach ($recordTypes as $type) {
$modelName = $type::model()->tableName();
$record = $type::model()->findAllbySql("SELECT * FROM $modelName WHERE vhost_id LIKE $id");
if ($record) {
foreach ($record as $key=>$rec) {
if ($type == 'ARecord'){
$type = 'A' + $i;
$hostname = $rec['sub_vhost_name'];
$points_to = $rec['points_to'];
$ttl = $rec['ttl'];
} else if ($type == 'CnameRecord') {
$type = 'CNAME';
$hostname = $rec['hostname'];
$points_to = $rec['points_to'];
$ttl = $rec['ttl'];
} else if ($type == 'MxRecord') {
$type = 'MX';
$priority = $rec['priority'] . ' ';
$points_to = $rec['points_to'];
$ttl = $rec['ttl'];
$hostname = $rec['host'];
} else if ($type == 'TxtRecord') {
$type = 'TXT';
$hostname = $rec['hostname'];
$points_to = '"' . $rec['txt_value'] . '" ';
$ttl = $rec['ttl'];
}
$i++;
print_r($type);
$custom_content = $hostname . ' ' . $ttl . ' ' . 'IN' . ' ' . $type . ' ' . $priority . $points_to . "\n";
}
}
}
print_r($i);die;
you are using:
foreach ($recordTypes as $type) { ...
And inside the foreach you're modifying the "type" var, so in the next loops through $record, you'll fail any if statement.
Change the $type var (inside if statements) to another var name and try again.

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

php domain validation

I need bit help as I am facing two issues.
Links without domain extension (.com, .net, ect) will be stored in
database as single words
Script allows for self shortening the shortner url which is a major
issue.
How can I
Check for domain extension else fail submit
and
Check if user is trying to shorten my own link and fail as well.
My code:
function remove_http($url)
{
$disallowed = array('http://', 'https://', 'http//', 'https//');
foreach($disallowed as $d) {
if(strpos($url, $d) === 0) {
return str_replace($d, '', $url);
}
}
return $url;
}
$url_to_shorten = get_magic_quotes_gpc() ? stripslashes(trim($_REQUEST['url'])) : trim($_REQUEST['url']);
if(!empty($url_to_shorten) || parse_url($url_to_shorten, PHP_URL_SCHEME) )
{
require('framework/core/config.xml.php');
// check if the URL has already been shortened
$already_shortened = mysql_result(mysql_query('SELECT id FROM ' . DB_TABLE. ' WHERE long_url="' . mysql_real_escape_string(remove_http($url_to_shorten)) . '"'), 0);
if(!empty($already_shortened))
{
// URL has already been shortened
$shortened_url = getShortenedURLFromID($already_shortened);
}
else
{
// URL not in database, insert
mysql_query('LOCK TABLES ' . DB_TABLE . ' WRITE;');
mysql_query('INSERT INTO ' . DB_TABLE . ' (long_url, created, creator) VALUES ("' . mysql_real_escape_string(remove_http($url_to_shorten)) . '", "' . time() . '", "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '")');
$shortened_url = getShortenedURLFromID(mysql_insert_id());
mysql_query('UNLOCK TABLES');
}
echo BASE_HREF . $shortened_url;
}
function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
{
$length = strlen($base);
while($integer > $length - 1)
{
$out = $base[fmod($integer, $length)] . $out;
$integer = floor( $integer / $length );
}
return $base[$integer] . $out;
}

Categories