Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I'm looking to stop image leeching on my server by using a fancypants URL hiding script.

I have images on a few different image servers and I am looking to hide the URL of them by doing something like the SA's attachment.php image output script where showimage.php outputs the image data and showimage.php checks whether it's pulling the file from one of my scripts, if it's true - it outputs the image data.

[index.php]

<img src="showimage.php?server=2&filename=sweet.jpg">

[/index.php]


Any help or pointer towards this would be appreciated.

Adbot
ADBOT LOVES YOU

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
How do I get the data of say, http://55.55.55.55/image.jpg or http://myimageserver.com/image.jpg into $imagedata?

php:
<?php
ob_start();
$imagedata how_do_i_get_data("http://blah.com/image.jpg");
$length strlen($imagedata);
header('Last-Modified: '.date('r'));
header('Accept-Ranges: bytes');
header('Content-Length: '.$length);
header('Content-Type: image/jpeg');
print($imagedata);
ob_end_flush();
?>

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

LOL AND OATES posted:

if cURL isn't enabled, use file_get_contents:
php:
<?php
$file file_get_contents'http://path/.jpg' );
header'Content-Type: image/jpeg' ); 
echo $file;
?>


Thank you. For my purposes and level of PHP, this works perfect.

I am now streaming images from my site from multiple servers seamlessly, whilst hiding the IP of the servers.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Without setting a cookie, session or global variable, I need to pass a variable from index.php to a PHP script included as an image.
eg
php:
<?
// index.php
global $inIndex = true;

[code]

<img src='showImage.php?param1=yay&param2=wee'>
?>
php:
<?
// showImage.php
global $inIndex;

