I'm working on a script that checks if the url already exists in the database, and if yes adds an additional -1 or -2 etc etc at the end. I found this script
But it 'd need to to check it again after adding-1. Since it may be already existing. How can I do that? I tired i this way
$query = mysql_query("SELECT * FROM posts WHERE url='$url'");
while ( $query ) {
$result = mysql_fetch_assoc($query);
$url = $result['url'];
$urlnew = $result['url'];
$oldurl = $url;
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
$url = preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $url.$separator.$first;
$first++;
}
$url = $urlnew;
}
The new code above works just fine. But it checks only once. How can I make it to check untill it dose not exists in the DB?
tried adding a new sql query at the bottom after $url -$urlnew but it only breaks the function.
EDIT
Here's the correct script :D
$query = mysql_query("SELECT * FROM posts WHERE url LIKE '%".$url."%'");
if ( $query ) {
while ( $result = mysql_fetch_assoc($query) ) {
$url = $result['url'];
$urlnew = $result['url'];
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$url.$separator.$first;
$first++;
}
}
}
$url = $urlnew;
Your code is likely vulnerable to SQL Injection. You should consider using PDO or MySQLi instead.
Here's an example of how you could do so:
$url = 'www.example.com';
$i = 0;
$max_duplicates = 100;
$query = $pdo->prepare('SELECT COUNT(id) count FROM urls WHERE url=?');
while ($i++ < $max_duplicates) {
$result = $query->execute($url);
if (!$result->fetch(PDO::FETCH_OBJ)->count)
break;
if ($i == 1) {
$url = $url . '-1';
} else {
$n = $i > 10 ? 2 : 1;
$url = substr($url, -$n) . $i;
}
}
Here's what I used for my needs
function checkLink($link, $counter=1){
global $connect;
$newLink = $link;
do{
$checkLink = mysqli_query($connect, "SELECT id FROM table WHERE link = '$newLink'");
if(mysqli_num_rows($checkLink) > 0){
$newLink = $link.'-'.$counter;
$counter++;
} else {
break;
}
} while(1);
return $newLink;
}
$link = 'www.example.com';
$uniquelink = checkLink($link);
Related
In my wordpress functions file, I'm getting sql query results of only post IDs, then taking those IDs to create an array that I send to my page.
This works perfectly but I want to re-order it based on one of the values I generate in the array process. I have a value of 'featured' and I want to make it so that any results where featured = 1 are first in the array.
$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt = 0;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$ress[$cnt]['featured'] = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$cnt]['imgs'] = $imgpath;
}else{
$ress[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$cnt++;
}
}
echo json_encode($ress);
}
Is there a way to simply use conditions in order to put those values first in the array?
Using a function get_post_meta in an array is bad practice. I would advise first querying the database to extract data from custom fields.
However, I think there are two ways to answer your question:
Use 2 arrays and merge them together after iteration:
$myresults = $wpdb->get_results( $sqlStatement );
$ress1 = $ress2 = array();
$cnt = 0;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$array_name = !empty($is_featured) ? 'ress1' : 'ress2';
$$array_name[$cnt]['featured'] = $is_featured;
if($imgpath){
$$array_name[$cnt]['imgs'] = $imgpath;
}else{
$$array_name[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$cnt++;
}
}
$ress = array_merge($ress1, $ress2);
echo json_encode($ress);
}
Use 2 counters:
$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt1 = 0;
$cnt2 = 1000000;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$counter_name = !empty($is_featured) ? 'cnt1' : 'cnt2';
$ress[$$counter_name]['featured'] = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$$counter_name]['imgs'] = $imgpath;
}else{
$ress[$$counter_name]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$$counter_name++;
}
}
$ress = array_values( $ress );
echo json_encode($ress);
}
I have a basic URL shortener script but I am having an issue. Each time I enter a new url to shorten the script just adds the next letter to the database (i.e. http://www.both.com/a then http://www.both.com/b then http://www.both.com/c etc). The problem is I don't want to people to be able to view those links by simply going in sequential order. How can I make it so each new url has a random 6 digit alpha and numerical name created? Also, I wanted to make the alpha both random upper and lower case.
<?php
require 'config.php';
header('Content-Type: text/plain;charset=UTF-8');
$url = isset($_GET['url']) ? urldecode(trim($_GET['url'])) : '';
if (in_array($url, array('', 'about:blank', 'undefined', 'http://localhost/'))) {
die('Enter a URL.');
}
if (strpos($url, SHORT_URL) === 0) {
die($url);
}
function nextLetter(&$str) {
$str = ('z' == $str ? 'a' : ++$str);
}
function getNextShortURL($s) {
$a = str_split($s);
$c = count($a);
if (preg_match('/^z*$/', $s)) { // string consists entirely of `z`
return str_repeat('a', $c + 1);
}
while ('z' == $a[--$c]) {
nextLetter($a[$c]);
}
nextLetter($a[$c]);
return implode($a);
}
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$db->set_charset('utf8mb4');
$url = $db->real_escape_string($url);
$result = $db->query('SELECT slug FROM redirect WHERE url = "' . $url . '" LIMIT 1');
if ($result && $result->num_rows > 0) { // If there’s already a short URL for this URL
die(SHORT_URL . $result->fetch_object()->slug);
} else {
$result = $db->query('SELECT slug, url FROM redirect ORDER BY date DESC, slug DESC LIMIT 1');
if ($result && $result->num_rows > 0) {
$slug = getNextShortURL($result->fetch_object()->slug);
if ($db->query('INSERT INTO redirect (slug, url, date, hits) VALUES ("' . $slug . '", "' . $url . '", NOW(), 0)')) {
header('HTTP/1.1 201 Created');
echo SHORT_URL . $slug;
$db->query('OPTIMIZE TABLE `redirect`');
}
}
}
?>
try something like this :
function generateString($length) {
$alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$alphabetLength = strlen($alphabet);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $alphabet[rand(0, $alphabetLength - 1)];
}
return $randomString;
}
$short = generateRandomString(6);
I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!
I am receiving the following error message "Header may not contain more than a single header, new line detected" I know it says that a new line has been detected, but I cannot figure where this line is coming from. I have tried to trim the variables..I have re-written the header line in different ways, without any result. I added the getallheaders function to see what was being passed, but I see no new line or any extra characters in the output $headers. Even using ob_start() does not help.
<?php
ob_start();
include "catalog.obj";
session_start();
$catalogObj = $_SESSION['catalogObj'];
if (isset($_POST['st']))
$st = $_POST['st'];
else
$st = '0';
if (isset($_POST['num']))
$num = $_POST['num'];
else
$num = '0';
if (isset($_POST['type']))
$type = $_POST['type'];
else
$type = '0';
if (isset($_POST['rec']))
$rec = $_POST['rec'];
else
$rec = '0';
if (isset($_POST['option']))
$option = $_POST['option'];
else
$option = '0';
if(strcmp($_POST['submit'],"Reset Form") == 0)
{
header("location: search_catalog.php?type=$type&firstTime=1");
exit;
}
elseif(strcmp($_POST['submit'],"Catalog Administration") == 0)
{
Header("Location: administration.php");
exit;
}
else
{
$inventory_id_num = $_POST['inventory_id_num'];
$inventory_desc = $_POST['inventory_desc'];
$inventory_revision = $_POST['inventory_revision'];
$quantity = $_POST['quantity'];
$catalog_status_id = $_POST['catalog_status_id'];
$order_form_type_id = $_POST['order_form_type_id'];
$catalogObj->inventory_id_num = $inventory_id_num;
$catalogObj->inventory_desc = $inventory_desc;
$catalogObj->inventory_revision = $inventory_revision;
$catalogObj->quantity = $quantity;
$catalogObj->catalog_status_id = $catalog_status_id;
//$catalogObj->order_form_type_id = array();
$catalogObj->order_form_type_id = $order_form_type_id;
$count=count($order_form_type_id);
for ($i=0; $i<$count; $i++)
{
//print "order_form_type_id: $order_form_type_id[$i]<br>";
if(strlen($order_form_type_id[$i]) > 0)
{
$catalogObj->order_form_type_id[$i] = $order_form_type_id[$i];
}
}
if(strcmp($_POST['submit'],"Back to Order Form") == 0)
{
Header("Location: order_form.php?num=$num");
exit;
}
else
{
//$url = "type=".$type."option=".$option."rec=".$rec."st=".$st."num=".$num;
Header("location: search_catalog_handler.php?type=$type&option=$option&rec=$rec&st=$st&num=$num");
//Header("location: search_catalog_handler.php?" . rawurlencode($url));
if (function_exists('getallheaders'))
{
$headers = getallheaders();
print_r( $headers);
}
exit;
}
}
function getallheaders()
{
$headers = '';
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == 'HTTP_')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
?>
First, thanks for the pointers! The problem in the above code was with the $st variable. I am not very experienced with headers and rewriting them but I had add the following conditinal statement:
if (!empty($_POST['st']))
{
$st = $_POST['st'];
$num = $_POST['num'];
$type = $_POST['type'];
$rec = $_POST['rec'];
$option = $_POST['option'];
}
To the beginning of my code, so it the complete code is:
<?php
ob_start();
/*************************************
altered complete 12/20/2013
rjm
*************************************/
include "catalog.obj";
session_start();
$catalogObj = $_SESSION['catalogObj'];
if (!empty($_POST['st']))
{
$st = $_POST['st'];
$num = $_POST['num'];
$type = $_POST['type'];
$rec = $_POST['rec'];
$option = $_POST['option'];
}
if(strcmp($_POST['submit'],"Reset Form") == 0)
{
header("location: search_catalog.php?type=$type&firstTime=1");
exit;
}
elseif(strcmp($_POST['submit'],"Catalog Administration") == 0)
{
Header("Location: administration.php");
exit;
}
else
{
echo "<pre>";
print_r($_POST);
echo "</pre>";
//exit;
$inventory_id_num = $_POST['inventory_id_num'];
$inventory_desc = $_POST['inventory_desc'];
$inventory_revision = $_POST['inventory_revision'];
$quantity = $_POST['quantity'];
$catalog_status_id = $_POST['catalog_status_id'];
$order_form_type_id = $_POST['order_form_type_id'];
$catalogObj->inventory_id_num = $inventory_id_num;
$catalogObj->inventory_desc = $inventory_desc;
$catalogObj->inventory_revision = $inventory_revision;
$catalogObj->quantity = $quantity;
$catalogObj->catalog_status_id = $catalog_status_id;
$catalogObj->order_form_type_id = $order_form_type_id;
$count=count($order_form_type_id);
for ($i=0; $i<$count; $i++)
{
if(strlen($order_form_type_id[$i]) > 0)
{
$catalogObj->order_form_type_id[$i] = $order_form_type_id[$i];
}
}
if(strcmp($_POST['submit'],"Back to Order Form") == 0)
{
Header("Location: order_form.php?num=$num");
exit;
}
else
{
Header("location: search_catalog_handler.php?type=$type&option=$option&rec=$rec&st=$st&num=$num");
exit;
}
}
?>
This allows for a specific type search (with parameters) and a general type search (no parameters) from the sending page.
Assuming that catalog.obj does not output any information to the browser (which would result in an error as well), your $type variable looks like the culprit since it's the only wildcard.
Note that you'll need to do the following for all POSTed variables in your script that you want to use in a URI:
Sine it's possible that $type could be anything (it's using the POSTed variable sometimes), you should clean it up before spitting it back out in your header:
$type = urlencode($type); // Prepares the variable to be inserted in the URI
header("Location: search_catalog.php?type=$type&firstTime=1");
I am trying to insert last 2 chararcters of Url into my database.When i insert everytime it takes some number like "2147483647".How to insert the correct last 2 chararcters of Url.
'$array = json_decode(stripslashes($_POST['data']));
for($i = 0, $l = sizeof($array); $i < $l; $i++){
$obj = $array[$i];
if($obj->{'leaf'} == true){
$leaf = 1;
} else{
$leaf = 0;
}
if($obj->{'parentId'} == null){
$parentID = 'null';
} else{
$parentID = $obj->{'parentId'};
}
if($obj->{'Duration'}==''){
$duration = 0;
} else{
$duration = $obj->{'Duration'};
}
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$gantt_id = substr(strrchr($url, '='), 1);
/*if($obj->{'gantt_id'}==null){
$gantt_id = 0;
} else{
$gantt_id = $obj->{'gantt_id'};
}
*/
$q = 'INSERT INTO j_gantt_tasks SET Name = "'.$obj->{'Name'}.'", StartDate = "'.$obj->{'StartDate'}.'", EndDate = "'.$obj->{'EndDate'}.'",
Duration = "'.$obj->{'Duration'}.'", DurationUnit = "'.$obj->{'DurationUnit'}.'", PercentDone = "'.$obj->{'PercentDone'}.'", Cls = "'.$obj->{'Cls'}.'", gantt_id="'.$gantt_id.'",
parentId = "'.$obj->{'parentId'}.'"';
$r = mysql_query($q);
if(!$r){
echo db_error($q);
}
$obj->{'id'} = mysql_insert_id();
}
echo json_encode($array);'
give a try to substring
$url = (!empty($_SERVER['HTTPS'])) ?
"https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
"http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$last2 = substring($url,-2);