Php redirct each data to each url - php

I have a database where I am storing data. Here every full link has a offer link. What I am trying to do? I want to redirect every single data to every different URL. But I failed.
Example:1
full link: http://localhost/LearnPHP/test/short2.php/redir&q=https%3A%2F%2Fgoogle.com
redirect link: google.com
Example 2
full link: http://localhost/LearnPHP/test/short2.php/redir&q=https%3A%2F%2Fyoutube.com
redirect link: youtube.com
Someone when visiting the full link it should redirect each offer link
Database
Data Insert
PHP Code

You should really post code instead of images. You can post code blocks by posting your code between 3 backticks (`) at the top, and three backticks at the bottom.
However, I tried to copy the code, and edited it. I don’t understand exactly what you are trying to do, but I just made some changes.
Data Insert
<?php
include 'db.php’;
$first = "http://localhost/LearnPHP/test/short2.php/redir&q=";
$magic = urlencode($_POST["longUrl"]);
if($magic) {
$finalUrl = $first . $magic;
$stmt = $conn->prepare("INSERT INTO url (offer_link, full_link) VALUES (?, ?)");
$stmt->bind_param("ss", $magic, $finalUrl);
$stmt->execute();
} else {
$finalUrl = '';
}
?>
In the above code, you can obviously tell I changed some things. First, I don’t have a checking statement inside the insert file. I have put it directly inside of the db.php file. I will post the code for it.
Next, I patched the vulnerability of mySQL injection (https://portswigger.net/web-security/sql-injection) using prepared statements.
db.php
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
For the last bit, can you please tell me exactly what you need to do? Your post isn’t that helpful. Do you want to use $_GET[‘’] for the redirection? Please edit your code. Read this as well: https://stackoverflow.com/help/how-to-ask

For redirection part you can do something like this:
if(isset($_GET['q'])) // if q param available
{
$redirectUrl = urldecode($_GET['q']); // get link
header("Location: $redirectUrl"); // redirect
}
I think that your problem is related to URL decode / encode: LINK

Related

MySQL PHP Column Update Query

i would really appreciate if anyone can help me out with this mysql php problem of which i have no idea how to do it.
I Have a column named = 'x'
The text of that column 'x' is = "yz,zz,zy"
I want to edit the value of the column 'x' to = "yz,zyz,zy".
Now how do i add that 'y' in the middle term between yz and zy using CONCAT.
Regards.
You haven't provided any code or an attempt for us to go off of something so I'll give you a brief way of doing it. Look up PDO here This is a really easy to follow and secure way to manipulate data in your database using php. Again as you haven't given me much to go off i'm unsure if you want to just set something at specific count of characters along OR if you want to just update the entire thing, SO i'll help you with the latter as it will help give you some base understanding.
Please read into PDO further as this is just an example further down the line and will not run if you just blindly copy and paste it in.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE table SET x='yz,zyz,zy' WHERE id= 1"; // No clue if you've even given anything IDs
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As you haven't really provided any Schema of the table you are updating this is the best I could provide based off of what you have given me.. try to include as much information as possible as I'm unsure if this is what you even want

How to read variables using PHP from a python file?

Trying to figure out the best way to do this and I'm getting very odd results. Long story short, we put application config parameters in the backend which is python, the front end PHP used hardcoded parameters and I'm trying to tie that back to the single python file so I don't have to change important config parameters in multiple places, for example to deploy to a different server.
The python file (defaults.py):
import time
#------------------------------------------------------
#Processing Options
#------------------------------------------------------
perform_tests = False
today = time.time()
#------------------------------------------------------
#MySQL Config
#------------------------------------------------------
host = "somehostname.com"
port = 3526
user = "someuser"
pw = "somepass"
db = "someDB"
bulk = 500
table = "Some_table"
The PHP code trying to gather the config variables from it (testing code mostly):
<?php
function db_connect() {
$config_file = fopen("../modules/defaults.py", "r");
if ($config_file) {
while (($line = fgets($config_file)) !== false) {
echo "<script>alert(". (string)$line. ");</script>";
// process the line read.
if(substr($line, 0, 4) === "host"){
//$servername = trim(explode("=",$line)[1]);
$servername = "somehostname.com";
}
}
fclose($handle);
}
echo "<script>alert(". $servername. ");</script>";
//$servername = "somehostname.com";
$username = "someuser";
$password = "somepass";
$dbname = "someDB";
$port = 3526;
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
?>
As you can see, I'm looping thru the python file trying to reassign my hardcoded variables with the variables from the file... there is a good bit of debugging code in there.
So at the moment when you run it it will alert back to you each line from the file... the VERY odd result is that its not alerting the full line (it's alerting "somehostname.com", 3526, "someuser", etc... it's also not alerting the import time line or the commented out lines. This is very odd to me, I expected it to read the lines as strings but fgets appears to me interpreting the code in a very strange way.
I'd like to know what's really happening here and if there is a better way to go about this... without modifying the python file, because the backend uses it everywhere.
Thanks.
This looks much like java .properties file. Despite the fact there is some method invoked in line:
today = time.time()
But you can read those properties as string, you can find some help in this question regarding to reading properties files: Read .properties files using PHP
Once you have all data loaded you would have to evaluate lines with code - hopefully you would recognize them by keys. I know this is only general idea, but I hope you can proceed further on your own.

Prepared statements using MySQL not inserting POST values to database table

I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}

mySQL - Can't delete table row with PHP (not showing an error)

I've spent today going through tons of similar questions and trying to figure out what is wrong with my code, lots of issues people had with back ticks, quotes, etc but none seem to help or change my cause. My code is no producing any errors, but when I use echo to print out my query results, it seems that the id is not getting a value.
In my delete.php:
<?
ini_set('display_errors',"1");
$username="xxx";
$password="xxx";
$database="xxx";
$conn = new mysqli(localhost, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = (int)$_GET['number'];
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id."");
$conn->close();
?>
And the delete button in my main.php (the rest of the php is correctly displaying my table with data):
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
Can someone help pick out what is causing my rows not to delete when I hit the delete button that I have created, or maybe something that more clearly can help me debug? (I don't want to use checkboxes for this).
EDIT:
I also tried this code (while defining the function as $sql and I'm getting a "Success" message:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
EDIT 2:
I changed the structure following the advice that I should use POST, thinking I might have caught something I didn't notice before, but still not working.
echo "<td><form method='post' action='delete.php'>
<input type='hidden' name='row_id' value=".$row['id']." />
<input type='submit' name='delete_row' />
</form>";
-
if(isset($_POST['delete_row'])) {
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");
$stmt->bind_param('i', $_REQUEST['row_id']);
$stmt->execute();
}
If I do it the above way, nothing happens. Also tried this way, and get a syntax error:
if(isset($_POST['delete_row'])) {
$id = $_POST['row_id'];
$sql = "DELETE FROM tourdates WHERE id=".$id;
mysqli_query($conn,$sql);
}
A potential problem that I can see, is that you are not quoting localhost so php will look for a constant called localhost:
$conn = new mysqli('localhost', $username, $password, $database);
^ ^ here
You are also not checking for errors so that is why you don't see any. The easiest way to fix that, is to have mysqli throw exceptions. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
I also don't know if you can mix procedural and object oriented mysqli like that. You should probably stick to the OOP version.
Apart from that you should not use a link (GET request) for your delete actions. What if a web-crawler or a browser extension tries to fetch the links? Instead you should use a POST request (like a form with a button).
Edit: There is another problem which causes you not to get your ID and as you cast it to int, you will always get 0:
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
^ Oooops, closing the href attribute value here...
Your id gets placed after the value / outside of the quote of the href value. You can easily verify this if you look at the source of your page.
You need:
<td><a href='delete.php?number=".$row['id']."'>Delete</a></td>
Replace these two parts of code in your php file, first write your host in the quotations
$conn = new mysqli('localhost', $username, $password, $database);
in your where condition you wrote id=".$id."" replace it with id=".$id
write it as:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id);
Edited:
If you want to see error in your query then use the below code:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id) or die(mysqli_error($conn));
why not use try and catch to see your error?
anyways try this
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");<br>
$stmt->bind_param('i', $_REQUEST['number']);<br>
$stmt->execute();
could this be the problem ?
$id = (int)$_GET['number'];
May be this would be better... ?
$id = intval($_GET['number']);
Anyway if, echo($query) print an empty id, this is probably because your parameter is not an integer.

Track Links Clicked On My Website Using HTML and PHP

I have a website that I would like to record on links clicked on each page. As an example, below is the code for my index.html page in which I attempt to record a link:
ADA
Where "trackIndexPageLinks.php" is the name of my php file and "?token=1" is the php variable and value that I would like to record in my server.
Listed below is the php code that I use to store the value and pass it to my server:
<?php
$db_hostname = '???.?.?.?';
$db_database = 'mySiteDB';
$db_username = 'something';
$db_password = '';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die("Unable to connect to MySQL:".mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: ".mysql_error());
echo #mysql_ping() ? 'true':'false';
$token = $_GET['token'];
//Create insert statement - inserts data into the database.
$sql = "INSERT INTO clickLog (linkClicked)
VALUES ('$token')";
//Error check to ensure SQL statement took.
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Close connection.
mysql_close();
?>
However, I get no recorded records. Any assistance on this would be greatly appreciated.
You're much better off to sign up with google analytics and add snippets of javascript code they provide. They can give you complete detail as to who is linking to what on your page as well as what links they click as well as the order they click them in.
Go to: http://www.google.com/analytics/
All you need is a google account and if you don't have one, you can sign up for one. The whole thing is free.

Categories