if ($inIndex == true)
 { //show real image }
else
 { //show fuckoff.jpg }
?>

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

Mashi posted:

Check the value of $_SERVER['HTTP_REFERER'] and deny access

Ahh yes of course, thank you.

If nobody chimes in with the way I originally planned I'll do that.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I was using ip2c (free IP to country database) for a while until it broke. Even the new version keeps breaking, I pasted the errors on pastebin.

Has anybody experienced this too, or any idea why?

The PHP files DO point to the database files correctly, which confused me.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

er0k posted:

Looks like you are using a relative path (fopen(../ip-to-country.bin)), do you still get the errors when you use an absolute path?

Failing that, maybe try Maxmind's GeoIP database, it's been working great for me.

sample.php, geoip.inc, GeoIP.dat all in the same dir (domain.com/ip2c)
path in sample.php is correct:

$gi = geoip_open("/home/removed/public_html/ip2c/GeoIPCity.dat",GEOIP_STANDARD);

Still not working:


Warning: fopen(/home/removed/public_html/ip2c/GeoIPCity.dat) [function.fopen]: failed to open stream: No such file or directory in /home/removed/public_html/ip2c/geoip.inc on line 314

Line 314 just includes the var $gi


EDIT: Fixed, standard file in the code is GeoIPCity.dat, I just had GeoIP.dat.

Safety Shaun fucked around with this message at 17:28 on Jun 25, 2008

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I've been browsing and I can't make sense of how to get my CSV file into an array so I can begin working with the data in the script.

The file is uploaded fine and the location of the file is in $file, I then want something like $Col1[0] $Col2[0] and $Col3[0] respectively with the 200 or so rows that are in the file.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

jasonbar posted:

http://us3.php.net/fgetcsv should do the trick.

Excellent!

Now I have this output:
php:
<?
$row = 1;
$handle = fopen($loc, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
}
fclose($handle);
?>
php:
<?
 3 fields in line 1:
STRING 1
STRING 2
STRING 3

3 fields in line 2:
STRING A
STRING B
STRING C
?>
How do I say, echo out only "STRING 3"

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

fletcher posted:

Your first question could have been answered by googling "php csv" (fgetcsv is the FIRST RESULT). Now you have copied and pasted the example code from that page and asked another extremely basic question that you should be able to figure out on your own. Either pay somebody to write this script for you or actually take the time to learn how to write it.
I'm learning. So gently caress off jerkbag.

This is a place for people to ask for help and some people are very helpful.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

DaTroof posted:

Come on, man. You're not even trying. Your previous post seems to indicate that you know how an array works, so how can you not be able to figure out what you want to do from the example you copied?

Here's a hint: $data is an array of the columns.

Thank you. I'm not sure if this was the easiest way to go about it but it works for me:
php:
<?
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    
    $row++;
    
    for ($c=0; $c < $num; $c++) {
        
    $entry[$row-1][$c+1] = $data[$c];   //this line
    }
}
?>
So I can call entry[1][2] for row 1, column 2.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I'm creating a little quiz script and I'm looking for ideas on how I can ask the database if the answer they have clicked on is correct without transmitting any visable indication in the source that he should click a certain one.

My database fields (that we'll use in this query) are
q_id (Unique ID of that question)
q_question (The question at hand)
q_correcta (The correct answer)
q_seconda (A wrong answer)
q_thirda (Another wrong answer)
q_fourtha (The last wrong answer)

I could transmit the answer back
php:
<?
<input type="button" value="Answer Here">?>
and compare that field to the correcta on submission, but I'm assuming it will start spitting out "wrong answer" messages when the correct answer is clicked if the answer contains certain characters. At the moment the desisn is using one form, with 4 submit buttons but I feel to pass the necesary information on, I'd need to use 4 forms, 4 buttons.

Would I need to have a variable inside each form with an md5 of the answer like so (x4)
php:
<?
<form method="POST">
    <input type="hidden" name="answer" value="xxxxxMD5HERExxxxx">
    <input type="submit" name="Answer1" value="This Is Answer 1"></p>
</form>?>
Can anybody point me in a direction of a simpler solution or clarify that I am indeed heading in the right direction before I over complicate this even more?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Thanks for the pointers sirs, now I have another annoyance.

The more questions they answer, the more likely it is that a question they've already answered will come up. If I store which q_ids they do in a string inside a cookie or session, is it possible with a simple query to do a

SELECT * FROM questions WHERE q_id != $IN_THIS_ARRAY() ORDER BY rand( ) LIMIT 1

Or something similar?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

stack posted:

code:
SELECT * FROM questions WHERE q_id NOT IN (x, y, z) ORDER BY RAND() LIMIT 1;
Use implode() to turn your array into a comma separated list which I represented above with 'x, y, z'.

Thank you so very very much.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Crap, how do I avoid the header already sent spaz out that PHP has when I retrieve and edit (remove) a cookie in the middle of my script. Simply moving it to the top of this script isn't possible because it's an include and the main index.php is outputted before this is called.

php:
<?
{lots of code}
    $prevcorrect = $_COOKIE["cookiename"];
    setcookie("cookiename", 0, time()-604800, "/", ".mydomain.co.uk", 0);
{lots of code}
?>
Or would it be a lot more simple to set a session in the other script, then destory the session here; or would I come up with the same problem?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

MrEnigma posted:

Sessions would fix this, but they also do not persist for a user when they come back (although you could somehow use a cookie to reactivate a session...or other craziness like that).

A cookie has to be sent in the headers, which means it has to go before any output. This means, you'll either need to figure out a way to get that cookie set at the top of the page (or on a new page), or you need to output buffer the page.

Either way I'll have to recode index.php to and call cookies and/or initiate the session at the top. I'll play around with buffer.

The value is only passed from one page to the other but using session/cookie to avoid any interference with the value. Is there any way I can set the variable in this script, redirect, then request the variable data from the previous page without having to submit a 'form'.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

Zorilla posted:

Yeah, really do try to separate your code from your templating as much as possible by getting most of your code out of the way before output happens. I know it's not totally possible short of using something like Smarty because of stuff like database result loops which end up in the middle of the page, but it does make it much easier to manage things that need to be done before the header gets sent out.

I will try that in future, thanks for the advice. Although I am still learning, I'm pretty confident what I am coding now (with assistance from you guys) is going to work pretty well. I appreciate all the pointers you guys have given me so far.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
$q_image = str_replace('\', '/', $q_image);
and
$q_image = str_replace("\", "/", $q_image);
are messing up for me, is there any way I can replace slashes?
It's changing a local path of an image into a location of an image on the server

Safety Shaun fucked around with this message at 23:00 on Aug 6, 2008

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
{long post about why my include() was broken}

I fixed it but thank you.

Safety Shaun fucked around with this message at 03:32 on Aug 30, 2008

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
code:
rewriteEngine on
RewriteCond %{HTTP_HOST} ([^.]+)\.url.com [NC]
RewriteRule ^(.*) [url]http://url.com/index.php?subdomain=[/url]%1 [P]
I'm using the above htaccess to make all subdomains point to the root index.php and it's working fine.

I need to pass any further variable on, say http://penis.url.com/testicles as rewriterule http://url.com/index.php?subdomain=%1&switch=%2 - can you fine gentlemen offer me any assistance?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I have a huge table of articles I've posted on one of my personal sites and each entry has a tags field as such

art_id, art_name, art_cont, art_tags
1, "title of article 1", "content of article 1", "hello, wooop, omnomnom"
2, "title of article 2, "content of article 2", "jello shots, canabis, gaysex"
3, "title of article 3, "content of article 3", "jello shots, canabis, robin hood"
4, "title of article 4, "content of article 4", "canabis, woop, something else, craigslist"

How would I create an array of all the tags, ordered by any more commonly used ones first? Would I implode them all into a tags array, order by somthing then use an array function to remove dupes? or is there some mythical magical MySQL command that'll accomplish this for me?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I have some returned XML data in $xml using simplexml_load_file() and I want to extract $someTitle from it from $xml->a->b->c->d->Title , how would I go about doing so?

Thanks in advance

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Is there any logical reason why
php:
<?
    function getFileList($directory) 
    {
        $dir = $_SERVER['DOCUMENT_ROOT']."/files/";    
        $results = array();
        $handler = opendir($directory);

        while ($file = readdir($handler))
        {
            if ($file != '.' && $file != '..')
            {
                $fullpath = $dir . $file;
                $results[]["filename"] = $file;
                $results[]["writetime"] = filemtime($fullpath);
                $results[]["size"] = filesize($fullpath);
            }
        }

        closedir($handler);
        return $results;

    }

    $dir = $_SERVER['DOCUMENT_ROOT']."/files/";
    $results = getFileList($dir);
        
    foreach ($results as $value)
    {
        $filename = $value["filename"];
        $writetime = $value["writetime"];
        $filesize = $value["size"];
        
        echo "$filename time:$writetime size:$filesize <br>";
    }
?>
is spitting out this exact formatting:
code:
Windows7Screenshot2.png time: size:
time:1241826449 size:
time: size:1805257
20090610_L_Hai.jpg time: size:
time:1244660004 size:
time: size:78007
Here.jpg time: size:
time:1241826333 size:
time: size:95370
Rainbow Books.txt time: size:
time:1241826915 size:
time: size:341
Windows7Screenshot.png time: size:
time:1241826406 size:
time: size:693221
walk.png time: size:
time:1242253484 size:
time: size:1245853
DataSorting.cs.txt time: size:
time:1241826325 size:
time: size:6219 

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

Supervillin posted:

$results[] assigns the value to the next index in the $results array, even if you're actually storing something in a subarray.

Thanks Supervillin, all sorted.

php:
<?
        $currentfile = 0;
        
        while ($file = readdir($handler))
        {
            if ($file != '.' && $file != '..')
            {
                $fullpath = $dir . $file;
                $results[$currentfile]["filename"] = $file;
                $results[$currentfile]["writetime"] = filemtime($fullpath);
                $results[$currentfile]["size"] = filesize($fullpath);
                $currentfile++;
            }
        }
?>

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
A few days ago I decided to see what type of neat text encryption PHP can do.

I stumbled upon this and within the same execution cycle it works fine:
php:
<?
   //encrypt3.php?key=balls&text=i like to move it move it
    $key_value = $_REQUEST["key"];
    $plain_text = $_REQUEST["text"];
    echo "key = '$key_value' and text = '$plain_text'<br>";
    $encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT);
    echo "encrypted text = '$encrypted_text'<br>";
    $decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT);
    $decrypted_text = trim($decrypted_text);
    echo "decrypted text = '$decrypted_text'";?>
shows the output
code:
key = 'balls' and text = 'i like to move it move it'
encrypted text = ''}OXh׍P:|V.{'
decrypted text = 'i like to move it move it'
But as soon as I start submitting it with a html form with encrypted text, funny things start happening, here's my form code: http://pastebin.com/m77339235

Comparing the output of my test script with the output from my main form, it's encrypting fine. It just seems the special characters aren't being transmitted to the server correctly when deycrpting. Could anybody please give me pointers why?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

gibbed posted:

I wouldn't spit out raw binary to a browser for it to resubmit, you should probably encode it somehow (base64, for example).

Thank you, that worked a treat!

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I'm messing around with the Google Maps API and Google's Latitude and wondered how I would construct a regex to return only "latitude_e6=[NUMBERS-INCLUDING-MINUS-SIGN]&longitude_e6=[NUMBERS-INCLUDING-MINUS-SIGN]" from the fopen() results. Possibly even throw those values into their own variables.

Thank you in advance

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Sorry for not explaining myself correctly. The GPS location is in the source of the body I am retriving, not the URL.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

royallthefourth posted:

What does the file look like?
php:
<?
        $handle = fopen("http://www.google.com/latitude/apps/badge/api?user=99999999999999&type=iframe&maptype=hybrid&z=20", "rt");
        $contents = '';
        while (!feof($handle)) {
          $contents .= fread($handle, 8192);
        }
        fclose($handle);
?>
The source returned in $contents is a mixture of HTML and Javsascipt but the substring I want only exists once in the whole string.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

Munkeymon posted:

Use preg_match

Thanks but I'm having trouble getting it to work.

Here is a snippet of the returned string with the actual GPS location changed slighly.

code:
setTop(e('belowPromo')) - calculateOffsetTop(e('abovePromo')));
var mapWidth = getWindowWidth() - (16);
e('map').src = "http://www.google.com/mapdata?latitude_e6=51741341&longitude_e6=-231444&w=0&h=0&hl=en&zl=-3&cc=us&tstyp=3".replace(/&w=\d+/, "&w=" + mapWidth).replace(/&h=\d+/, "&h=" + mapHeight);
e('map').width = mapWidth;
e('map').height = mapHeight;

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

Munkeymon posted:

Oh, sorry, I just assumed they would be floats for some reason.

Thanks so far, sir.

[php] $pattern = "/latitude_e6=(-?\d+(?:\.\d+)?)/";
preg_match($pattern, $contents, $matches);
//print_r($matches);
$lat = $matches[1];
[php]
This prints out the value as an integer, is there anything I am wrong?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

Munkeymon posted:

If you make your own test data with decimal places you should see the difference.
My output is this:
code:
Array ( [0] => latitude_e6=13744341 [1] => 13744341 ) Array ( [0] => longitude_e6=-132443 [1] => -132443 ) 
Co-ordinates are lat,long 13744341,-132443

Safety Shaun fucked around with this message at 22:36 on Jul 21, 2009

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

royallthefourth posted:

I'm pretty sure parse_url will do this without any need for regexes. It doesn't actually need to be a URL, it'll take anything formatted key1=value1&key2=value2

I tried but this is regexing the source of a requested URL which contains HTML and Javascript.

Why oh why is it returning it as an integer?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

FeloniousDrunk posted:

Because the matched part is really returned elsewhere... like so:
I've just realised, stupidly, that google is returning to me a latitude_e6, which is an integer version of the floating point number I actually want. Has anybody experienced this before?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
php:
<?
$myArray = $_REQUEST["myArray"];
print_r($myArray); //prints the contents fine
//^^^ Array ( ['someVar1'] => text woo ['someVar2'] => text wee ['someVar3'] => text omg ['someVar4'] => ['someVar5'] => ) 
echo "test: alias = " . $myArray['someVar1']. "<br>"; //blank?
?>
What am I doing wrong please? the array is bring passed across from the form on the previous page and print_rd properly but I am having trouble using those array entities.

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I coded myself a silly little script to get data from amazon web services after inputting my ISBNs, to store the data in a mysql table but I am looking to extract the category information and require a bit of assistance on pulling this from the XML which is returned.

Here is the full XML return with the useless nodes closed: http://pastebin.com/MWM8syA1
and here is the specific item of categorisation I'd like: http://pastebin.com/L68X6hx0 but I am not sure if that is always returned in the same position within <BrowseNodes>

Or alternatively, how so I extract $xml->Items->Item->BrowseNodes and his children?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
php:
<?
 // inside some_function() inside some_function_file.php
$response = file_get_contents($request);
    
    if ($response === False)
    {
    echo "Response was false (msg1)<br>";
        return False;
    }
    else
    {
        // parse XML
        $pxml = simplexml_load_string($response);
        if ($pxml === False)
        {
        echo "xml parsing bad (msg2)<br>";
        return False; // no xml
        }
        else
        {
        echo "xml parsing good (msg3)<br>";
        return $pxml;
        }
    }?>
When I am including some_function_file.php from within some_file.php, the above returns okay (msg3).

But when I am including some_function_file.php from within some_file.php, which is being included in index.php, it returns msg1 and fails to respond from the file_get_contents. in php.ini, 'allow_url_fopen = On' is set. Any ideas, please?

Safety Shaun
Oct 20, 2004
the INTERNET!!!1

qntm posted:

I imagine file_get_contents() searches different directories based on where the original calling script is located. Are some_file.php and index.php located in different directories?

Correct
\index.php
- include('\includes\some_file.php');
\includes\some_file.php
- require('some_functions.php)
- calls some_function() from^
\includes\some_functions.php

edit: File get contents pulls a URL which returns XML data.

Safety Shaun fucked around with this message at 00:04 on Apr 20, 2011

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
Thanks guys. The I am getting is a URL from a XML based web service.

I've been echoing crap out everywhere to see where my data isn't being passed, heres what i've found so far.

some_functions.php
- contains some_function(a,b,c,d);
- some_function(a,b,c,d) contains

php:
<?
<snip>
$request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature;
    
// do request
    $response = file_get_contents($request);
    echo "Debug: <a href='$request'>Query</a> = $request (response = $response)<br>";
<snip>
return $someXML?>
returns XML;

some_include.php
- require_once(some_functions.php), calls some_function();
- echos query = fine, response = fine

index.php
- includes some_include.php
- echos query = fine, response = blank

Adbot
ADBOT LOVES YOU

Safety Shaun
Oct 20, 2004
the INTERNET!!!1
I'm not exactly sure what you mean but I found the cURL class, but I am not receiving any errors to indicate i'm doing it wrong or any data back
php:
<?
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, '$request');
        $response = curl_exec ($ch);
        curl_close ($ch);
?>
As per above debug echos, query = fine (accessible and viewable by URL, returns XML to browser), response = blank

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply