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

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;
}

Related

Allow unique $_GET request only? Generate, verify, forbid values [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
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;
}

Admin restrinction fails from an irrelevant function

I have this piece of code in PHP web app.
if (isset($require_admin) && $require_admin) {
if(!check_admin()) {
$toolContent_ErrorExists = $langCheckAdmin;
$errorMessagePath = "../../";
}
}
The normal behavior is that if the variable $require_admin is set and true,the code will check if the visit is by the admin.
I try to add a similar piece of code some lines below so as to make other things like checking for cross-origin(especially CSRF) requests.
if (isset($require_token) && $require_token) {
if( !checkToken( $mycsrf_token, $myform)) {
$toolContent_ErrorExists = $langCheckToken;
$errorMessagePath = "../../";
}
}
I had in mind that in this way i will have a check that the posted forms I get are valid and if no,there would be an error message.
However,when $require_token is set and true,and the condition is verified i have a very strange result.Not only nothing happens for the csrf validation,but the above function stops working properly and admin restriction stops to work.
I know the question maybe is ambiguous but I cannot get what's going on there.I'm not so experienced on web programming and totally new in PHP so maybe someone could have a better idea!

Fast way to see if a domain is in use or registered using PHP [duplicate]

This question already has answers here:
How do I run a WHOIS lookup with PHP or Python?
(7 answers)
Closed 6 years ago.
I am looking for a fast wat to test if a domain name is in use, hence has a site attached to it. I have a huge list of domain names and need to check which ones have a site attached to it or not.
If I know that there is a site attached to it then I don't need to do any time consuming whois lookups, etc.
My initial idea was to check for HTTP header code and see if the header codes return 200, 301, 302... if is is something else there is a high chance that there is no site attached or that the domain name is available. The code snipper I am using is:
$headers = #get_headers( $url);
$headers = (is_array($headers)) ? implode( "\n ", $headers) : $headers;
return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
However this process is pretty slow.
Next I've tried using the PHP function checkdnsrr to check if a DNS record exist. I am using the following code snipper.
if (checkdnsrr($domain . ".", "A") == false) {
echo "Domain might be available";
} else {
echo "Domain is in use";
}
Unfortunately it gives me a lot of "false" information saying that the domain might be available. The same goes for the following code snippet:
if (gethostbyname($domain) != $domain) {
echo "DNS Record found";
} else {
echo "NO DNS Record found";
}
A WHOIS lookup is a possibility also however with all the new TLD (.frl, .xyz, etc.) this might be a huge task to setup.
Another idea I had was to ping the domain name in question and if I get a response I know the domain name is "in use". Not sure if this is the best approach therefor I am asking you is there a a fast but more reliable way to check if domain is in use (or registered)?
You could try parse "http://whois.domaintools.com/" . $domain
and look for the keyword "Domain Available"

PHP $_SERVER['REMOTE_ADDR'] no longer giving users ipaddress as expected?

Before PHP 5.4 when running retrieving the users IPAddress using $_SERVER['REMOTE_ADDR'] the result would be the users external IPV6 IPAddress.
EG: 60.123.456.168
However since updating my server to PHP 5.4 the returned users IPAddress seems to be their internal IP:
EG: 192.168.1.34
This becomes an issue if you want a specific office or 'router' to see a particular group of content or in our case debug code.
I tried using the other IP option $_SERVER['HTTP_X_FORWARDED_FOR'] but this isn't available on all servers.
Is their another way to grab the users external ipaddress in PHP >= 5.4 or has this functionality been removed?
this even checks for proxy servers and still reveal correct user ip
<?php
function get_real_ip()
{
if (isset($_SERVER["HTTP_CLIENT_IP"]))
{
return $_SERVER["HTTP_CLIENT_IP"];
}
elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_X_FORWARDED"]))
{
return $_SERVER["HTTP_X_FORWARDED"];
}
elseif (isset($_SERVER["HTTP_FORWARDED_FOR"]))
{
return $_SERVER["HTTP_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_FORWARDED"]))
{
return $_SERVER["HTTP_FORWARDED"];
}
else
{
return $_SERVER["REMOTE_ADDR"];
}
}
$IP_Address = get_real_ip();
echo $IP_Address
?>
It is not PHP's fault. PHP doesn't detect anything but just reading environment variable.
You have some proxy probably, that is not properly configured.
Ok,
Figured out this issue appears to be due to our Newb server setup.
As the server was in fact running from a localhost and networked through Windows (I wasn't aware it was till now).
This explains why the Local IPAddress was coming up.
False alarm :)
Thanks everyone for your help though!

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