I have edited some code I found on 'ye old internet (http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls/). I have not gotten my variation of the code to work properly. My edited versions requests another input called "pages" from index.php. Pages is put into the database along with $url and $short. Pages goes into a pages field in the database which has a varchar value. Pages is later called in serve.php for a javascript purpose. In the code below I have noted where I think the problem occurs. If your interested in my faulty code, stay tuned; I have yet to edit the other files.
I am starting to think the error could be happening in MYSQL because I almost always receive the first $html error of "Error: invalid url"
<?php
require("./db_config.php");
$url = $_REQUEST['url'];
$pages = $_REQUEST['pages'];
//this seems to be where the errors are occuring
if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $url)) {
$html = "Error: invalid URL";
} else {
$db = mysql_connect($host, $username, $password);
$short = substr(md5(time().$url), 0, 5);
if(mysql_query("INSERT INTO `".$database."`.`url_redirects` (`short`, `url`, `pages`) VALUES ('".$short."', '".$url."', '".$pages."');", $db)) {
$html = "Your short URL is<br />www.srprsr.com/".$short;
} else {
$html = "Error: cannot find database";
}
mysql_close($db);
}
?>
Consider filter_var($url, FILTER_VALIDATE_URL) instead of a regular expression.
http://php.net/filter.examples.validation
http://php.net/filter.filters.validate
Related
I have a page that connects to a MySQL database via PHP. On this page the data is fetched to load an image and its related details. This page all work OK when the page is loaded.
I also have a module included on this page where users can create a board (which will hold images) along a certain theme.
On other pages this board module works OK, but on a page where a $_GET request happens, which is needed to identify a user's username or an image filename (depending on the page), the board module doesn't work correctly. When you create a new board it fails and I get a PHP error saying Undefined variable: filename in with reference to the line of code ':filename' => $filename in the execute function below.
When this boards module is used to create a new board name I have some JavaScript fetch() code on the page that prevents a hard refresh. I'm not sure if this is causing the problem (although this JS is also used on the pages that don't have a problem, i.e. no $_GET request). On pages where this is no $_GET request everything works as expected.
Note: in the code below $connection is the database connection from a db.php file
PHP on pageload that loads the image and related data
isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");
$image_stmt = $connection->prepare("SELECT * FROM `lj_imageposts` WHERE `filename` = :filename");
$image_stmt -> execute([
':filename' => $filename // variable that returns the error
]);
$image_row = $image_stmt->fetch();
// if the GET url parameter doesn't exist/changed
if ($image_row == 0) { header ("Location: index.php"); exit; }
$db_userid = htmlspecialchars($image_row['user_id']);
$db_image_id = htmlspecialchars($image_row['image_id']);
$db_image_title = htmlspecialchars($image_row['image_title']);
$db_image_filename = htmlspecialchars($image_row['filename']);
$db_image_ext = htmlspecialchars($image_row['file_extension']);
$db_username = htmlspecialchars($image_row['username']);
?>
---- HTML OUTPUT THAT INCORPORATES THE ABOVE VARIABLES
PHP for the boards module
if (isset($_POST['submit-board-name'])) {
$create_board_name = $_POST['create-board-name'];
if(strlen(trim($create_board_name)) < 10) {
$error[] = "Board name must be at least 10 characters long";
}
if(strlen(trim($create_board_name)) > 150) {
$error[] = "Board name can be at less than 150 characters long";
}
if(!isset($error)) {
try {
$createBoardSQL = "INSERT INTO lj_boards (board_name, user_id) VALUES (:board_name, :user_id )";
$bstmt = $connection->prepare($createBoardSQL);
$bstmt->execute([
':board_name' => $create_board_name,
':user_id' => $db_id
]);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
} else {
// give values an empty string to avoid an error being thrown before form submission if empty
$create_board_name = "";
}
This first line is unnecessarily cryptic, making the mistake harder to spot (and harder to fix):
isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");
It's pretending to be an expression, but it's actually an if statement in disguise - it consists of nothing but side effects. Let's write it out more clearly:
if ( isset($_GET['filename']) ) {
$filename = $_GET['filename'];
}
else {
header("Location: login.php");
}
Now we can look more clearly at what each branch does:
The if branch sets a variable. If the code takes that branch, everything should be fine.
The else branch sets a header to be included when PHP sends the response. It doesn't do anything else, and it doesn't set the variable, so if this path is taken, you'll have a problem later.
What you probably intended to happen was for the else branch to set that header and then immediately stop processing. For that you need an exit; statement (also known as die;
if ( isset($_GET['filename']) ) {
$filename = $_GET['filename'];
}
else {
header("Location: login.php");
exit;
}
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 6 years ago.
I built a website locally with WAMP server, and everything worked fine, then ported over to web server on GoDaddy, and my redirect function suddenly stopped working.
Simple site at (www.minute.tech), you can test out the one form I have, goes to the form_processing.php, but should redirect back to the index page with a message. When you go back to the index page after the failed redirect, it still shows the proper message of "Booyah!...", and inputs the email into my database.
Any ideas why it won't redirect on my web server, but will on my local WAMP server with the same code? Cheers!
Here's my redirect function in sessions.php:
function redirect_to($new_location) {
header("Location: " . $new_location);
exit();
}
Here's process_email.php where I redirect:
<?php require_once("sessions.php"); ?>
<?php require_once("db_connection.php"); ?>
<?php require_once("functions.php"); ?>
<?php
if(isset($_POST['submit']) && !empty($_POST['email'])){
//Process form
$email = $_POST['email'];
$email = mysql_prep($email);
$techcheck = (isset($_POST['techcheck'])) ? 1 : 0;
// 2. Perform database query
$query = "INSERT INTO signups (";
$query .= " email, techcheck";
$query .= ") VALUES (";
$query .= "'{$email}', $techcheck";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["good_message"] = "Booyah! We will keep you posted on progress.";
redirect_to("../index.php");
} else {
//Failure
$_SESSION["bad_message"] = "Failed to accept email.";
redirect_to("../index.php");
}
} else {
//This can be an accidental GET request
$_SESSION["bad_message"] = "That is not a valid email! Please try again.";
redirect_to("../index.php");
}
?>
You have to start object for header function sometimes
Add this code to all pages
<?php ob_start(); ?>
Do with JS.
<?php
function redirect_to($new_location) { ?>
<script>window.location="<?php echo $new_location; ?>";</script>
<?php } ?>
Remove all the empty spaces. Some server set-ups will be okay with output before the header redirect but the vast majority of servers will not redirect properly. Turn on error reporting and it will probably tell you have output before the redirect:
<?php
// ^---- Just do one open tag
require_once("sessions.php"); // Remove close tag, possible empty space after
require_once("db_connection.php"); // Remove close tag, possible empty space after
require_once("functions.php"); // Remove close tag, possible empty space after
// Remove the close and open php tags
if(isset($_POST['submit']) && !empty($_POST['email'])){
//Process form
$email = $_POST['email'];
$email = mysql_prep($email);
$techcheck = (isset($_POST['techcheck'])) ? 1 : 0;
// 2. Perform database query
$query = "INSERT INTO signups (";
$query .= " email, techcheck";
$query .= ") VALUES (";
$query .= "'{$email}', $techcheck";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["good_message"] = "Booyah! We will keep you posted on progress.";
redirect_to("../index.php");
} else {
//Failure
$_SESSION["bad_message"] = "Failed to accept email.";
redirect_to("../index.php");
}
} else {
//This can be an accidental GET request
$_SESSION["bad_message"] = "That is not a valid email! Please try again.";
redirect_to("../index.php");
}
// If you have no more content below this point, just remove the close php tag
// it is not required and is a possible source of empty space down the line...
Also, you should not be using mysql_ anymore, it is deprecated and removed in PHP 7. Also, bind parameters instead of doing this parameter right into the sql:
$query .= "'{$email}', $techcheck";
What's wrong with this preg_match() usage? I want to check steam lobby link and if it's matching then write to database. If not, just echo the error. I am doing this through ajax. Is it better to do this with ajax or $_SERVER["REQUEST_METHOD"] == "POST"?
<?php
require("../includes/config.php");
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^((steam?:)+(/joinlobby\/730\/)+([0-9]{17,25}\/.?)+([0-9]{17,25})/$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
else {
$rank = "Golden";
$mic = "No";
try {
$stmt=$db->prepare("INSERT INTO created_lobby (lobby_link, current_rank, have_mic) VALUES (:lobby_link, '$rank', '$mic')");
$stmt->execute(array(
':input_link' => $_POST['lobbyLink']
));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
My Problem:
When I execute this code, it will give me false.
Thank you for help.
This works:
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^(steam?:)+(//joinlobby/730/)+([0-9]{17,25}/.?)+([0-9]{17,25}$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
I changed /joinlobby to //joinlobby, and remove the / at the end. I also removed the unnecessary () around everything.
I suspect you also shouldn't have (...)+ around steam?: and //joinlobby/730/. They'll cause repeated uses of those prefixes to be accepted as correct, e.g. steam:steam:...
I have some code to get some public available data that i am fetching from a website
//Array of params
foreach($params as $par){
$html = file_get_html('WEBSITE.COM/$par');
$name = $html->find('div[class=name]');
$link = $html->find('div[class=secondName]');
foreach($link as $i => $result2)
{
$var = $name[$i]->plaintext;
echo $result2->href,"<br>";
//Insert to database
}
}
So it goes to the given website with a different parameter in the URL each time on the loop, i keep getting errors that breaks the script when a 404 comes up or a server temporarily unavailable. I have tried code to check the headers and check if the $html is an object first but i still get the errors, is there a way i can just skip the errors and leave them out and carry on with the script?
Code i have tried to checked headers
function url_exists($url){
if ((strpos($url, "http")) === false) $url = "http://" . $url;
$headers = #get_headers($url);
//print_r($headers);
if (is_array($headers)){
//Check for http error here....should add checks for other errors too...
if(strpos($headers[0], '404 Not Found'))
return false;
else
return true;
}
else
return false;
}
Code i have tried to check if object
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
// and only then start searching (and manipulating) the dom
You need to be more specific, what kind of errors are you getting? Which line errors out?
Edit: Since you did specify the errors you're getting, here's what to do:
I've noticed you're using SINGLE quotes with a string that contains variables. This won't work, use double quotes instead, i.e.:
$html = file_get_html("WEBSITE.COM/$par");
Perhaps this is the issue?
Also, you could use file_get_contents()
if (file_get_contents("WEBSITE.COM/$par") !== false) {
...
}
well i'm writing a php code to edit tags and data inside those tags but i'm having big trouble getting my head around the thing.
basically i have an xml file similar to this but bigger
<users>
<user1>
<password></password>
</user1>
</users>
and the php code i'm using to try and change the user1 tag is this
function mod_user() {
// Get global Variables
global $access_level;
// Pull the data from the form
$entered_new_username = $_POST['mod_user_new_username'];
$entered_pass = $_POST['mod_user_new_password'];
$entered_confirm_pass = $_POST['mod_user_confirm_new_password'];
$entered_new_roll = $_POST['mod_user_new_roll'];
$entered_new_access_level = $_POST['mod_user_new_access_level'];
// Grab the old username from the last page as well so we know who we are looking for
$current_username = $_POST['mod_user_old_username'];
// !!-------- First thing is first. we need to run checks to make sure that this operation can be completed ----------------!!
// Check to see if the user exist. we just use the normal phaser since we are only reading and it's much easier to make loop through
$xml = simplexml_load_file('../users/users.xml');
// read the xml file find the user to be modified
foreach ($xml->children() as $xml_user_get)
{
$xml_user = ($xml_user_get->getName());
if ($xml_user == $entered_new_username){
// Set array to send data back
//$a = array ("error"=>103, "entered_user"=>$new_user, "entered_roll"=>$new_roll, "entered_access"=>$new_access_level);
// Add to session to be sent back to other page
// $_SESSION['add_error'] = $a;
die("Username Already exist - Pass");
// header('location: ../admin.php?page=usermanage&task=adduser');
}
}
// Check the passwords and make sure they match
if ($entered_pass == $entered_confirm_pass) {
// Encrypt the new password and unset the old password variables so they don't stay in memory un-encrytped
$new_password = hash('sha512', $entered_pass);
unset ($entered_pass, $entered_confirm_pass, $_POST['mod_user_new_password'], $_POST['mod_user_confirm_pass']);
}
else {
die("passwords did not match - Pass");
}
if ($entered_new_access_level != "") {
if ($entered_new_access_level < $access_level){
die("Access level is not sufficiant to grant access - Pass");
}
}
// Now to load up the xml file and commit changes.
$doc = new DOMDocument;
$doc->formatOutput = true;
$doc->perserveWhiteSpace = false;
$doc->load('../users/users.xml');
$old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0);
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($entered_new_username, $old_user);
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
}
when run with just the username entered for change i get this error
Catchable fatal error: Argument 1 passed to DOMNode::replaceChild() must be an instance of DOMNode, string given, called in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 252 and defined in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 201
could someone explain to me how to do this or show me how they'd do it.. it might make a little sense to me to see how it's done :s
thanks
$entered_new_username is a string so you'll need to wrap it with a DOM object, via something like$doc->createElement()
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($doc->createElement($entered_new_username), $old_user);
This may not be quite right, but hopefully it points you in the correct direction.
alright got it writing and replacing the node that i want but i have ran into other issues i have to work out (IE: it's replacing the whole tree rather then just changing the node name)
anyway the code i used is
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
try {
$new_node_name = $doc->createElement($entered_new_username);
$old_user->parentNode->replaceChild($new_node_name, $old_user);
}
catch (DOMException $e) {
echo $e;
}
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
$doc->save('../users/users.xml');