Direct PHP file error message if they access it directly - php

i have a php file called "Status.php" which basically allows the person if they use the correct URL
http://konvictgaming.com/status.php?channel=isypie to pull their twitch.tv stream online/offline status, That works perfectly
However i would like it so that if they attempt to access the status.php file directly
http://konvictgaming.com/status.php
It will return the error
ERROR: Please put a stream user in your link.
ex: http://konvictgaming.com/status.php?channel=konvictgaming
my current code
<?php
$channelName = htmlspecialchars($_GET['channel'], ENT_QUOTES);
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
header("Content-Type: image/png");
$image = null;
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
$image = file_get_contents($online);
} else {
$image = file_get_contents($offline);
}
echo $image;
?>

Just add a check at the beginning of your script:
if(empty($_GET['channel']))
die('ERROR: Please put a stream user in your link. ex: http://konvictgaming.com/status.php?channel=konvictgaming');

Related

Base64_decoded image string saved to directory doesn't show image

I am trying to upload an image from my android application to a php script on my server. In my script, I am attempting to decode the image (using base64_decode) and then use file_put_contents() to save the image as a file in my directory. My problem is that the file 'appears' empty when I have .jpg at the end of the file name. When I removed that to see what was added for the image encoding, I see a very long string of characters, (65214 bytes specifically that were written to the file). When I run the code again, only this time uploading the $_POST['sent_image'] without decoding, I get the same exact string of text.
I am not sure what I am doing wrong... The end goal would be to save the image on the server, so it could be viewed elsewhere online, and also be able to retrieve it and get back into another activity in my android application.
All suggestions are appreciated!
NOTE: I have also tried imagecreatefromstring(), but that causes 0 bytes to be written.
My Code:PHP that gets encoded android image and tries to save to server directory:
<?php
include('inc.php');
if ((isset($_POST['searchinput'])) && (isset($_POST['newUnitStatus'])) && (isset($_POST['generalCause'])) && (isset($_POST['newUnitStatusComment'])) && (isset($_POST['newUnitStatusPhoto'])) && (isset($_POST['lexauser'])) && (isset($_POST['password']))) {
$sgref = "";
$searchinput = $_POST['searchinput'];
$newUnitStatus = $_POST['newUnitStatus'];
$generalCause = $_POST['generalCause'];
$newUnitStatusComment = $_POST['newUnitStatusComment'];
$lexauser = $_POST['lexauser'];
$pass = $_POST['password'];
if ((strpos($searchinput, "/") !== false)) {
$barcodesplit = preg_split('/\D/im', $searchinput, 4);
$sgref = $barcodesplit[0];
$lineitem = $barcodesplit[1];
$unitnumber = $barcodesplit[2];
$totalunits = $barcodesplit[3];
$unitname = $sgref."-".$lineitem."-".$unitnumber."_of_".$totalunits;
$photo = $_POST['newUnitStatusPhoto'];
$decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
$decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$fileName = "".$unitname."_rej";
$target = '../LEXA/modules/bms/uploads/';
$newFile = $target.$fileName;
$docType = "Reject";
$success = file_put_contents($newFile, $newUnitStatusPhoto);
if($success === false) {
$response['message'] = "Couldn not write file.";
echo json_encode($response);
} else {
$response['message'] = "Wrote $success bytes. ";
echo json_encode($response);
}
} else {
$sgref = $searchinput;
$response['message'] = "I'm sorry, but you must enter a unit's uniqueid value to add a unit exception. Please view the siblings for this SG and pick the unit you need. Then you can add the new status.";
echo json_encode($response);
}
} else {
$response['message'] = "Your search value did not get sent. Please try again.";
echo json_encode($response);
}//End logic for post values.
?>
Thank you!
Using str_replace may be problematic if image format is other than jpg, for example.
Example code:
<?php
$photo = $_POST['newUnitStatusPhoto'];
if(substr($photo, 0,5) !== "data:"){
//do error treatment as it's not datauri
die("Error: no data: scheme");
};
$decodedPhoto = substr($photo, 5);
$mimeTerminator = stripos($decodedPhoto,";");
if($mimeTerminator === false){
die("Error: no mimetype found");
};
$decodedPhoto = substr($decodedPhoto, $mimeTerminator+8); //1<;>+4<base>+2<64>+1<,>
// $decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
// $decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$unitname = "testando";
$fileName = "".$unitname."_rej.jpg";
$target = 'img/';
$newFile = $target.$fileName;
if(file_exists($newFile))
unlink($newFile);
$success = file_put_contents($newFile, $newUnitStatusPhoto);
echo $success;

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

