Allow unique $_GET request only? Generate, verify, forbid values [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Hello everyone again here,
I want to create a PHP script for my software which generates and returns the specific code using one $_GET request with a string and using another verificates this code, then forbid running same string.
Something what should work like this:
1st user's software runs "http://example.com/codes.php?create=" and string like "abc".
and script returns code based on "abc", e.g. "4aO45k", "12sdF4" etc.
2nd user's software runs "http://example.com/codes.php?verify=" and this code.
If this code exists, return true and remove it FOREVER, meaning this code will never be generated again. If this code doesn't exist, return false.
If 1st user's software will run "http://example.com/codes.php?create=abc" another code will be generated.
In simple words:
if $_GET is create, then
generate random alphanumeric string, save it and return
if $_GET is verify, then
check if this string exists, if so, then
return true, remove from saved
otherwise
return false
Possible without databases, SQL, mySQL, FireBird...?
How do I make it using .ini files as storage?
Thanks.

It's possible with files. You can do something like the simple solution below:
A couple of notes:
I don't know what you intend by based on exactly, so this just uses the input as a prefix
This stores every code in a file indefinitely; if used a lot this file will grow very large and checking for the existence of codes, and ensuring new codes are unique can grow very slow
The same code can be verified multiple times, but will never be recreated. Marking them as used after verification is of course possible as well
As a general rule don't go creating global functions and shoving everything in one file like this. It's really just proof of concept of what was asked
<?php
$file = fopen('codes', 'a');
if (!empty($_GET['create'])) {
$seed = $_GET['create'];
do {
$code = uniqid($seed);
} while (codeExists($code));
fwrite($file, $code . "\n");
echo $code;
}
else if (!empty($_GET['verify'])) {
echo codeExists($_GET['verify']) ? 'found' : 'not found';
}
function codeExists($verification) {
$file = fopen('codes', 'r');
$found = false;
while ($code = trim(fgets($file))) {
if ($code == $verification) {
$found = true;
break;
}
}
return $found;
}

Related

Recursion with array's PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a function (listarUrls ()) that returns / scans all the urls it finds on a web page.
I need that for each of the urls that the function returns to me, I return to the list / scan all the urls of that page
many times as requested by the user, that is
.If the user asks for 1 iteration of the url www.a.com, bring back:
-$arry[0] www.1.com
-$arry[1] www.2.com
-..... So with all the urls you find in www.a.com
.If the user asks for 2 iteration of the url www.a.com, bring back:
-$arry[0] www.1.com
-$arry[0][0] www.1-1.com
-$arry[0][1] www.1-2.com
-...So with all the urls you find in www.1.com
-$arry[1] www.2.com
-$arry[1][0] www.2-1.com
-$arry[1][1] www.2-2.com
-...So with all the urls you find in www.2.com
-...
.If the user asks for 3 iteration of the url www.a.com, bring back:
-$arry[0] www.1.com
-$arry[0][0] www.1-1.com
-$arry[0][0][0] www.1-1-1.com
-$arry[0][0][1] www.1-1-2.com
-...So with all the urls you find in www.1-1.com
-$arry[0][1] www.1-2.com
-$arry[0][1][0] www.1-2-1.com
-$arry[0][1][1] www.1-2-2.com
-...So with all the urls you find in www.1-2.com
-$arry[1] www.2.com
-$arry[1][0] www.2-1.com
-$arry[1][0][0] www.2-1-1.com
-$arry[1][0][1] www.2-1-2.com
-...So with all the urls you find in www.2-1.com
-$arry[1][1] www.2-2.com
-$arry[1][1][0] www.2-2-1.com
-$arry[1][1][1] www.2-2-2.com
-...So with all the urls you find in www.2-2.com
-...
Could someone shed some light on the subject please?
This is web scraping with the option to instruct how much deep to investigate.
We can have a function definition like below:
function scrapeURLs($url,$steps,&$visited_urls = []);
Here, $url is the current URL we are scraping. $steps is which step we are investigating. If $steps == 1 at any point in our recursive function, we stop scraping further. $visited_urls is to make sure we aren't visiting same URL twice for scraping.
Snippet:
<?php
ini_set('max_execution_time','500');
libxml_use_internal_errors(true); // not recommended but fine for debugging. Make sure HTML of the URL follows DOMDocument requirements
function scrapeURLs($url,$steps,&$visited_urls = []){
$result = [];
if(preg_match('/^http(s)?:\/\/.+/',$url) === 0){ // if not a proper URL, we stop here, but will have to double check if it's a relative URL and do some modifications to current script
return $result;
}
$dom = new DOMDocument();
$dom->loadHTMLFile($url);
// get all script tags
foreach($dom->getElementsByTagName('script') as $script_tag){
$script_url = $script_tag->getAttribute('src');
if(!isset($visited_urls[$script_url])){
$visited_urls[$script_url] = true;
$result[$script_url] = $steps === 1 ? [] : scrapeURLs($script_url,$steps - 1,$visited_urls); // stop or recurse further
}
}
// get all anchor tags
foreach($dom->getElementsByTagName('a') as $anchor_tag){
$anchor_url = $anchor_tag->getAttribute('href');
if(!isset($visited_urls[$anchor_url])){
$visited_urls[$anchor_url] = true;
$result[$anchor_url] = $steps === 1 ? [] : scrapeURLs($anchor_url,$steps - 1,$visited_urls);
// stop or recurse further
}
}
/* Likewise, you can capture several other URLs like CSS stylesheets, image URLs etc*/
return $result;
}
print_r(scrapeURLs('http://yoursite.com/',2));
array_walk_recursive — Apply a user function recursively to every member of an array
https://www.php.net/manual/en/function.array-walk-recursive.php

validate a localhost:xxxx link in php laravel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i have the method:
public function getAppLink($app_path)
{
if( ! $this->isAppExists($app_path)) { return false; }
$content = $this->getContent();
// make sure that the link is available
$validate_link = \Validator::make(
['app_link' => $content->apps->$app_path->link],
['app_link' => 'active_url']
);
if($validate_link->fails())
{
$this->setAppStatus($app_path, 'stopped');
$this->setAppLink($app_path, 'invalid_link');
return '';
}
else {
$this->setAppStatus($app_path, 'started');
return $content->apps->$app_path->link;
}
}
i need to validate that localhost:xxxx link is active and can be accessed via the browser, before returning it.
somehow the laravel way of testing link is not working, am i doing this wrong, or i need to use a different approach?
note: xxxx is the port number
The Laravel active_url Validator is just a wrapper around the PHP checkdnsrr function. The purpose of this function is solely to check for DNS records, not to actually check if the server is responding.
Because you are on localhost, there are no DNS records so this check would not work.
If you want to check that a link can be accessed by the browser, you have to do that in JavaScript on the browser. Otherwise, you could have a case where http://localhost:1234 is accessible from the server but is not accessible from the browser because of the firewall or because the webserver is only listening on 127.0.0.1 and not on all IP addresses. While this will obviously work properly as long as you are doing all of your development on your local computer, it may cause you problems in production (depending, of course, on exactly what it is that you need this information for).
If you actually want to check whether the site is up, just do a CURL GET (or HEAD) request to the URL.
An easy way to use CURL in Laravel is with this composer package. The full documentation is too long to put here, but you can find it here.
i solved this problem by using fsockopen:
// ==================================================== isLinkValid()
//
// $link : the link you want to validate, ex: localhost:1234
//
// return true | false
//
private function isLinkValid($link)
{
if(strpos($link, ":") === false)
{
return false;
}
$arr_link = explode(":", $link);
$host = $arr_link[0];
$port = $arr_link[1];
$sock_open = #fsockopen($host, $port);
if(is_resource($sock_open))
{
fclose($sock_open);
return true;
}
return false;
}

PHP hand variable to another php document [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to get a variable which I declared in one php file to another without including the whole first php
while($row = mysql_fetch_assoc($sql)) {
// Urlaubstage ausgeben
if($row['frtutage'] < 1) {
$verbraucht = "0";
} else {
$verbraucht = $row['frtutage'];
}
$resturlaub = $row['miturlaubstage'] + $row['mitutagevorjahr'] - $verbraucht;
$urlaubgesamt = $row['miturlaubstage'] + $row['mitutagevorjahr'];
I need the variable $resturlaub in the second PHP without calculating the variable again.
How do I do this? Or is it even possible?
Thanks.
edit: the first php file is about calculating vacation days and how much I have remaind after taking a few vacation days, in the second file I need the calculation of the remaining days then, so I just want to use the variable again and not calculate it again
You can try somehting like
$var = 'random_query';
$page= 'yourpage.com/?my_var='.serialize($var);
header("Location: $page");
exit;
and in your page you can get the value by
if (isset($_GET['my_var']))
{
$my_var = unserialize($_GET['my_var']);
}
But it would depend on the size of that variable that you need to pass, and what is the purpose of the scripts.
If you don't want to include the whole first php file but only a variable then you should create a third file (called: variables.php or config.php for example).
Then include variables.php in both file so the variable will be shared among your scripts

Is it safe to pass filename in GET? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am doing
index.php?letter=1&show=cat.jpg
File I do not include, but use it only as <img src="$_GET['show']">
Is it safe?
Simple code to validate the input.
// Check File Param provided
$filename = (isset($_GET['show']) ? $_GET['show'] : '');
if (strlen($filename) == 0) {
die('File Not Provided');
}
// remove leading '/' or double slashes (will also hack out http:// injections)
$filename = trim($filename);
$filename = str_replace('//', '/', $filename);
while (strlen($filename) > 0 && strcmp(substr($filename,0,1), '/') == 0) {
$filename = substr($filename, 1);
}
// Check filename exists
if (file_exists('./' . $filename)) { // Note the "./", also will to prevent cross site injections; if using a sub-directory, add in here
die ('file does not exist');
}
// Check file actually is an image
if (!#getImageSize('./' . $filename)) {
die ('file is not an image');
}
// Should be safe at this point.
You could also preg_match for a pattern if you know the pattern of filename e.g. always expecting a .png).
You probably also want to handle errors differently, but this should give you an idea.
Yes, Its safe to use. But you want to take care of XSS attacks.
Actually now you are showing the content attached to your parameter show inside your html page. Think a scenario if a user edited the 'cat.jpg' and inserted some script content into it.
See this simple example by Arjun Sreedharan.
XSS attack to your url would be as shown below
index.php?letter=1&show=Path/To/some/other/Image"></img><h1>XSS Attack</h1><div> Showing False data in your website</div><img src="Some/Other/Image.jpg
The Html rendered in your page would be
<img src="Path/To/some/other/Image"></img>
<h1>XSS Attack</h1>
<div> Showing False data in your website</div>
<img src="Some/Other/Image.jpg">
The solution is to encode html. HtmlEntities in PHP.
Yes, it is safe but the mechanism to deliver/show that file should be proper to handle only authorized requests.
If you want then you can do it by POST, but some time its possessive when you refresh the page and browser asking to confirm that previously posted data sends back to server again.
Above are my personal view.
I'd say get something like image_id from URL and then retrieve the relevant data from database and output your own data (e.g. file name) in the markup.
Even if you consider different ways of validating or filtering the users' input, you might still be open to some attacks or maybe bugs. To avoid that, again, I'd recommend to get a key from user and then based on that key output the data. Validating that key is much easier and also you are not gonna to output it again -- you're using that only in the back-end so it won't be a security hole for XSS attacks for example.
<img src="/images/<?php echo basename(preg_replace('/[^a-z0-9\.-]/i','',$_GET['show'])); ?>">
This will this will only return name of a file even if path or url is passed.

using href to two links(php and a webpage) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
While($enreg=mysql_fetch_array($res))
{
$link_d.="<font color=\"red\">clic here to download</font></td>"
}
i want to use the href so it leads to download link, also to send the id to a php file so i can get how many times the files have been downloaded !
How can we use href to multiple links !
You can't. A link can only point to one resource.
Instead, what you should do is have your PHP script redirect to the file. The link points at your PHP script with the counter, and then set a Location: header (which automatically sets a 302 status code for redirection) with the value being the URL you want to redirect to.
Also, you should really use htmlspecialchars() around any variable data you use in an HTML context, to ensure you are generating valid HTML.
Ideally you would have some checks to see if it's a human downloading (Web crawlers may trigger it - we will put no-follow in the link which will help though). You could also use a database but that gets more complicated. My preferred way would be to use Google Analytics Events. But here is a simple PHP script that might fulfill your needs without the complexity of the other solutions.
First modify your links to have a tracker script and to urlencode
$link_d.= '<a style="color:red" href="tracker.php?url='.urlencode($enreg[link]).'" target="_blank">click here to download</a>';
}
Then create a script that will record downloads (tracker.php)
<?php
// keep stats in a file - you can change the path to have it be below server root
// or just use a secret name - must be writeable by server
$statsfile = 'stats.txt';
// only do something if there is a url
if(isset($_GET['url'])) {
//decode it
$url = urldecode($_GET['url']);
// Do whatever check you want here to see if it's a valud link - you can add a regex for a URL for example
if(strpos($url, 'http') != -1) {
// load current data into an array
$lines = file($statsfile);
// parse array into something useable by php
$stats = array();
foreach($lines as $line) {
$bits = explode('|', $line);
$stats[(string)$bits[0]] = (int)$bits[1];
}
// see if there is an entry already
if(!isset($stats[$url])) {
// no so let's add it with a count of 1
$stats[$url] = 1;
} else {
// yes let's increment
$stats[$url]++;
}
// get a blank string to write to file
$data = null;
// get our array into some human readabke format
foreach($stats as $url => $count) {
$data .= $url.'|'.$count."\n";
}
// and write to file
file_put_contents($statsfile, $data);
}
// now redirect to file
header('Location: ' . $url);
}
You can't.
Anchor are meant to lead to one ressource.
What you want to do is tipically addressed by using an intermediate script that count the hit and redirect to the ressource.
eg.
Click here to download
redirect.php
// Increment for example, a database :
// UPDATE downloads SET hits = (hits + 1) WHERE id=42
// Get the URI
// SELECT uri FROM downloads WHERE id=42
// Redirect to the URI
// (You may also need to set Content-type header for file downloads)
header( "Location: $uri" );
You may optimize this by passing the uri as a second parameter so that you won't need to fetch it at redirect time.
Click here to download
Another way of collecting this kind of statistics is to use some javascript tools provided by your statistics provider, like Google Analytics or Piwik, adding a listener to the click event.
It is less invasive for your base code but won't let you easily reuse collected data in your site (for example if you want to show a "top download" list).
Create a file with download script for example download.php and route all your downloads through it. Update your counter in this page and use appropriate headers for download.
eg:
url may be download.php?id=1&file=yourfile
in download.php
//get id and file
//database operation to update your count
//headers for download

Categories