Our client have below link added in their site (given by us) which call our test.php file to use it as library and we return some script as well as we store some data.
Script tag is as per below on client's side,
<script src='https://example.com/test.php?id=194&referer='WHAT SHOULD I Write Here'></script>
test.php is as per below on our server,
<?php
$id = $_GET['id'];
$clientsrefferer = $_GET['referer'];
$ip = $_SERVER['REMOTE_ADDR'];
//below referer becomes address of client's webpage visited by their customer
$visitedwebpage = $_SERVER['HTTP_REFERER'];
try{
$dbh = new PDO("mysql:host=XXXXXX;dbname=XXXXXX", "XXXXXX", 'XXXXX');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = "insert into table (ID,IP,Referer,Page) values(?, ?, ?, ?)";
$sth = $dbh->prepare($query);
$sth->execute(array($id, $ip, $clientsrefferer, $visitedwebpage));
echo "document.write('Returning some script')";
}
catch(PDOException $e) {echo $e->getMessage();}
?>
We want to check if client's website is searched and visited using any search engine referer. To get it from javascript,
document.referrer
can be use.
But I want to attach document.refferer value to the tag only which we gave it to our client. Is it possible?
Is there any other way to do that?
If question is not clear, let me know so I can try to do more clarifications.
You can retrieve the referrer detail and dynamically add the script tag on client side. Like below
<script type='text/javascript'>
var my_script = document.createElement('script');
my_script.setAttribute('src','https://example.com/test.php?id=194&referer=' + document.referrer);
document.head.appendChild(my_script);
</script>
Related
Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)
Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.
I have such a request: I have to do JS script, that works with PHP script.
Right now i have such a PHP code:
~~~~~~ PHP ~~~~~~
<?php
$email = filter_input(INPUT_POST, 'email');
if (!empty($email)){
$host = "localhost";
$dbusername ="root";
$dbpassword ="";
$dbname = "email";
$conn = new mysqli ($host,$dbusername, $dbpassword , $dbname);
if (mysqli_connect_error()){
die('Connection problem('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else{
$sql = "INSERT INTO `email` (`email_id`, `email`) VALUES (NULL, '$email');";
if ($conn->query($sql)){
echo "<script type='text/javascript'>alert(\"Email has been written to subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
else{
echo "<script type='text/javascript'>alert(\"Your email is already in our subscribe list!\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
$conn->close();
}}else{
echo "<script type='text/javascript'>alert(\"Don't forget to include your email address !\");</script>";
echo '<script type="text/javascript">
window.location = "index.html"
</script>';
}
?>
And here is a challenge. Instead of currently js scripts in php (that they activate on clean page without any content) JS script has to work on page, without reload - on the same page, when the request was sent from. I don't know how to do that ( i'm quite new to JS ) and i hope for your hints
Thanks for advices
If you don't want to reload the rendered page, you will have to work the other way around: not PHP is generating the whole page, but a JS script is pulling information from a PHP script and uses this information to display the according note.
There are multiple ways to fetch information from a server using JavaScript, the most prominent being AJAX to load HTML chunks or JSON responses. Please search for those topics as this is a relatively broad topic and your question is much too broad as it is.
I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.
I will try to explain:
I have a domain - example.com without any other pages.
I want to be able create a redirect from non existing link, example.com/whatever to nba.com, how can I do it, without creating a example.com/whatever page?
I want to have a website without pages, only domain, that will work for me as a redirect center, i mean - I want have 100 random links from example.com/****** that the 1st link will redirect to website1 , 2nd to website2.com and etc.
I understand that I must have a Database, with at least 1 table, with 2 rows, in 1st row - random links from example.com/*** in 2nd row - links to redirected websites. But how to make a redirect, if pages do not exist ?
Using php or another technique ? Please help.
It can be achieved by .htaccess and a php file:
.htaccess:
ErrorDocument 404 /404.php
404.php:
<?php
if ($_SERVER["HTTP_HOST"] == "example.com") // current domain
header('Location: http://nba.com/', TRUE, 301);
?>
See this answer: https://stackoverflow.com/a/18764078/5692251
You will need .htaccess for this. Find the root directory of your hosting account where the domain is (usually public_html) and create a .htaccess file with the following in it:
ErrorDocument 404 /index.php
Now create an index.php file in your root directory with something like this:
<?php
$websites = array( 'http://www.websiteone.com', 'http://www.websitetwo.com' );
$random_website = array_rand( $websites );
header( "Location: {$random_website}", TRUE, 301 );
?>
You can keep adding elements to the $website array variable. This example assumes your server is setup and can use PHP to run the code.
If you are going to configure a database to retrieve the value:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM websites ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
$website = mysql_fetch_object($result);
$random_website = $website->website;
$conn->close();
header( "Location: {$random_website}", TRUE, 301 );
?>
This code assumes your table in the database is called websites that has a field called website where the URL is stored.
I'm new with questions and generally with "Stack Overflow", so forgive me if it is not formatted well.
So, I have problem with transferring some informations from one page to another. It is a value of <a> tag from an php while loop.
At the moment I have something like this:
$query = mysql_query("SELECT DISTINCT `a`.`id`,`o`.`first_name` , `o`.`last_name` , `a`.`name` FROM `owner` AS `o` , `animal` AS `a` WHERE `o`.`id` = `a`.`fk_current_owner` AND `o`.`fk_user` = '".$_SESSION['user_id']."'");
while($row = mysql_fetch_assoc($query)){
$pet_id = $row['id'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$pet_name = $row['name'];
echo 'Owner: <strong>'.$first_name.' '.$last_name.'</strong> ';
echo 'Pet: <strong>'.$pet_name.'</strong><br>';
}
So you can assume that this will display names of pets that logged user got.
So I linked their names and I need to get ID of selected name on another page so I can display details of pet on page viewPet.php.
You can also send the pet id along as a GET parameter with the link.
echo ''.$pet_name.'';
On the viewPet.php page you'd access it by $_GET['id']
you can put the link in a cookie:
setcookie(name, value, expire, path, domain);
that is the code to set the cookie and then to receive the cookie you can do $_COOKIE['name'];
or you can do a session.
session_start();
$_SESSION['name']=value;