get meta data of mp3 with getID3 PHP

I'm trying to get the meta data out from my mp3 playlist using PHP and the library getid3, I'm sure the file path is correct and the mp3 has some information on meta data, but the information returns me null.
Here is my code :
<?php
header("Content-type: application/json");
require_once('getid3/getid3.php');
$input = json_decode(file_get_contents("php://input"), true);
$action = $input['action'];
switch ($action)
{
case "get_songs":
$currentDirectory = dirname(dirname(getcwd()));
$directory = $currentDirectory."/resources/assets/playlists/";
$files = glob($directory."*.mp3");
for($i = 0; $i < count($files); $i++)
{
$getID3 = new getID3;
$file = ($files[$i]);
$ThisFileInfo = $getID3->analyze($file);
$Result = array('song_url'=>($files[$i]), "tags"=> $ThisFileInfo);
$data[] = $Result;
}
$result = array("result"=>"ok","data"=>$data);
break;
}
echo json_encode($result);
?>
I know the library is working, because when I force it to access a local file it returns me :
"GETID3_VERSION" = "1.7.4";
error = (
"Could not open file \"AYO.mp3\""
);
Could it be, I cant access files from another path?

How to allow only logged in user to access files in a folder on linux server

I created .htaccess file and place this piece of code in it :
Order Deny,Allow
Deny from all
Here is my php code which is working fine on my windows machine with WAMP SERVER on it :
$path = $data['path']; // complete path to file
if (is_user_logged_in()) {
//return $path;
if (file_exists($path)) {
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
readfile($path);
}
} else {
return 'Welcome, visitor!';
}
But when I run it on server, it didn't work at all. There is a locked folder, in which I have placed .htaccess file. And under locked folder there are many subfolders which I want to limit access to only logged in users.
Your .htaccess file is a (slow) way to stop anyone requesting your files. It does not care if the user is logged in or not.
The approach I would take is to
a) Move the files you want to give logged in access to out of the root. That way no-one can request the path directly - they have to use your php file to get access.
b) In your php file, test if your user is logged in. If not, present them with the log-in screen or error message as appropriate.
c) As they are logged in read the file you want to show them and echo the contents, (or read the data and build the reply page).
I use a another way to download file by loged user (without connect to DB and running all framework...).
First of all, when user is loged a generate special link using: sessionID, pathDir, userId, seprarator "=" and secureKey.
$tx = rand(999,99999).'='.$dirUQ.'='.$user_id.'='.$fileUQ.'='. session_id();
$checkSum = hash('sha256', $tx.$this->keySecure );
$sx = $tx.'='.$checkSum;
Thanks for this I get special param, unique for every user using get download file: /download.php?get_sx=91653%3D1%3D1%3D1655104198_9592081.jpg%3D123e2592526883ebfa426898f09c7c9e%3Dec30217a28a564f24dfed226bf3b37b11e0f6a0d732a98a1cfd598dc7cfe2fb2&gofull=600
change you private secure key
generate params "get_sx" for your files
exectue method "downloadIfAuth" in your index.php file
My PHP Class
class FileSecure {
//put your code here
private $keySecure = '***My_KEY_TO_GEN_LINK';
private $sessionID = '';
public function __construct($get)
{
$this->sessionID = $_COOKIE['PHPSESSID'] ?? '';
}
/**
* check if param get_sx added
*/
public function downloadIfAuth()
{
if(isset($_GET['get_sx']) && $this->sessionID != '')
{
$tx = $_GET['get_sx'];
$params = explode('=', $tx);
if(count($params) == 6)
{
$rand = $params[0];
$dirUQ = $params[1];
$px_user_id = $params[2];
$fileUQ = $params[3];
$sessionId = $params[4];
$checkSum = $params[5];
$tx2 = $rand.'='.$dirUQ.'='.$px_user_id.'='.$fileUQ.'='. $this->sessionID;
$checkSum2 = hash('sha256', $tx2.$this->keySecure );
if($checkSum == $checkSum2)
{
$path = 'files/'.$dirUQ.'/'.$fileUQ;
if(file_exists($path))
{
$type = #mime_content_type($path);
header('Content-type: '.$type);
header('Content-Length: '.filesize($path) );
header('Content-Disposition: filename='.$fileUQ );
echo file_get_contents($path);
die;
}
}else
{
header('Location: /?crc=false');
die;
}
}
header('Location: /?crc2=false');
die;
}
}
public function getSX( string $dirUQ, int $user_id, string $fileUQ)
{
$tx = rand(999,99999).'='.$dirUQ.'='.$user_id.'='.$fileUQ.'='. session_id();
$checkSum = hash('sha256', $tx.$this->keySecure );
$sx = $tx.'='.$checkSum;
$sx = urlencode($sx);
return $sx;
}
}
How to generate link
$fileSecure = new FileSecure(array());
$imgs = '<img src="/index.php?get_sx='.$fileSecure->getSX("myHomeDir", $this->getUser()->GetId(), "myFile.jpg").'" class="img_browser" >
Put below code to you index.php to check if get_sx is exist
$file = new FileSecure($_GET);
$file->downloadIfAuth();
The most important thing is "$_COOKIE['PHPSESSID']". When browser execute index.php send cookie. Thanks for this, special sum and secureKey we can download file by loged user. And... we don't need to connect to DB.
If you see any bug in my way, please show me :)
Sorry for my english :(

display the content of a folder

I have the following PHP code to display the content of a directory in my website:
<?php
$conn = ftp_connect("host") or die("Could not connect");
ftp_login($conn,"username","password");
if ($_GET['dir'] != null) {
ftp_chdir($conn, "logs/{$_GET['dir']}");
}
else
{
ftp_chdir($conn, "logs");
}
$files = ftp_nlist($conn,"");
foreach($files as $value) {
echo "{$value}";
}
ftp_close($conn);
?>
This is my webpage
When I click on the subdirectory1 or subdirectory2, I get the content of it (some images). Then when I click on one of the images, I get the content of the root directory of my website.
How can I display only the image when a visitor clicks on it? Note that I don't want to download it or anything - I just want to display it in the browser when a visitor clicks on it.
You need to establish which of the returned items are files and which are directories. For that you are better of using ftp_rawlist as it allows to extract more data. Then create links for each case and so you can process them appropriately. Here's a possible implementation:
$ftpHost = 'hostname';
$ftpUser = 'username';
$ftpPass = 'password';
$startDir = 'logs';
if (isset($_GET['file'])) {
// Get file contents (can also be fetched with cURL)
$contents = file_get_contents("ftp://$ftpUser:$ftpPass#$ftpHost/$startDir/" . urldecode($_GET['file']));
// Get mime type (requires PHP 5.3+)
$finfo = new finfo(FILEINFO_MIME);
$mimeType = $finfo->buffer($contents);
// Set content type header and output file
header("Content-type: $mimeType");
echo $contents;
}
else {
$dir = (isset($_GET['dir'])) ? $_GET['dir'] : '';
$conn = ftp_connect($ftpHost) or die("Could not connect");
ftp_login($conn, $ftpUser, $ftpPass);
// change dir to avoid ftp_rawlist bug for directory names with spaces in them
ftp_chdir($conn, "$startDir/$dir");
// fetch the raw list
$list = ftp_rawlist($conn, '');
foreach ($list as $item) {
if(!empty($item)) {
// Split raw result into pieces
$pieces = preg_split("/[\s]+/", $item, 9);
// Get item name
$name = $pieces[8];
// Skip parent and current dots
if ($name == '.' || $name == '..')
continue;
// Is directory
if ($pieces[0]{0} == 'd') {
echo "<a href='?dir={$dir}/{$name}'><strong>{$name}</strong></a><br />";
}
// Is file
else {
echo "<a href='?file={$dir}/{$name}'>{$name}</a><br />";
}
}
}
ftp_close($conn);
}
You'll need to add a function which checks which type of file we're handling.
If it's a directory show the regular link (the one you're using now) and if it's an image
show a link with the path of the image.
Because $value contains the name of the file you can use end(explode('.',$value)); to find the ext. of the file (php , jpg , gif , png).
Use another condition with the piece of information and you can identify if it's a picture or not.
In order to build the path of the image you'll need to use the $_GET['dir'] variable's value.
For instance:
<a href='<?=$_GET['dir']?>/Flower.gif'>Flower.gif</a>
I hope you got the idea.

Categories